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 |
|---|---|---|---|---|---|
#include <stdlib.h> void setkey (key) char *key;
#include <unistd.h> char *crypt (key, salt) const char *key, *salt;
#include <unistd.h> void encrypt (block, flag) char *block; int flag;
#include <crypt.h>
char *des_crypt (key, salt) char *key, *salt;
void des_encrypt (block, flag) char *block; int flag;
void des_setkey (key) char *key;
int run_setkey (p, key) int p[2]; char *key;
int run_crypt (offset, buffer, count, p) long offset; char *buffer; unsigned int count; int p[2];
int crypt_close(p) int p,A-Z,0.
In the international version of crypt(S) a flag argument of 1 to encrypt() or des_encrypt() is not accepted, and errno is set to [ENOSYS] to indicate that the functionality is not available.
crypt, setkey, and encrypt are front-end routines that invoke des_crypt, des_setkey, and des_encrypt respectively.
The routines run_setkey and run_crypt are designed for use by applications that need cryptographic capabilities (such as ed(C) and vi(C)) that must be compatible with the crypt(C) user-level utility. run_setkey establishes a two-way pipe connection with crypt(C), using key as the password argument.
run_crypt takes a block of characters and transforms the cleartext or ciphertext using crypt(C). offset is the relative byte position from the beginning of the file that the block of text provided in buffer is coming from. count is the number of characters in buffer, and p is an array containing file descriptor indices to a table of input and output file streams. When encryption is finished, crypt_close is used to terminate the connection with crypt(C).
crypt and des_crypt return a pointer to the string representing the encrypted password.
run_crypt returns -1 if it cannot write output or read input from the pipe attached to crypt. Otherwise it returns 0.
run_setkey returns -1 if a connection with crypt(C) cannot be established. This occurs on international versions of the Operating System where crypt(C) is not available. If a null key is passed to run_setkey, 0 is returned. Otherwise, 1 is returned.
crypt_close returns 0 if it successfully terminated the connection with crypt(C). Otherwise, it returns -1.
setkey, des_setkey, encrypt, and des_encrypt do not have return values.
X/Open Portability Guide, Issue 3, 1989 . | http://osr507doc.xinuos.com/cgi-bin/man?mansearchword=setkey&mansection=S&lang=en | CC-MAIN-2020-50 | refinedweb | 370 | 64.71 |
On Wed, 2008-09-10 at 18:52 -0300, Leonardo Santagada wrote:
On Sep 10, 2008, at 6:22 PM,.
Two restrictions, both that statements can be used in place of expressions and that statements now return values. But please explain how to do it in a way that is clear. It's a plus if it is backwards compatible :)
Well, one or two, depending on how you word it ;-) My position is to simply do away with statements and provide equivalent expressions.
As far as backwards-compatibility, this is legal Python:
1 2 3
It doesn't do anything, but it is valid syntax. This demonstrates that expressions can be valid when used independent of a statement, therefore, the following is also legal (assuming "if" were now implemented as an expression):
if (a==1): pass.
And now ifs return a value
Which you are not required to use, just as today:
def foo(x): return x**2
foo(2)
Secondly any syntax change won't happen until we start planing Python 4000 ;)
Yes, that's my expectation, although hopefully PyPy will make some of these things possible to experiment with well before then =)
You can do that now in PyPy or any other python version... or maybe use Logix to show us a proof of concept version:
Now if I remeber correctly this is already the case of logix, look at:...
Yes, Logix is quite interesting. Unfortunately the author has discontinued work on it (and was, in fact, unreachable when I last tried to contact him). He also mentioned retargeting to another VM (rather than the Python VM) which made it less appealing to me.
It is interesting that you mention Logix, since it demonstrates that it's quite possible to be backward-compatible with this particular change.
Why would you need lambda then? couldn't you just write x = def (x,y): return x+y ?
Yes, although I suspect that this particular change to "def" would be more substantial and "lambda" is currently equivalent. Although this might satisfy GvR's inclination to dump lambda at some future point ;-)
Cliff | https://mail.python.org/archives/list/python-ideas@python.org/message/YBQ43BDN4ETIN2LKHD27IQEPO3B6F2RU/ | CC-MAIN-2021-17 | refinedweb | 351 | 58.82 |
[ Usenet FAQs | Search | Web FAQs | Documents | RFC Index ]
Search the FAQ Archives
Search the FAQ Archives
-
From: mpcline@nic.cerf.net (Marshall Cline) Newsgroups: comp.lang.c++, alt.comp.lang.learn.c-c++ Subject: C++ FAQ (part 8 of 10) Date: 29 Feb 2000 20:07:15 GMT Message-ID: <89h8tj$bu3$1@news.cerf.net> Reply-To: cline@parashift.com (Marshall Cline) Summary: Please read this before posting to comp.lang.c++ Archive-name: C++-faq/part8 Posting-Frequency: monthly Last-modified: Feb 29, 2000 URL: AUTHOR: Marshall Cline / cline@parashift.com / 972-931-9470 COPYRIGHT: This posting is part of "C++ FAQ Lite." The entire "C++ FAQ Lite" document is Copyright(C)1991-2000 Marshall Cline, Ph.D., cline@parashift.com. All rights reserved. Copying is permitted only under designated situations. For details, see section [1]. NO WARRANTY: THIS WORK IS PROVIDED ON AN "AS IS" BASIS. THE AUTHOR PROVIDES NO WARRANTY WHATSOEVER, EITHER EXPRESS OR IMPLIED, REGARDING THE WORK, INCLUDING WARRANTIES WITH RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE. C++-FAQ-Lite != C++-FAQ-Book: This document, C++ FAQ Lite, is not the same as the C++ FAQ Book. The book (C++ FAQs, Cline and Lomow, Addison-Wesley) is 500% larger than this document, and is available in bookstores. For details, see section [3]. ============================================================================== SECTION [24]: Inheritance -- private and protected inheritance [24.1] How do you express "private inheritance"? When you use : private instead of : public. E.g., class Foo : private Bar { public: // ... }; ============================================================================== [24.2] How are "private inheritance" and "composition" similar? void start() { e_.start(); } // Start this Car by starting its Engine private: Engine e_; // Car has-a Engine }; The same "has-a" relationship can also be expressed using private inheritance: class Car : private Engine { // Car has-a Engine public: Car() : Engine(8) { } // Initializes this Car with 8 cylinders Engine: Note that private inheritance is usually used to gain access into the protected: members of the base class, but this is usually a short-term solution (translation: a band-aid[24.3]). ============================================================================== [24.3][22.4]) in itself, which are overridden by Fred. This would be much harder to do with composition. class Wilma { protected: void fredCallsWilma() { cout << "Wilma::fredCallsWilma()\n"; wilmaCallsFred(); } virtual void wilmaCallsFred() = 0; // A pure virtual function[22.4] }; class Fred : private Wilma { public: void barney() { cout << "Fred::barney()\n"; Wilma::fredCallsWilma(); } protected: virtual void wilmaCallsFred() { cout << "Fred::wilmaCallsFred()\n"; } }; ============================================================================== [24.4] Should I pointer-cast from a private derived class to its base class? Generally, No. From a member function or friend[14]. ============================================================================== [24.5] How is protected inheritance related to private inheritance? Similarities: both allow overriding virtual[20] subclasses of the protected derived class to exploit the relationship to the protected base class) and costs (the protected derived class can't change the relationship without potentially breaking further derived classes). Protected inheritance uses the : protected syntax: class Car : protected Engine { public: // ... }; ============================================================================== [24.6] What are the access rules with private and protected inheritance? Take these classes as examples: class B { /*...*/ }; class D_priv : private B { /*...*/ }; class D_prot : protected B { /*...*/ }; class D_publ : public B { /*...*/ }; class UserClass { B b; /*...*/ }; None of the subclasses so it is public in D_priv or D_prot, state the name of the member with a B:: prefix. E.g., to make member B::f(int,float) public in D_prot, you would say: class D_prot : protected B { public: using B::f; // Note: Not using B::f(int,float) }; ============================================================================== SECTION [25]: Coding standards [25.1] What are some good C++ coding standards? Thank where. ============================================================================== [25.2][26.1],. ============================================================================== [25. Seek out experts who can help guide you away from pitfalls. Get training. Buy libraries and see if "good" libraries pass your coding standards. Do not set standards by yourself unless you have considerable experience in C++. Having no standard is better than having a bad standard, since improper "official" positions "harden" bad brain traces. There is a thriving market for both C++ training and libraries from which to pool expertise. One more thing: whenever something is in demand, the potential for charlatans increases. Look before you leap. Also ask for student-reviews from past companies, since not even expertise makes someone a good communicator. Finally, select a practitioner who can teach, not a full time teacher who has a passing knowledge of the language/paradigm. ============================================================================== [25.4] What's the difference between <xxx> and <xxx.h> headers? [NEW!] [Recently created thanks to Stan Brown (on 1/00).]yz.h> versions make them available both in std namespace and in the global namespace. The committee did it this way so that existing C code could continue to be compiled in C++, however the <xyz.h> versions are deprecated, meaning they are standard now but might not be part of the standard in future revisions. (See ISO clause D and subclause [25.8]. ============================================================================== [25): cout << funct(); // Not as good (emphasizes the minor goal -- a function call): functAndPrintOn cout: int n = /*...*/; // number of senders // Preferred (emphasizes the major goal -- printing): cout << "Please get back to " << (n==1 ? "me" : "us") << " soon!\n"; // Not as good (emphasizes the minor goal -- a decision): cout << "Please get back to "; if (n==1) cout << "me"; else cout << "us";. ============================================================================== [25.6]. ============================================================================== [25.7] What source-file-name convention is best? foo.cpp? foo.C? foo.cc? If you already have a convention, use it. If not, consult your compiler to see what the compiler expects. Typical answers are: .C, .cc, .cpp, or .cxx (naturally the .C extension assumes a case-sensitive file system to distinguish .C from .c). We've often used both .cpp for our C++ source files, and we have also used .C. In the latter case, we supply the compiler option forces .c files to be treated as C++ source files (-Tdp for IBM CSet++, -cpp for Zortech C++, -P for Borland C++, etc.) when porting to case-insensitive file systems. None of these approaches have any striking technical superiority to the others; we generally use whichever technique is preferred by our customer (again, these issues are dominated by business considerations, not by technical considerations). ============================================================================== [25. ============================================================================== [25 String, and += has to reallocate/copy string memory, it may be better to know the eventual length from the beginning). ============================================================================== [25.10] Which is better: identifier names that_look_like_this or identifier names thatLookLikeThis? LETTRS.) So there is no universal standard. If your organization has a particular coding standard for identifier names, use it. But starting another Jihad over this will create a lot more heat than light. From a business perspective, there are only two things that matter: The code should be generally readable, and everyone in the organization should use the same style. Other than that, th difs r minr. ============================================================================== [25.11] Are there any other sources of coding standards? Yep, there are several. Here are a few sources that you might be able to use as starting points for developing your organization's coding standards: * * [The old URL is <> if anyone knows the new URL, please let me know] * * v2ma09.gsfc.nasa.gov/coding_standards.html * fndaub.fnal.gov:8000/standards/standards.html * cliffie.nosc.mil/~NAPDOC/docprj/cppcodingstd/ * * groucho.gsfc.nasa.gov/Code_520/Code_522/Projects/DRSL/documents/templates/cpp_style_guide.html * * The Ellemtel coding guidelines are available at - [The old URL is <> if anyone knows the new URL, please let me know] - [The old URL is <> if anyone knows the new URL, please let me know] - [The old URL is <> if anyone knows the new URL, please let me know] - [The old URL is <> if anyone knows the new URL, please let me know] - Note: I do NOT warrant or endorse these URLs and/or their contents. They are listed as a public service only. I haven't checked their details, so I don't know if they'll help you or hurt you. Caveat emptor. ============================================================================== SECTION [26]: Learning OO/C++ [26.1] What is mentoring? It's the most important tool in learning OO. Object-oriented developer"). ============================================================================== . ============================================================================== [27.3], non-subtyping inheritance[27.1]. ============================================================================== [26.4] Should I buy one book, or several? At least two. There are two categories of insight and knowledge in OO programming using C++. You're better off getting a "best of breed" book from each category rather than trying to find a single book that does an OK job at everything. The two OO/C++ programming categories are: * C++ legality guides -- what you can and can't do in C++[26.6]. * C++ morality guides -- what you should and shouldn't do in C++[26.5].: * Neither of these categories is optional. You must have a good grasp of both. * These categories do not trade off against each other. You shouldn't argue in favor of one over the other. They dove-tail. ============================================================================== [26.5] What are some best-of-breed C++ morality guides? Here's my personal ++,. ============================================================================== . ============================================================================== [26.7] Are there other OO books that are relevant to OO/C++? Yes! Tons! The morality[26.5] and legality[26. ============================================================================== [26.8] But those books are too advanced for me since I've never used any programming language before; is there any hope for me? Yes. There are probably many C++ books that are targeted for people who are brand new programmers, but here's one that I've read: Heller, Who's afraid of C++?, AP Professional, 1996, ISBN 0-12-339097-4. Note that you should supplement that book with one of the above books and/or the FAQ's sections on const correctness[18] and exception safety[17] since these topics aren't highlighted in that book. ============================================================================== SECTION [27]: Learning C++ if you already know Smalltalk [27.1] What's the difference between C++ and Smalltalk? Both fully support the OO paradigm. Neither is categorically and universally "better" than the other[6.4]. But there are differences. The most important differences are: * Static typing vs. dynamic typing[27.2] * Whether inheritance must be used only for subtyping[27.5] * Value vs. reference semantics[28] Note: Many new C++ programmers come from a Smalltalk background. If that's you, this section will tell you the most important things you need know to make your transition. Please don't get the notion that either language is somehow "inferior" or "bad"[6.4], or that this section is promoting one language over the other (I am not a language bigot; I serve on both the ANSI C++ and ANSI Smalltalk standardization committees[6.11]). Instead, this section is designed to help you understand (and embrace!) the differences. ============================================================================== [27.2] What is "static typing," and how is it similar/dissimilar to Smalltalk? Smalltalk (dynamically typed) catches the error at run-time. (Technically speaking, C++ is like Pascal --pseudo statically typed-- since pointer casts and unions can be used to violate the typing system; which reminds me: only use pointer casts and unions as often as you use gotos). ============================================================================== [27.3] Which is a better fit for C++: "static typing" or "dynamic typing"? [UPDATED!] [Recently added cross references to evilness of macros (on 3/00).] [For context, please read the previous FAQ[27.2]]. If you want to use C++ most effectively, use it as a statically typed language. C++ is flexible enough that you can (via pointer casts, unions, and #define macros) make it "look" like Smalltalk. But don't. Which reminds me: try to avoid #define: it's evil[9.3], evil[34.1], evil[34.2], evil[34). ============================================================================== [27.4] How do you use inheritance in C++, and is that different from Smalltalk?;[22.3]). The C++ compiler exploits the added semantic information associated with public inheritance to provide static typing. ============================================================================== [27.5] What are the practical consequences of differences in Smalltalk/C++ inheritance? [For context, please read the previous FAQ[27.4]]. Smalltalk lets you make a subtype that isn't a subclass, and allows you to make a subclass that isn't a subtype. This allows Smalltalk subclasses. Therefore you're usually better off not putting the data structure in a class. This leads to a stronger reliance on abstract base classes[22.3]. I like to think of the difference between an ATV and a Maseratti. An ATV (all terrain vehicle) is more fun, since you can "play around" by driving through fields, streams, sidewalks, and the like. A Maseratti,. ============================================================================== SECTION [28]: Reference and value semantics [28.1]. ============================================================================== [28.2]ableArray's constructor would provide a new StretchableArray to this special constructor. Pros: * Easier implementation of StretchableStack (most of the code is inherited) * Users can pass a StretchableStack as a kind-of Stack Cons: * Adds an extra layer of indirection to access the Array * Adds some extra freestore allocation overhead (both new and delete) * Adds some extra dynamic binding overhead (reason given in next FAQ) In other words, we succeeded at making our job easier as the implementer of StretchableStack, but all our users pay for it[28.5]. Unfortunately the extra overhead was imposed on both users of StretchableStack and on users of Stack. Please read the rest of this section. (You will not get a balanced perspective without the others.) ============================================================================== [28.3] What's the difference between virtual data and dynamic data? The easiest way to see the distinction is by an analogy with virtual functions[20]: A virtual member function means the declaration (signature) must stay the same in subclasses, but the definition (body) can be overridden. The overriddenness of an inherited member function is a static property of the subclass; it doesn't change dynamically throughout the life of any particular object, nor is it possible for distinct objects of the subclass to have distinct definitions of the member function. Now go back and re-read the previous paragraph, but make these substitutions: * "member function" --> "member object" * "signature" --> "type" * "body" --> data: the definition (class) of the member object is overridable in subclasses provided its declaration ("type") remains the same, and this overriddenness is a static property of the subclass *. ============================================================================== [28.4] in constructor, delete in destructor) * Extra dynamic binding (reason given below) ============================================================================== [28.5][20] function calls can be statically bound, which allows inlining. Inlining allows zillions (would you believe half a dozen :-) optimization opportunities such as procedural integration, register lifetime issues, etc. The C++ compiler can know an object's exact class in three circumstances: local variables, global/static variables,! ============================================================================== [28.6] Are "inline virtual" member functions ever actually "inlined"? Occasionally... When the object is referenced via a pointer or a reference, a call to a virtual[20] function. Note: Please read the next two FAQs to see the other side of this coin! ============================================================================== [28.7] Sounds like I should never use reference semantics, right? Wrong. Reference semantics are A Good Thing. We can't live without pointers. We just don't want our s/w the come into play with real OO design. OO/C++ mastery takes time and high quality training. If you want a powerful tool, you've got to invest. Don't stop now! Read the next FAQ too!! ============================================================================== [28.8] subclass. ============================================================================== -- Marshall Cline / 972-931-9470 / mailto:cline@parashift.com | http://www.faqs.org/faqs/C++-faq/part8/ | crawl-002 | refinedweb | 2,503 | 66.13 |
Question:
I need to check if a certain property exists within a class. Please refer to the LINQ query in question. For the life of me I cannot make the compiler happy.
class Program { static void Main(string[] args) { ModuleManager m = new ModuleManager(); IModule module = m.FindModuleForView(typeof(HomeView)); Console.WriteLine(module.GetType().ToString()); Console.ReadLine(); } } public class ModuleManager { [ImportMany] public IEnumerable<Lazy<IModule>> Modules { get; set; } [ImportMany] public IEnumerable<Lazy<View>> Views { get; set; } public ModuleManager() { /()); } } public IModule FindModuleForView(Type view) { //THIS IS THE PROBLEM var module = from m in Modules where ( from p in m.Value.GetType().GetProperties() where p.GetType().Equals(view) select p ) select m; } public CompositionContainer _container { get; set; } } public interface IModule { } [Export] public class HomeModule : IModule { public HomeModule() { } [Export] public HomeView MyHomeView { get { return new HomeView(); } set { } } } public class HomeView : View { } public class View { }
Solution:1
The inner query should return
bool, but returns
PropertyInfo.
I haven't tested this, but I think you want something like:
var module = (from m in Modules where m.Value.GetType().GetProperties() .Select(p => p.PropertyType).Contains(view) select m).FirstOrDefault();
Edit:
Incorporating the
Enumerable.Any suggestion on another answer:
var module = (from m in Modules where m.Value.GetType().GetProperties() .Any(p => p.PropertyType.Equals(view)) select m).FirstOrDefault();
Solution:2
GetProperties() returns an array of PropertyInfo objects. Your call to p.GetType() is always going to return typeof(PropertyInfo) - never the "view" type you've passed in.
You probably want this instead:
from p in m.Value.GetType().GetProperties() where p.PropertyType.Equals(view) select p
Edit
As Robert pointed out, your logic to determine if the above query returns any properties is also wrong. An easy way around that is to see if anything came back from the subquery:
var module = from m in Modules where ( from p in m.Value.GetType().GetProperties() where p.PropertyType.Equals(view) select p ).Any() select m
Keep in mind that that query might return more than one module. You will probably want to return .First() from the results.
Solution:3
The
where keyword expects a predicate that returns a boolean condition, but you are providing a subquery that returns an
IEnumerable. Can you rework your subquery so that it returns an actual boolean condition?
You can convert it to a boolean result by using the
FirstOrDefault() extension method. This method will return
null if there are no records. So this should work (untested):
where ( from p in m.Value.GetType().GetProperties() where p.PropertyType.Equals(view) select p ).FirstOrDefault() != null
Solution:4
Even if you can get your query working, I don't think this is a good way to link your model with your view. I'd recommend creating a new question with more detail about what you are trying to do (and why), asking how you can create the association/link between the model and the view.
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon | http://www.toontricks.com/2019/04/tutorial-c-help-with-linq.html | CC-MAIN-2019-18 | refinedweb | 501 | 50.12 |
Red Hat Bugzilla – Bug 239672
'Select All' on a filtered list selects items outside of the filter
Last modified: 2007-10-23 22:46:03 EDT
When you filter say a list of systems, and click the 'select all' button,
systems outside of the filter (and that are not visible to the user within the
list pages returned by the filter) are added to set. Pretty much all systems in
the unfiltered list are added when the list is filtered.
Tasks such as getting systems with a particular naming scheme into particular
system groups, or just creating on-the-fly system sets to perform work on, are
impossible to accomplish from the system list because of this behavior.
The checkbox in the upper left corner of the list does not provide the needed
functionality, because clicking that checkbox only selects all visible (on the
current page) systems, not all systems in the currently displayed list. (e.g.,
100-page list of 1,000 systems, filtered down to 20 pages of 200 systems. Click
on the upper-left corner. Following current behavior, that would only select the
10 systems available on page 1 of the 20 page list of 200 systems. Make sense?)
PROPOSED USE CASE to fix this
=============================
Scenario: Say I have a list of 1,000 systems, and I have let's say 200 systems
with the term 'wkstation' in their name. I need to do some work on systems in
this particular namespace, and only those systems.
(1) I go to my system list. I get a 100-page list of 1,000 systems.
(2) I filter for 'wkstation' in that system list, and I get a 20-page list with
200 systems in it.
(3) I hit the 'select all' button in the lower-left corner of the list-view
because I want to add all of those 'wkstation' systems and put them in a system
group (or perhaps merely just want to work with them as a system set.) Only
those 200 systems will be added to my set.
(4) I then clear my set by hitting clear in the SSM bar, upper right.
(5) I then clear the filter by erasing the filter term and hitting the 'go' button.
(6) Now I see all 1,000 systems again. I click 'select all'. All 1,000 systems
are selected.
Duplicate of 241070.
*** This bug has been marked as a duplicate of 241070 *** | https://bugzilla.redhat.com/show_bug.cgi?id=239672 | CC-MAIN-2017-30 | refinedweb | 406 | 69.72 |
Hii guys,
I want to defined a function in c# in unity3d.I want to access the object or method of C# function in eclipse ide.e.g
I am defined a class in eclipse ide as
public classs MyClass extends com.qualcomm.QCARUnityPlayer.PlayerActivity{
}
how the C# functions defined in unity3d and what are procedures to access the function in java using eclipse ide.The defined class in java is as above given.
- Sort Posts
- 3 replies
- Last post
Hii guys,
As far as I know this isn't possible. Java and native code can't access methods in the C# Unity scripts. Instead, your Unity script has to call a native or Java method. You might try asking in the Unity forums though, they will know for sure.
Also, I suggest reading through Unity's documentation on this subject:
- Kim
Delete Message
Are you sure you want to delete this message?
Delete Conversation
Are you sure you want to delete this conversation?
I found solution for this.we can use androidjavaObject and androidJavaclass for this.also we can pass message from java to c#.
UnityPlayer.sendMessage("Name of ur scene","methodName","parameterpassedtofunction");. | https://developer.vuforia.com/forum/unity-extension-technical-discussion/how-call-c-function-eclipse-ide | CC-MAIN-2019-51 | refinedweb | 194 | 67.86 |
I'm trying to create the some sample application.
Which first row is One label then input entry box then submit button.
Then second row has the another entry box.
My problem is when I increase width of the entry box in second row it affect the first row style. I don't know what is the problem.
import Tkinter
tk_obj = Tkinter.Tk()
tk_geo = tk_obj.geometry("1200x800")
Tkinter.Label(tk_obj, text='Enter query ').grid(row=1,column=1)
def callback():
print "hi"
E1 = Tkinter.Entry(tk_obj,bd=3,width=120)
E1.grid(row=1, column=2,ipady=3)
b = Tkinter.Button(tk_obj, text="Check", command=callback)
b.grid(row=1,column=3)
E2 = Tkinter.Entry(tk_obj,bd=3,width=100)
E2.grid(row=2,column=1,ipady=100)
tk_obj.mainloop()
The
grid method places widgets in the center of the cell they inhabit. When you have two widgets of different sizes sharing a row or column, this means that there will be blank space around the smaller widget. To make the second
Entry widget span the first two columns, use
columnspan=2 when you
grid() it. To left-align it within those two columns, use
sticky='W':
E2.grid(row=2,column=1,ipady=100, columnspan=2, sticky='W')
You can then adjust that
Entry widget's
width attribute until it looks the way you want it to. | https://codedump.io/share/1f6KOV8NhxLf/1/second-row-entry-width-affect-the-first-row-style-in-tkinter | CC-MAIN-2018-09 | refinedweb | 228 | 61.43 |
This is the mail archive of the libstdc++@sources.redhat.com mailing list for the libstdc++ project.
Phil Edwards wrote: > >. How about: class basic_file { . . . typedef __whatever__ __np_file_descriptor; . . . __np_file_descriptor __np_get_descriptor() const { return ... }; . . . }; > >. I agree with Mr. Edwards here. In general, that's not what an iostream is for. One thing that I do in my program, which links to the last snapshot you guys made that wasn't part of GCC, is this: "socketostream.h" template<typename _CharT, typename _Traits = char_traits<_CharT> > class basic_socketostream : public basic_ostream<_CharT, _Traits> { public: basic_socketostream(int iSocket) : basic_ostream<_CharT, _Traits>(0), m_iSocket(iSocket), m_fb(iSocket, "socket", ios::out) { this->init(&m_fb); } virtual ~basic_socketostream() { shutdown(m_iSocket, 2); #ifdef WIN32 #error "close() probably isn't right for a socket!" #endif } private: int m_iSocket; filebuf m_fb; }; typedef basic_socketostream<char> socketostream; You guys still support this non-standard filebuf constructor, right? This might help Mr. Papadopoulo. P.S. Unrelated, to the list: If you mistakenly have a close() call in ~basic_socketostream() above, it causes a memory leak deep in libstdc++ 2.90.3. I posted to the list about this a while ago, but never heard anything back. I've got a test program that demonstrates the memory leak if anyone wants it. In general, it seemed that any error when close() is called in a filebuf will cause a memory leak in 2.90.3. -- George T. Talbot <george at moberg.com> | http://gcc.gnu.org/ml/libstdc++/2000-09/msg00068.html | crawl-001 | refinedweb | 233 | 59.19 |
Opened 3 years ago
Last modified 3 months ago
#22712 new Cleanup/optimization
Consider not using built-in functions as parameters
Description (last modified by )
Currently the staticfiles finders'
find function has a parameter
all which is also a built-in function. Personally, I consider using built-ins as parameters/variables to be bad form, and would usually just rename the parameter in my subclasses. Unfortunately,
find is explicitly called with
all=all in
django.contrib.staticfiles.finders.find(). So, to use the built in
all() one needs to use
from __builtin__ import all as all_.
There are probably more examples throughout the codebase, but this is the one I've run into.
Change History (4)
comment:1 Changed 3 years ago by
comment:2 Changed 3 years ago by
Couldn't the arguments undergo the normal django deprecation cycle? For two version accept both, but issue a warning if the builtin version is used.
comment:3 Changed 3 years ago by
The
all kwarg is a private API, so we can change it. However, we should check whether this is going to break popular third-party addons. (I don't know the staticfiles landscape very well.)
Unfortunately, I think changing this is not going to be worth it, backwards compatibility wise. Will leave it open for a second opinion though. | https://code.djangoproject.com/ticket/22712 | CC-MAIN-2017-17 | refinedweb | 221 | 54.22 |
Looks likes Arora, pretty good,dear Daniel.
i never expect this browser developed so quick, good job man.
Ryouko 0.10.1 fail to start without PyQt4 installed,but Ryouko 0.10.0 did.
Ryouko is a simple PyQt4 Web browser. It was coded for fun and is not intended for serious usage, but it should nonetheless be capable of serving basic browsing needs. Ryouko is licensed under the MIT license.
Looks likes Arora, pretty good,dear Daniel.
i never expect this browser developed so quick, good job man.
Ryouko 0.10.1 fail to start without PyQt4 installed,but Ryouko 0.10.0 did.
I wasn't aware of the issue with 0.10.1, but I'll be sure to investigate. In the meantime, 0.10.6 is available with some new functionality added in.
Sorry for responding late. I am afraid I do not have a fix for that at this time. However, starting with a blank profile in a newer version of Ryouko should not cause this Issue, I think.
It's not the time to debug now, dear Daniel.
And Ryouko become more and more better every build, unfortunately Windows program always needs many debug, i prefer to waiting the final release, maybe you could take your time to debug for Windows user. ^^
Truthfully-speaking, it is possible that even though there will be updates, there may never be a final release of Ryouko. As mentioned on the homepage, Ryouko was coded as a hobby for fun, as not a serious effort to build a Web browser. However, if enough people like it, it might become a serious effort.
"As mentioned on the homepage, Ryouko was coded as a hobby for fun, as not a serious effort to build a Web browser."
That's why i appreciate your effort, there're few programmer has such free soul as you today. Ryouko has some fresh feeling, that's real awesome. ^^
Dear Daniel, from 1.3.0, there're something strange.
Ryouko can't close chinese/Japanese/Korea website by clock the "X" on tab, but other language site is OK.
i try to replace the ryouko.py from 1.2.6, no such problem.
Some CJK site:
Best wishes,
Thank you for notifying me. I've looked into this problem, and sure enough, you're right. So I've fixed it in the latest Git revision of Ryouko. It will be released in the near future, so stay tuned. ^^
Alright! Ryouko 1.4.0 has been released with the bugfix, plus some other changes. Enjoy this release!
The only things left is: notice softpedia the great update of Ryouko, 1.4.0 worth to share with more people. Softpedia still has Ryouko 0.11.11.
There're some guys like Ryouko in china, so how to translate the menu and other resource to chinese? Do you have plan to make Ryouko to multilanguage? :)
Ryouko is currently only available in English and Spanish, as those are the only two languages I'm familiar with. Fortunately, the program is designed so that other languages can be added without too much difficulty. All the existing translation files are available in the folder "translations". Translations can work in two ways: Either a translation file contains all of the translation strings, or it simply links to another translation file. If you open the "en_US.json" and "es.json" translations in a text editor, I think it should be fairly simply to see how the translation files are structured. The syntax is basically {"id1": "string1", "id2": "string2", ... "idn": "stringn"} where "id" indicates the identifier of the string (which is ALWAYS the same for all languages) and "string" indicates the contents of the string itself (which is adjusted to fit the language). For example, the identifier "back" indicates a string that should contain the text "Back" (in English), or "Previo" (in Spanish), or whatever that should be in whatever language. For simplicity, an existing translation file can just be copied-and-pasted, renamed to match what Python's locale.getdefaultlocale()[0] would detect the language as ("en_US" is American English, for example), and finally edited in a text editor until all the strings are properly adjusted. To accurately determine what the name of the file should be, install Python 2.7, open IDLE, and run the following commands:
import locale
print locale.getdefaultlocale()[0] + ".json"
i've translate the en_US.json, but have no idea how to use it on windows,so i upload it here.
Please add this to Ryouko, it's simple chinese, for China user.
im not so sure there're multiple-byte characters support or not.
Don't worry, Ryouko supports multiple byte characters in its translations. I tested an alpha translation of Japanese on a related program, Akane, which uses the same library as Ryouko.
The file was deleted... =( Are you sure it should be called en_CN? It might be zh_CN or zh_TR, I think.
Never mind, the file was not deleted after all. I'll take a look at it, thanks!
To use the translation, you'll have to stick it into the translations folder and set your computer's locale to Simplified Chinese. Ryouko currently does not have a way of switching translations without relying on the system...
You're welcome. By the way, the translation has to be encoded in UTF-8.
The translation file encoding must be UTF-8; if not, the browser will crash.
In any case, I've converted your translation to UTF-8 and uploaded it to the Git repository. It will be included in version 1.4.2. You have, of course, been credited in the AUTHORS.txt file and licensing, so don't worry. =)
Thanks.
i got the SSL file from 1.01c
Maybe this useful to you.
Log in to post a comment. | https://sourceforge.net/p/ryouko/wiki/Home/ | CC-MAIN-2017-04 | refinedweb | 975 | 68.06 |
Scroll down to the script below, click on any sentence (including terminal blocks!) to jump to that spot in the video!
gstreamer0.10-ffmpeg
gstreamer0.10-plugins-goodpackages.
Let's do something fun, like create a custom page. Like always, any custom code will
live in a module. And modules live in the
modules/ directory. Create a new one
called
dino_roar. To make Drupal fall in love with your module, create the info
file:
dino_roar.info.yml. If you loved the old
.info files, then you'll feel
all warm and fuzzy with these: it's the same thing, but now in the YAML format.
Inside give it a
name:
Dino ROAR, a
type:
module,
description:
Roar at you,
package:
Sample and
core:
8.x:
If YAML is new to you, cool! It's pretty underwhelming: just a colon separated key-value pair. But make sure you have at least one space after the colon. Yaml also supports hierarchies of data via indentation - but there's none of that in this file.
Module ready! Head back to the browser and go into the "Extend" section. With any luck we'll see the module here. There it is under "Sample": "Dino ROAR". It sounds terrifying. Check the box and press the install button anyways. What's the worst that could happen?
Nothing! But now we can build that page I keep talking about.
In any modern framework - and I am including Drupal in this category, yay! - creating a page is two steps. First, define the URL for the page via a route. That's your first buzzword in case you're writing things down.
Second, create a controller for that page. This is a function that you'll write that actually builds the page. It's also another buzzword: controller.
If these are new buzzwords for you, that's ok - they're just a new spin on some old ideas.
For step 1, create a new file in the module:
dino_roar.routing.yml. Create a new
route called
dino_says: this is the internal name of the route and it isn't important
yet:
Go in 4 spaces - or 2 spaces, it doesn't matter, just be consistent - and add
a new property to this route called
path. Set it to
/the/dino/says: the URL to
the new page:
Below
path, a few more route properties are needed. The first, is
defaults, with
a
_controller key beneath it:
The
_controller key tells Drupal which function should be called when someone
goes to the URL for this exciting page. Set this to
Drupal\dino_roar\Controller\RoarController::roar.
This is a namespaced class followed by
:: and then a method name. We'll create
this function in a second.
Also add a
requirements key with a
_permission key set to
access content:
We won't talk about permissions now, but this is what will allow us to view the page.
In YAML, you usually don't need quotes, except in some edge cases with special
characters. But it's always safe to surround values with quotes. So if you're in
doubt, use quotes! I don't need them around
access content... but it makes me fee
good.
Step 1 complete: we have a route. For Step 2, we need to create the controller: the
function that will actually build the page. Inside of the
dino_roar module create
an
src directory and then a
Controller directory inside of that. Finally, add
a new PHP class called
RoarController:
Ok, stop! Fun fact: every class you create will have a namespace at the top. If you're not comfortable with namespaces, they're really easy. So easy that we teach them to you in 120 seconds in our namespaces tutorial. So pause this video, check that out and then everything we're about to do will seem much more awesome.
But you can't just set the namespace to any old thing: there are rules. It must
start with
Drupal\, then the name of the module -
dino_roar\, then whatever directory
or directories this file lives in after
src/. This class lives in
Controller.
Your class name also has to match the filename, +
.php:
If you mess any of this up, Drupal isn't going to be able to find your class.
The full class name is now
Drupal\dino_roar\Controller\RoarController. Hey, this
conveniently matches the
_controller of our route!
In
RoarController, add the new
public function roar():
Now, you might be asking yourself what a controller function like this should return.
And to that I say - excellent question! Brilliant! A controller should always return
a Symfony
Response object. Ok, that's not 100% true - but let me lie for just a
little bit longer.
Tip
The code-styling (4 spaces indentation, etc) I'm using is called PSR-2. It's a great PHP standard, but is (I admit) different than the recommended Drupal standard.
To return a response, say
return new Response(). I'll let it autocomplete the
Response class from Symfony's HttpFoundation namespace. When I hit tab to select this,
PhpStorm adds the
use statement to the top of the class automatically:
That's important: whenever you reference a class, you must add a
use statement
for it. If you forget, you'll get the famous "Class Not Found" error.
For the page content, we will of course
ROOOAR!.
That's it! That's everything. Go to your browser and head to
/the/dino/says:
Hmm page not found. As a seasoned Drupal developer, you may be wondering, "uhh do I need to clear some cache?" My gosh, you're right!
// composer.json { "require": { "composer/installers": "^1.0.21", // v1.0.21 "wikimedia/composer-merge-plugin": "^1.3.0" // dev-master } } | https://symfonycasts.com/screencast/drupal8-under-the-hood/modules-routes-controllers | CC-MAIN-2021-31 | refinedweb | 959 | 76.01 |
import "github.com/agl/ed25519/extra25519"
PrivateKeyToCurve25519 converts an ed25519 private key into a corresponding curve25519 private key such that the resulting curve25519 public key will equal the result from PublicKeyToCurve25519.
PublicKeyToCurve25519 converts an Ed25519 public key into the curve25519 public key that would be generated from the same private key.
RepresentativeToPublicKey converts a uniform representative value for a curve25519 public key, as produced by ScalarBaseMult, to a curve25519 public key.
ScalarBaseMult computes a curve25519 public key from a private key and also a uniform representative for that public key. Note that this function will fail and return false for about half of private keys. See.
Package extra25519 imports 2 packages (graph) and is imported by 56 packages. Updated 2018-03-15. Refresh now. Tools for package owners. | https://godoc.org/github.com/agl/ed25519/extra25519 | CC-MAIN-2019-39 | refinedweb | 128 | 53.81 |
We can splice a single-entry, single-exit LGraph onto a head or a tail.
For a head, we have a head h followed by a LGraph g.
The entry node of g gets joined to h, forming the entry into
the new LGraph. The exit of g becomes the new head.
For both arguments and results, the order of values is the order of
control flow: before splicing, the head flows into the LGraph; after
splicing, the LGraph flows into the head.
Splicing a tail is the dual operation.
(In order to maintain the order-means-control-flow convention, the
orders are reversed.)
For example, assume
head = [L: x:=0]
grph = (M, [M: stuff,
blocks,
N: y:=x; LastExit])
tail = [return (y,x)]
Then splice_head head grph
= ((L, [L: x:=0; goto M,
M: stuff,
blocks])
, N: y:=x)
Then splice_tail grph tail
= ( stuff
, (???, [blocks,
N: y:=x; return (y,x)])
A safe operation
Conversion to and from the environment form is convenient. For
layout or dataflow, however, one will want to use postorder_dfs
in order to get the blocks in an order that relates to the control
flow in the procedure.
Traversal: postorder_dfs returns a list of blocks reachable
from the entry node. This list has the following property:
Say a back reference exists if one of a block's
control-flow successors precedes it in the output list
Then there are as few back references as possible
The output is suitable for use in
a forward dataflow problem. For a backward problem, simply reverse
the list. (postorder_dfs is sufficiently tricky to implement that
one doesn't want to try and maintain both forward and backward
versions.)
This is the most important traversal over this data structure. It drops
unreachable code and puts blocks in an order that is good for solving forward
dataflow problems quickly. The reverse order is good for solving backward
dataflow problems quickly. The forward order is also reasonably good for
emitting instructions, except that it will not usually exploit Forrest
Baskett's trick of eliminating the unconditional branch from a loop. For
that you would need a more serious analysis, probably based on dominators, to
identify loop headers.
The ubiquity of postorder_dfs is one reason for the ubiquity of the LGraph
representation, when for most purposes the plain Graph representation is
more mathematically elegant (but results in more complicated code).
Here's an easy way to go wrong! Consider
A -> [B,C]
B -> D
C -> D
Then ordinary dfs would give [A,B,D,C] which has a back ref from C to D.
Better to geot [A,B,C,D]
For layout, we fold over pairs of 'Block m l' and 'Maybe BlockId'
in layout order. The 'Maybe BlockId', if present, identifies the
block that will be the layout successor of the current block. This
may be useful to help an emitter omit the final goto of a block
that flows directly to its layout successor.
For example: fold_layout f z [ L1:B1, L2:B2, L3:B3 ]
= z $ f (L1:B1) (Just L2)
$ f (L2:B2) (Just L3)
$ f (L3:B3) Nothing
where a $ f = f a | https://downloads.haskell.org/~ghc/6.10.4/docs/html/libraries/ghc/ZipCfg.html | CC-MAIN-2015-32 | refinedweb | 525 | 69.11 |
I've been looking for a straight answer for this (I can think of lots of possiblities, but I'd like to know the true reason):
jQuery provides a .data() method for associating data with DOM Element objects. What makes this necessary? Is there a problem adding properties (or methods) directly to DOM Element Objects? What is it?
Is there a problem adding properties (or methods) directly to DOM Element Objects?
Potentially.
There is no web standard that says you can add arbitrary properties to DOM nodes. They are ‘host objects’ with browser-specific implementations, not ‘native JavaScript objects’ which according to ECMA-262 you can do what you like with. Other host objects will not allow you to add arbitrary properties.
In reality since the earliest browsers did allow you to do it, it's a de facto standard that you can anyway... unless you deliberately tell IE to disallow it by setting
document.expando= false. You probably wouldn't do that yourself, but if you're writing a script to be deployed elsewhere it might concern you.
There is a practical problem with arbitrary-properties in that you don't really know that the arbitrary name you have chosen doesn't have an existing meaning in some browser you haven't tested yet, or in a future version of a browser or standard that doesn't exist yet. Add a property
element.sausage= true, and you can't be sure that no browser anywhere in space and time will use that as a signal to engage the exciting DOM Sausage Make The Browser Crash feature. So if you do add an arbitrary property, make sure to give it an unlikely name, for example
element._mylibraryname_sausage= true. This also helps prevent namespace conflicts with other script components that might add arbitrary properties.
There is a further problem in IE in that properties you add are incorrectly treated as attributes. If you serialise the element with
innerHTML you'll get an unexpected attribute in the output, eg.
<p _mylibraryname_sausage="true">. Should you then assign that HTML string to another element, you'll get a property in the new element, potentially confusing your script.
(Note this only happens for properties whose values are simple types; Objects, Arrays and Functions do not show up in serialised HTML. I wish jQuery knew about this, because the way it works around it to implement the
data method is absolutely terrible, results in bugs, and slows down many simple DOM operations.)
I think you can add all the properties you want, as long as you only have to use them yourself and the property is not a method or some object containing methods. What's wrong with that is that methods can create memory leaks in browsers. Especially when you use closures in such methods, the browser may not be able to complete garbage cleaning which causing scattered peaces of memory to stay occupied.
This link explains it nicely.
here you'll find a description of several common memory leak patterns
It has to do with the fact that DOM in IE is not managed by JScript, which makes it completely different environment to access. This leads to the memory leaks. Another reason is that, when people use innerHTML to copy nodes, all those added properties are not transfered. | https://javascriptinfo.com/view/98974/what-s-wrong-with-adding-properties-to-dom-element-objects | CC-MAIN-2020-45 | refinedweb | 554 | 61.26 |
table of contents
NAME¶
ftok - convert a pathname and a project identifier to a System V IPC key
SYNOPSIS¶
#include <sys/types.h> #include <sys/ipc.h>
key_t ftok(const char *pathname, int proj_id);
DESCRIPTION¶¶
On success, the generated key_t value is returned. On failure -1 is returned, with errno indicating the error as for the stat(2) system call.
ATTRIBUTES¶
For an explanation of the terms used in this section, see attributes(7).
CONFORMING TO¶
POSIX.1-2001, POSIX.1-2008.
NOTES¶.
EXAMPLES¶
SEE ALSO¶
msgget(2), semget(2), shmget(2), stat(2), sysvipc(7)
COLOPHON¶
This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | https://manpages.debian.org/bullseye/manpages-dev/ftok.3.en.html | CC-MAIN-2022-27 | refinedweb | 131 | 67.15 |
.
Before proceeding, I recommend reading the previous tutorial. This way, you'll have the understanding of what namespaces and autoloading are, you'll have the working version of the plugin up to this point (since we're going to be building on it), and then you will be ready to proceed from that point forward.
Once you've read it, feel free to come back to this tutorial and resume your work.
Before We Begin
As with all of my tutorials, I assume you have a working development environment on your machine. This includes the following:
- A local development environment that includes PHP 5.6.20, the Apache web server, and a MySQL database server.
- A directory out of which WordPress 4.6 is being hosted.
- A text editor or IDE of your choice that you're comfortable using for writing a plugin.
- A working knowledge of the WordPress Plugin API.
If you're this far into the series (or have read any of my previous work), then I assume you already have something like the above already in place.
And when you do, we're ready to get started.
What We're Building
Recall from the previous tutorial:
We'll be building a plugin that makes it easy to load stylesheets and JavaScript styles in our plugin, and that displays a meta box that prompts the user with a question to help them brainstorm something about which to blog.
Yes, it's simple and it's not likely something that anyone will use outside of studying the concepts we're covering in this blog. But the means by which we're teaching the concepts that we're using are what's important.
This plugin gives us the ability to do exactly that.
At the end of the last tutorial, we left with a plugin that displays a random question to the writer at the top of the sidebar in the WordPress post creation screen.
Each time you refresh the page, a new question is loaded. As it stands, it's not bad, but there are some improvements we can make in terms of the style of the content in the meta box.
That is, we can introduce stylesheets that will help us create a slightly more visually appealing presentation. Additionally, it will give us a chance to explore a few more object-oriented techniques that we can use when working with assets like stylesheets.
So let's begin.
Introducing Stylesheets
For the purposes of this tutorial, I'm not going to be using any type of preprocessor. I'm just going to be using vanilla CSS. But the way in which we enqueue assets will be a bit more object-oriented than what many WordPress developers are used to seeing.
This will all contribute to the goal of using namespaces and autoloading in this series. But first, let's start with introducing these stylesheets, creating the necessary class interfaces, classes, and communication with the WordPress API.
Add the CSS File
In the
admin directory, create a subdirectory called
assets. Within the
assets directory, create a subdirectory called
css and then add the file
admin.css.
The final directory structure should look something like this:
We're not ready to provide any type of styles just yet. Instead, we need to turn our attention to the server-side code responsible for enqueuing this stylesheet.
Enqueue the Stylesheet
When it comes to registering and enqueuing both stylesheets and JavaScript, most WordPress plugin developers are familiar with the hooks necessary to do just that. Specifically, I'm referring to
admin_enqueue_scripts and
wp_enqueue_style.
And though we are going to using these hooks, we're going to be setting it up in a simple, object-oriented manner. No, this series isn't meant to take a deep dive into object-oriented principles but, when applicable, I'm happy to try to show them to you.
The Assets Interface
In object-oriented programming, an interface is defined as such:
An interface is a programming structure/syntax that allows the computer to enforce certain properties on a class.
Another way to think of it is this:
If you have a class that implements an interface, the class must define functionality that the interface dictates.
So if the interface has two method signatures with a specific visibility and name, then the class implementing the interface must have two methods with the same visibility and name as well as an actual method implementation.
And that's what we're going to do. First, we need to define our interface. So in the
util directory, create
interface-assets.php and then add the following code:
<?php /** * Defines a common set of functions that any class responsible for loading * stylesheets, JavaScript, or other assets should implement. */ interface Assets_Interface { public function init(); public function enqueue(); }
Notice, the interface doesn't actually define functionality. Instead, it specifies what the classes that implement this interface should define.
As you may surmise, the classes that will implement this interface will have two methods above along with an actual implementation for each function. And we'll see how this works momentarily.
Next, make sure to include this file in the main plugin file:
<?php // Include the files for loading the assets include_once( 'admin/util/interface-assets.php' );
Next, we need to create a file that implements this interface. Since we're working with CSS files, we'll create a CSS loader.
The CSS Loader
This is the class that is responsible for implementing the interface and doing the actual work of registering the function with the necessary WordPress hook (and actually giving the implementation to said function).
If you take a look at the code below, it should look very similar to something you've seen or perhaps worked on in a previous project:
<?php /** * Provides a consistent way to enqueue all administrative-related stylesheets. */ /** * Provides a consistent way to enqueue all administrative-related stylesheets. * * Implements the Assets_Interface by defining the init function and the * enqueue function. * * The first is responsible for hooking up the enqueue * callback to the proper WordPress hook. The second is responsible for * actually registering and enqueuing the file. * * @implements Assets_Interface * @since 0.2.0 */' ) ); } }
The code above should be relatively easy to follow given the code comments, but I'll outline what's happening:
initand
enqueueare both functions required as the class implements the
Assets_Interface.
- When
initis called, it registers the
enqueuefunction with the hook responsible for registering a stylesheet.
- The
enqueuemethod registers the
admin.cssfile and uses
filemtimeas a way to know if the file has changed or not (which allows us to bust any cached version of the file when serving).
In this implementation, the actual
admin.css file is added on every page. Adding a conditional to check which page is currently active and then determining if the stylesheet should be added or not can be added as a post-tutorial exercise. For a hint, check out
get_current_screen().
Next, we need to include this file in the main plugin file:
<?php // Include the files for loading the assets include_once( 'admin/util/interface-assets.php' ); include_once( 'admin/util/class-css-loader.php' );
Next, we need to instantiate the CSS loader and call its
init method in the main
tutsplus_namespace_demo function:
<?php $css_loader = new CSS_Loader(); $css_loader->init();
Assuming you've done everything right, you should be able to refresh the Add New Post page, view the source, and see
admin.css listed as an available stylesheet.
We've one more thing to do before we're ready to wrap up this part of the tutorial. We need to actually write some CSS.
Style the Meta Box
Since the majority of the tutorial has focused on some object-oriented techniques and we still have some new topics to explore in this series, we'll make this part relatively easy.
Rather than just using some default styles as provided by WordPress, let's enhance the meta box just a little bit.
First, locate the
render function in the
Meta_Box_Display class. Let's modify it so that it outputs the contents of the file in a paragraph element with the ID attribute of "tutsplus-author-prompt".
To do this, we're going to introduce a new method that will use a WordPress API method for sanitizing HTML.
<?php /** * Sanitizes the incoming markup to the user so that * * @access private * @param string $html The markup to render in the meta box. * @return string Sanitized markup to display to the user. */ private function sanitized_html( $html ) { $allowed_html = array( 'p' => array( 'id' => array(), ), ); return wp_kses( $html, $allowed_html ); }
We'll then call this function from within the
render method to display the content in the meta box.
<?php /** * Renders a single string in the context of the meta box to which this * Display belongs. */ public function render() { $file = dirname( __FILE__ ) . '/data/questions.txt'; $question = $this->question_reader->get_question_from_file( $file ); $html = "<p id='tutsplus-author-prompt'>$question</p>"; echo $this->sanitized_html( $html ); }
Now we can open admin.css and make some small changes to update the look and feel of the meta box in the Add New Post screen. Let's add the following CSS:
#tutsplus-author-prompt { font-style: italic; text-align: center; color: #333; }
And at this point, your meta box should now look something like the following:
As mentioned at the beginning, it's nothing major, but it's something that enhances the look and feel of the question just a little bit.
What's Next?
At this point, we've introduced a number of different classes, interfaces, and other object-oriented features. We have a plugin that uses data from a text file, that communicates with the WordPress API, and that sanitizes information before rendering it to the homepage.
We've got a good foundation from which to begin talking about namespaces. So in the next tutorial, we're going to do exactly that. If you've yet to catch up on the rest of the series, then I recommend it as we're only going to continue building on what we've learned.
If, in the meantime, you're looking for other WordPress-related material, you can find all of my previous tutorials on my profile page and you can follow me on my blog or on Twitter.
Until then, don't forget to download the working version of the plugin (version 0.2.0) attached to this post. The link is available in the sidebar under a button titled Download Attachment. And, as usual, don't hesitate to ask any questions in the comments!
Resources
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/using-namespaces-and-autoloading-in-wordpress-plugins-part-2--cms-27203 | CC-MAIN-2017-13 | refinedweb | 1,782 | 62.98 |
How To Use the GitLab User Interface To Manage Projects
Introduction.
DigitalOcean has a GitLab one-click install image that allows you to easily deploy a GitLab server on a VPS instance. You can set up GitLab on DigitalOcean here.
In this guide, we will explore the GitLab interface so that you can configure the environment, upload your projects, and invite and manage users. We will assume you've gone through the installation procedure and can log into your GitLab instance.
How To Configure Your User Profile
Before you get started using GitLab to handle your projects, it is a good idea to get your profile set up correctly. This will not only help your teammates identify you, it is also where you can manage your interface and the way that you connect to projects.
Begin by clicking on the "Profile settings" button in the upper-right corner:
The initial screen will allow you to change the name and email associated with your account. You can also link your social media accounts, write a short bio, and upload a picture of your choice.
If you would also like to change your username, click the "Account" tab at the top. Here you can adjust the username that your repositories will be stored under. You will also have access to your access token:
The other item that you definitely want to look into is the "SSH Keys" tab. In this tab, click the "Add SSH Key" button.
Here, you can add the SSH key that you will use to communicate with the server through git. Multiple keys can be added for each user. Add your SSH key and click "Add Key":
This is also a good opportunity to change the application and code preview themes, if you so desire. Click on the "Design" tab. You can choose from five application themes and four popular code preview themes:
How To Manage Users and Groups
GitLab gives you the tools to manage projects, users, and groups from one screen. Access it by clicking the "Admin area" button in the top-right corner:
The interface is divided into six sections: projects, latest projects, users, latest users, groups, and stats. The main points of contact that we will be using are the projects, users, and groups.
Create a New User
Currently, there is only a single user and no projects of groups. Let's start by creating a demonstration user that we can use later. Click on the "New User" button in the middle column:
We will need to fill out the regular contact details. When you are done, click the "Create User" button at the bottom:
You will be taken to the new user's account page. An email with an initial password will be sent to the account email.
Create a New Group
Let's add a new group now. Click on the "Admin area" button again in the top-right corner. Click the "New Group" button in the right column:
The only thing you need to do to create a group is fill out a name and description. Click the "Create group" button:
The group will be created and you will automatically be added to the group as an owner. Let's add our demonstration account to this group as well.
Search for the second username in the box titled "Add user(s) to the group:". You will need to choose an access level for the user as well. For an explanation of the different permission levels available on your GitLab, go here:
your_domain.com/help/permissions
This is also available as a link in the box under "Read more about project permissions here".
For now, it doesn't matter which level you choose. Click "Add users into group" to add their access:
If you would like to change a user's permission level, you can add the user again with the new permissions. It will update accordingly.
Initialize a Project
Now, we can initialize a project. Return to the admin dashboard by clicking on the "Admin area" button as before. Click on the "New Project" button on the left side:
You can also get to this area by clicking on the "New project" button in the top navigation bar:
Pick a name and a namespace. A namespace is who will own the project. We will give the group we created ownership of our project. You should also fill out a description and choose whether the repo should be public.
It is also possible to import a repository from another site. You can click the "Import existing repository" link to get access to this functionality.
You will be taken to a page that will show you how to clone the project to your local computer, or push a local project to your new repository on GitLab.
You will be given a repository link that you can use to clone the repository and share with group members (or other people if it is public).
If you follow the instructions, you should be able to push your first commit to your GitLab repository.
Manage Projects with GitLab
We will add a sample project to our GitLab repository so we can see some of the features available when a project has a history and many commits.
Go through the procedure to create a new project. Call it "Rails". This time, click "Import existing repository" link. We will be using Michael Hartl's Ruby on Rails tutorial sample application.
In the Import existing repo field, type:
Click "Create project".
View Project Code
You should be taken to the project's landing page. Click on the "Files" tab to see the actual repository files:
Click on the "Gemfile" file. As you can see, there is great syntax highlighting included for recognized languages:
If your project has multiple branches, you can change the branch view by clicking on the master drop-down and switch to a different branch:
Review Commits
Click on the "Commits" tab to see the list of commits for the current branch:
You can click on any commit to see the diff that was produced by the commit. If you would like to see the entire project at any commit point, click the "Browse Code" link associated with that commit:
To see the diff between two commits, you can click the "compare" tab at the top. If we type the name of one of the commits in the left-hand box (in this case, we'll use e3c055dff), we can get a complete diff between the two:
Graphic Representations of your Project
You can view your project graphically in two different ways.
First, if you click on the "Network" tab, you can see a commit tree of your project. This allows you to see branches, merges, and commits. It will use the user's picture next to each commit as well, for easy identification:
The other way to get a graphical picture of your project is with the "Graphs" tab. You will see a large graph with the number of the project's commits vs time displayed. Below it will be a matching graph for each contributor:
You can select a portion of the project graph and the user's graphs will adjust accordingly. You can also choose to display additions or deletions instead of commits through the drop-down menu.
Conclusion
There are other tools included within GitLab that you should check out if you plan on using it with a team. This includes an embedded wiki for each project, an issue tracking system, and merge requests. For sharing small pieces of code outside of any specific project, GitLab also has snippet support.
For most teams, a properly configured GitLab will be more than adequate to handle projects. It provides simple user control and easy project creation and sharing. Explore the interface to see if it could be an easy solution for your project.
4 Comments | https://www.digitalocean.com/community/tutorials/how-to-use-the-gitlab-user-interface-to-manage-projects | CC-MAIN-2017-04 | refinedweb | 1,321 | 69.82 |
Still updating my Mix 09 Silverlight 3 + RIA Services talk with more fun stuff. While many of the RIA Services examples we have shown thus far do CRUD directly against database tables, I certainly recognize that many scenarios require using stored procedures in the database to encapsulate all data access.
You can see the full series here.
The demo requires (all 100% free and always free):
Check out the live site Also, download the full demo files
In this example, I am going to encapsulate all our data access in stored procedures. I will continue to use Entity Framework to access these stored procs, but you could of course use LinqToSql or ADO.NET directly.
Add Stored Procedures
The first step is to create a set of stored procedures in the database.
In Server Explorer open up the Database, select the Stored Procedures node and “Create New Stored Procedure”
These are very, very basic. My goal here is to show you how to get started, you can then add additional logic as needed while following the same basic overall pattern.
Let’s start by adding some query stored procedures:
ALTER PROCEDURE dbo.CoolSuperEmployees.Issues Between 10 And 99999
RETURN
Notice this stored proc does not directly support paging. You could take a paging information if that is required.
and to get a particular employee
ALTER PROCEDURE dbo.GetSuperEmployee
(
@EmployeeID int
).EmployeeID = @EmployeeID
RETURN
Update:
ALTER PROCEDURE dbo.UpdateSuperEmployee
(
@EmployeeID int,
@Name nvarchar(MAX),
@Gender nvarchar(50),
@Origin nvarchar(10),
@Issues int,
@Publishers nvarchar(10),
@LastEdit datetime,
@Sites nvarchar(MAX)
)
AS
Update SuperEmployees
Set
Name = @Name,
Gender = @Gender,
Origin = @Origin,
Issues = @Issues,
Publishers = @Publishers,
LastEdit = @LastEdit,
Sites = @Sites
Where
EmployeeID = @EmployeeID
Insert:
ALTER PROCEDURE dbo.InsertSuperEmployee
@Name nvarchar(MAX),
@Gender nvarchar(50),
@Origin nvarchar(10),
@Issues int = 0,
@Publishers nvarchar(10),
@LastEdit datetime = null,
@Sites nvarchar(MAX)
AS
Insert into SuperEmployees
(
Name,
Gender,
Origin,
Issues,
Publishers,
LastEdit,
Sites
)
Values
(
@Name,
@Gender,
@Origin,
@Issues,
@Publishers,
@LastEdit,
@Sites
)
Select SCOPE_IDENTITY() as Id
And finally delete:
ALTER PROCEDURE dbo.DeleteSuperEmployee
(
@EmployeeID int
)
AS
Delete From
SuperEmployees
Where
EmployeeID = @EmployeeID
Update the Entity Framework Model
Now let’s create an Entity Framework model that knows how to access the data via these Stored Procs. Let’s start by creating a new Entity Framework Model
Then we select the SuperEmployees table and all of the storedprocs we created above
Next, I like to set the properties on the SuperEmployee entity to make the naming more clear in the .NET world.
Next, we wire up the CUD (create, update, delete) operations for this table to go through the storedprocs we just wrote.
First we setup the Insert function to map to the “InsertSuperEmployees” storedproc
Visual Studio automatically sets up the mapping, if you need to tweak this based on your stored procs, you certainly can.
Repeat this for Update and Delete, such that they are all mapped.
Now we need to do the same thing for the query methods. Open the Model Browser and find the stored proc for “CoolSuperEmployee”. Right click and select “Create Function Import”.
Then we set up a mapping to return SuperEmployees
And repeat for the GetSuperEmployee (int employeeID)…
Now we have our model all setup, let’s go back to our DomainService and update it to use these settings.
Update the Domain Service
The DomainService allows you to create custom business logic and easily expose this data to the Silverlight client. The good news is this looks almost exactly like the pervious examples.
First, let’s look at the query methods.
1: [EnableClientAccess()]
2: public class SuperEmployeeDomainService :
3: LinqToEntitiesDomainService<NORTHWNDEntities>
4: {
5: public IList<SuperEmployee> GetSuperEmployees()
6: {
7: var q = Context.CoolSuperEmployees();
8: return q.ToList();
9: }
10:
11: public SuperEmployee GetSuperEmployee(int employeeID)
12: {
13: return Context.GetSuperEmployee(employeeID).FirstOrDefault();
14:
15: }
Notice in line 5, we return an IList rather than an IQueryable.. this means that query composition from the client composes at the stored proc level, rather than all the way into the database. This is goodness because we funnel all requests through that stored proc, but it has the costs of maybe returning more data to the mid-tier than the client really needs. You can of course add paging to the stored proc or you can do direct table access for read only scenarios, but still use stored procs for CUD.
Then we have Insert and Update..
1: public void InsertSuperEmployee(SuperEmployee superEmployee)
2: {
3: Context.AddToSuperEmployees(superEmployee);
4: }
5:
6: public void UpdateSuperEmployee(SuperEmployee currentSuperEmployee)
7: {
8: this.Context.AttachAsModified(currentSuperEmployee, this.ChangeSet.GetOriginal(currentSuperEmployee));
9: }
Notice they look just like our previous example, but now these methods eventually call into our stored procs rather than direct table access.
We run it and it works great! Exactly like pervious examples, but this time all data access is via stored procs.
For more information on working with stored procedures with Entity Framework or LinqToSql see:
Hi,
Very nice article. Can all these be done in code. Why are you automating these things ?
Thanks,
Thani
Thanks Brad. Great post. Question question: I’m still trying to come up to speed on incorporating stored procs like you have demonstrated. Why do I need to pull the "table" into the model if the CRUD operations are being done by the stored procs. Is that so the appropriate meta data is created? It would seem like I would need to pull ALL the tables in the from the DB. Am I on the right path?
Thanks,
Sean
You seen to skim over the issue, that you need to explictly create sprocs a against superemployee object that already exists as a table.
We need to see samples for read only operations for join tables, could you please provide this?
Hello Brad,
many thanks for your superb blog, wow ;o)! Such good reading, better than TV or anything..
Now, one problem, among the others :).. All the nice articles deal with pretty ideal (simple) data and filter scenarios. My situation is: I’ve a lot of related db tables on the server, which I’ve managed to be sent to the client with .Include() and [Include].
Now my main entity has got a 1-many relation, which I would like to filter on. Concrete: the SessionDetails record (the main business entity) posses a Media collection.
Showing it in DataGrid should be possible with a custom converter (e.g. 1 SessionDetails row will contain a column with all the media names concatenated as a string).
Now the filter in the GUI will show things like "User name" (who created the session), from-to date (when the session was created). This is easy with the FilterDescriptors collection, applying a logical "AND" to all the required (simple) props. But now, there should be also a group of checkboxes, one for every possible media involved in (e.g. related to) the SessionDetails record. I mean a group of "OR" criteria, which as such is another "AND" criterion in the final FilterDescriptors.
I’ve tried to append all the filter "where" expressions in DomainDataSource_LodingData, modifying the original LoadingDataEventArgs.Query, which works fine – but looses the sort order :-(. I’m not sure, how the stuff works low-level, I even didn’t find any [IsComposable] docs etc.
So my question is: what about complicated data sources (e.g. 1-many relations, lot of tables) and tricky filtering (e.g. groups of "AND" and groups of "OR")?
I would love to see some "how to" / "best practice" in situations, where you have such data sources (should one take DTO, but what about related entities and server-side filtering then?), how to apply custom filtering, what about complicated custom expression columns (e.g. "if the session response code was 200 AND the media used was voiceOverIp, THEN set the column "duration" to "endTime – answerTime") – how to filter and sort on such custom columns would be really a nirvana article for me ;-).
Thank you so much for your blog,
Andrej
Hi Brad,
I’ve analyzed even more the DomainDataSource problem with custom querying – it should be possible:
1. to have some custom code hookups in generating the query, as doing this in LoadingData appends more ".Where" to the expression tree _after_ the .OrderBy methods, which renders in lost sorting (and paging may be as well). I’ve decompiled the DomainDataSource.LoadData(), calling .GetFilterDescriptorsQuery(), which calls static (!) LinqHelper.BuildFilterExpression(). So by this design, it’s impossible to change anything, IMHO.
– or –
2. to have the possibility to provide an own IQueryable<TEntity>, instead of doing this by reflection by "QueryName", as one can’t append own modifiers to the .Where
– or –
3. appending the .Where wherever one likes (e.g. into the _LoadingData() event) and some component should be enough smart to reorder it: e.g. when SortXXX is found before any .Where, it should be put onto the end. As is, the EF SQL provider (?) ignores it simply – I’ve sniffed the executed query and point is, if there is an .OrderBy before any .Where, it gets lost.
Thank you,
Andrej
I have been using this method even before this post and I seem to prefer this way as compared to the normal way…
I encountered several problems…. but I was able to get around it.. by manually modifying the xml file… then I will have to save a copy of the xml because when ever I "update from the database" everything I have typed gets erased…
Anyways… I still prefer this way…
Hi,
thank you for this tutorial.
It works fine, but now I have a Entity with Including some attributes as a foreign key.
And now if I want to filter hte process crashes if i type in a filter.
Did anyone know, what I have to do now?
Thanks | https://blogs.msdn.microsoft.com/brada/2009/08/24/business-apps-example-for-silverlight-3-rtm-and-net-ria-services-july-update-part-24-stored-procedures/ | CC-MAIN-2017-13 | refinedweb | 1,629 | 55.44 |
With structures, variables , and unification in place, you might think that the next logical step is to collect groups of structures and then to unify a variable structure with each one. However, logic programming introduces notions that veer from this course. The first notion is that a structure can represent a statement of truth, or what logic programming calls an axiom . For example, you can regard
city(denver, 5280)
as a model of the true statement that Denver's elevation is about 5,280 feet. A structure that contains no variables is a fact, which is one type of axiom. The other type of axiom is a rule, which you will meet shortly. In the classes in package sjm.engine , class Fact is a subclass of Structure , as Figure 12.2 shows.
The constructors for the Fact class that accept objects as terms wrap these objects as other facts. A Fact object is always a composition of facts. In other words, a structure that contains only data is a composition of structures that contain only data.The variety of constructors provided by the Fact class makes it easier to create new Fact objects. For example, you can create city facts as follows :
package sjm.examples.engine; import sjm.engine.*; /** * This class shows the construction of a couple of facts. */ public class ShowFacts { public static void main(String[] args) { Fact d = new Fact( "city", new Fact[]{ new Fact("denver"), new Fact(new Integer(5280))}); Fact j = new Fact( "city", "jacksonville", new Integer(8)); System.out.println(d + "\n" + j); } }
This prints
city(denver, 5280) city(jacksonville, 8)
You can build a logic program from facts because facts are axioms. | https://flylib.com/books/en/2.879.1.108/1/ | CC-MAIN-2019-09 | refinedweb | 278 | 64.51 |
This is the mail archive of the cygwin@sourceware.cygnus.com mailing list for the Cygwin project.
--- Joost Kraaijeveld <J.Kraaijeveld@Askesis.nl> wrote: > In /src/backend/utils/error/elog.c and > /src/backend/utils/error/exc.c > you have t change > > extern int sys_nerr; > > to > > #ifdef __CYGWIN__ > # define sys_nerr _sys_nerr > #else > extern int sys_nerr; > #endif > This is really terrible advice. Please don't do this. As Chris already mentioned the correct solution is to #include <errno.h> It's generally bad practice to include platform-specific solutions in source code when there are alternatives. The fact is the program in question had a bug (failure to "#include <errno.h>") and it should be fixed. The old-fashioned Unix error handling is not thread-safe and is likely to break on other systems than just Cygwin. __________________________________________________ Do You Yahoo!? Yahoo! Photos -- now, 100 FREE prints! -- Want to unsubscribe from this list? Send a message to cygwin-unsubscribe@sourceware.cygnus.com | http://cygwin.com/ml/cygwin/2000-06/msg00368.html | CC-MAIN-2019-22 | refinedweb | 161 | 62.95 |
However, this isn't the 1990's. Your IDE will do most of your work for you if you like. When we right moused clicked you may have noticed something that I didn't touch on in the last post. Here's a photo of what I'm talking about.
Yes, that is correct. Eclipse has a wizard for adding servlets to your project. So let's go ahead and see what this wizard does by adding a Goodbye servlet.
Here's step 1 of the wizard:
Okay so I'm going to create my SayGoodByeServlet in the com.blogger.testing package, since I already have my SayHelloServlet in the same package. On to step 2!
This step covers pretty much the stuff you'd see in the annotations, in this case the @WebServlet annotation. When it comes to annotations it's pretty much convention over configuration. If you change nothing here, then your @WebServlet annotation will follow convention. Everything here is acceptable except the URL mapping. I would like it to be "/Goodbye" so I'll click on it, click Edit and change that.
Everything on this final step is fine as is, so I'll click the finish button., the generated code appears in the code editor windows. Here's what it says: SayGoodByeServlet */ @WebServlet("/Goodbye") public class SayGoodByeServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SayGoodByeS } }
As you can see the automatically generated code, is pretty much on par with the code that we wrote just the other day. Now we can remove those TODO comments and put down some actual code that will tell our system what to do. Publish the new information to the server and see the wonderful results.
Having a good start on manually building a servlet really helps you to understand the bits that the wizard is doing for you automatically. So I really recommend getting a peek at how it is done manually and then come and do this and see how it is done automatically.
Cheers! | http://ramenboy.blogspot.com/2012/11/eclipse-serves-servlets-on-quick.html | CC-MAIN-2018-13 | refinedweb | 341 | 73.47 |
I am attempting to build the latest development version (12/16/09) of gnuplot using Sun Studio 12.1, and wxGTK-2.8.10 (with patches applied from\). During the make process, I get errors during the compilation of wxterminal/wxt_gui.cpp that look like the same kinds of errors I got when trying to build wxGTK before adding the patches. I see that someone came up with a patch for gnuplot 4.2.6 that addressed these issues (Bug Tracker ID: 2883574). Has someone come up with an analogous patch for v4.5? The source for wxt_gui.cpp seems to have removed references to the _T( ) macro, so I'm not sure why I'm still seeing conflicts [/opt/sunstudio12.1/prod/include/CC/Cstd/./memory line 107, etc.].
Don
Ethan Merritt
2009-12-17
I am confused.
The patch intended to fix building with Sun Studio was applied to 4.4 and 4.5, but not to 4.2. But you are saying that 4.2.6 works and 4.5 does not? I think you will need to provide the complete error messages. The one you quote above refers only to a system include file, not to a gnuplot source file.
Anonymous
2009-12-17
make errors with wxt_gui.cpp
Anonymous
2009-12-17
I only references v4.2.6 because it seemed like someone had similar issues with wxt_gui.cpp and Sun Studio with that version and found a patch that worked for ID: 2883574. I have not tried v4.2.6 + patch to see if it works because we need the functionality of v4.5 for our task. While the errors are in system include files, if you look at the line referenced in the error message, it has the _T( ) macro, which indicated to me that it was another wxt vs. Sun Studio issue.
Anonymous
2009-12-17
I've attached a text file with the make errors.
Ethan Merritt
2009-12-17
There are no _T() macros remaining in the gnuplot source code to either version 4.4 or 4.5.
Can you persuade the Sun compiler to produce more informative output? Even in the full listing you attached, there are no line references to indicate the problem site in the actual gnuplot source code. Until, that is, it starts complaining about the "mouse.h" header file and the lack of a definition for _Bool. That seems to indicate the problem may be with the definition of TBOOLEAN, but I can't tell whether this is also the cause of the earlier error messages. Also, I would have thought that a problem with booleans would have produced error messages in many gnuplot files, not just wxt_gui. I'm afraid that without more informative error messages, I don't know where to look for the problem.
Anonymous
2010-01-02
wxt_gui.cpp make errors with --verbose=all flag passed to CC
Anonymous
2010-01-02
I uploaded the output of make with the --verbose=all flag passed to the Sun compiler. As you mention below, the errors seem to be centered around the lack of a _Bool definition.
Ethan Merritt
2010-01-03
The relevant lines seem to be these, from syscfg.h:
#if HAVE_STDBOOL_H
# include <stdbool.h>
#else
# if ! HAVE__BOOL
# ifdef __cplusplus
typedef bool _Bool;
# else
typedef unsigned char _Bool;
# endif
# endif
# define bool _Bool
# define false 0
# define true 1
# define __bool_true_false_are_defined 1
#endif
They are supposed to guarantee that _Bool is defined, but for some reason this is failing on your machine. You would have to look deeper into the output of the configure script to determine, for example, if HAVE_STDBOOL_H was set during configuration, and you would have to look in your system's stdbool.h header to see if it indeed contains a definition for _Bool.
It is possible that everything will work correctly if you replace the definition of TBOOLEAN on line 443 in syscfg.h:
/* #define TBOOLEAN bool */
#define TBOOLEAN unsigned char
Anonymous
2010-01-05
make errors after syscfg.h mod
Anonymous
2010-01-05
system stdbool.h | http://sourceforge.net/p/gnuplot/bugs/824/ | CC-MAIN-2014-15 | refinedweb | 682 | 76.22 |
pipe(2) BSD System Calls Manual pipe(2)
NAME
pipe -- create descriptor pair for interprocess communication
SYNOPSIS
#include <unistd.h> int pipe(int fildes[2]);
DESCRIPTION
The pipe() function creates a pipe (an object that allows unidirectional data flow) and allocates a pair of file descriptors. The first descrip- tor connects to the read end of the pipe; the second connects to the write end. Data written to fildes[1] appears on (i.e., can be read from) generation of the SIGPIPE signal can be suppressed using the F_SETNOSIGPIPE fcntl command.
RETURN VALUES
On successful creation of the pipe, zero is returned. Otherwise, a value of -1 is returned and the variable errno set to indicate the error.
ERRORS
The pipe() call will fail if: [EFAULT] The fildes buffer is in an invalid area of the process's address space. [EMFILE] Too many descriptors are active. [ENFILE] The system file table is full.
SEE ALSO
sh(1), fork(2), read(2), socketpair(2), fcntl(2), write(2)
HISTORY
A pipe() function call appeared in Version 6 AT&T UNIX. 4th Berkeley Distribution February 17, 2011 4th Berkeley Distribution
Mac OS X 10.9.1 - Generated Mon Jan 6 10:25:04 CST 2014 | http://www.manpagez.com/man/2/pipe/ | CC-MAIN-2016-36 | refinedweb | 203 | 65.52 |
The delivery of web content is being revolutionized by a new technique known as syndication. The most common format for syndication is RSS, or Really Simple Syndication, an XML (eXtensible Markup Language) format for coordinating the
delivery of time-based content streams, or "feeds." This means that RSS can be
used to deliver content that changes over time. RSS provides for the inclusion
of additional data, similar to email attachments, using the <enclosure>
tag.
Through applications in Mac OS X Tiger, Apple has
added and expanded support for the RSS content, including the Safari browser, iTunes and iWeb. Podcasts are a form of RSS
enclosure as used in iTunes and iWeb. And Safari has arguably the best browser
support for RSS content. Through autodiscovery, an RSS client can notify a user
of an available feed (for example, the RSS badge in
Safari's address bar), and also subscribe on the user's behalf. Plus, there are
a number of tools available for developers and publishers that simplify the
process of generating, validating, and reading RSS feeds. We will explore each of these
topics in this article.
Note that there are several different interpretations of the
RSS acronym. "Really Simple Syndication" is one such interpretation. Others
include "RDF Site Summary" and "Rich Site Summary". RDF stands for "Resource
Description Framework."
The basic structure of an RSS feed is illustrated in Listing 1. The outer container is an <rss> tag that encloses a <channel>. The channel contains elements, or tags that collectively define the feed properties, much the way that a header contains metadata about an email message. Following the channel elements are items that define the actual feed content. Each item defines a unique entry, and a feed can contain multiple items. An <item> might define a headline, image, or audio file. The closing </channel> and </rss> tags follow the items (all tags must be closed to be valid XML). Not all of the tags included in this example are required. You can find more RSS syntax examples in the references listed at the end of this article.
Listing 1: RSS Feed Structure
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<!-- channel metadata -->
<title>ADC Feed</title>
<link></link>
<description>ADC headlines, new sample code, and docs.</description>
<!-- channel content -->
<item>
<!-- item content -->
<title>Intro To RSS</title>
<description>This article provides an overview of RSS. The enclosure references the podcast.</description>
<enclosure url=""" length="123456" type="audio/mpeg" />
</item>
</channel>
</rss>
Whether you are a web publisher or an application developer, time-based
streams represent the current trend in providing on-demand content. What is a
"time-based stream?" It is information that:
How does RSS relate to time-based streams? Blogging techniques provide a good example. In a static model, which does not use RSS, you might post your blog updates to a web server on a daily or weekly basis. Interested users will navigate to your site using a browser or blog reader software and read your enlightening observations on the state of the world, best programming practices, and so on. But manually checking for updates takes time, and that user will have to navigate back to your site to read your latest postings.
A more effective approach is to publish your blog updates via an RSS feed,
and allow subscribers (most commonly software acting on behalf of your users) to
check for, download, and display the updates. These activities can be performed
by many browsers, such as Safari, specialized feed readers, and web-based
aggregators such as Bloglines or My Yahoo! It is RSS that makes the feed
publish-and-subscribe model possible.
Like the content it delivers, the RSS specification is not static. And it is
redefining the market for content delivery. Consider "enclosures," which are
part of the RSS specification. RSS enclosures carry additional content with the
stream, similar to the way attachments carry additional information in an email
message. enclosure is a sub-element of item, and
defines a stream of data, including its URL, length in bytes, and MIME type (see
Listing 2). Podcasts are an example of enclosures. The audio and/or video stream
is sent in the body of the enclosure. Enclosures can also include documents and
photos.
enclosure
item
Listing 2: The Enclosure Sub-Element
<enclosure url=""" length="123456" type="audio/mpeg" />
Apple recently released RSS extensions in the <itunes:> namespace. (XML namespaces allow elements with the same name but different purposes to co-exist without interfering with each other.) These extensions allow podcast authors to improve the user experience in iTunes and other client applications that understand the <itunes:> namespace. For example, the <itunes:category> element can improve the way content is categorized, while <itunes:keywords> allows users to search on text keywords. The document Podcasting and iTunes: Technical Specification has more information on the iTunes tags.
There are a number of different feed specifications at this time, though most
attention remains focused on RSS 2.0 and Atom 1.0. Web publishers and developers
need to remain aware of changes to the landscape as specifications gain or fall
out of favor. The good news for publishers and developers on Mac OS X is that
Safari handles all the current specifications. Most popular RSS readers also
support both RSS and Atom.
Feed publishers can use a type of application called a "generator" to create
the RSS markup that makes your feed available. FeedForAll, for example, has a wizard that
walks you through the creation of RSS feeds, whether you want to publish a plain
RSS feed, a podcast feed, or a podcast with iTunes support.
You should also test your feed by using an RSS reader application such as NetNewsWire or an RSS-capable browser. Make sure the reader displays the feed without error. You should also check the feed against a validator, such as FEED Validator, to ensure that it is well-formed. Several other validators are available online; the MacTech article referenced at the end of this article contains a list of these plus other tools for generating and reading feeds.
Feed dates are specified in the <pubDate> and <lastBuildDate> channel elements. Listing 3 adds both of these elements to our first example. <pubDate> specifies the date on or after which the feed will be published. <lastBuildDate> specifies the date and time of the last feed update. At reader compares the timestamp of one of these tags with the last time the feed was cached locally, and if the time specified in the tag is newer, then the feed has been updated. The format of each of these tags should follow the convention specified in RFC 2822. The RFC is a little dry; Wikipedia has a summary. The time must be in 24 hour format (no AM or PM) and must include the time zone offset. Podcasting and iTunes: Technical Specification has more information.
Listing 3: Date Channel Elements
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<!-- channel metadata -->
<title>ADC Feed</title>
<link></link>
<description>ADC headlines, new sample code, and docs.</description>
<pubDate>Mon, 3 Apr 2006 15:00:00 -0800</pubDate>
<lastBuildDate>Mon, 3 Apr 2006 09:00:00 -0800</lastBuildDate>
<!-- snip -->
Important: <pubDate> also applies to items. Use it to specify the publication date of individual items within the channel.
Note: Incorrect date/time formatting is a common problem. Make sure your dates adhere to RFC 2822.
There are a couple of other tags that assist with date handling: <skipDays> and <skipHours>. These tags list the days of the week and hours of the day, respectively, during which the feed will not be updated. This additional schedule information can be used by a reader or aggregator to determine when not to check a feed for updates: if the intervening days or hours since the last update consist solely of values found in these tags for the feed, then the reader can assume that the feed has not been updated. Note, however, that some browsers or readers may ignore these tags.
In addition, the <ttl> or time-to-live tag, specifies the number of minutes during which a feed will not be updated; this is the length of time that a reader or aggregator should cache the feed. While optional, it is strongly recommended in order to minimize load on the server caused by too-frequent checks for update.
As a feed publisher, you cannot depend on all browsers or readers
supporting all these date and time tags. What should you do? Publishing
your feed on a server that properly supports Etags, and/or has the right mod dates, and so deals with HTTP conditional GET requests, is
your best bet for reducing load on your servers. The HTTP/1.1 Header
Field Definitions provide some additional detail on Etags.
Getting your feed noticed can be tough sometimes, but there is a convenient way to allow readers to discover your feed. You simply add a <link> element within the <head> element of your web page to specify that an RSS feed is available, and the URL at which to find it. Some web browsers use <link> elements to indicate the availability of a feed for a website: Safari displays an RSS button in its Address Bar.
Listing 4 shows the <link> syntax for both RSS and Atom. You can read more about the <link> type and title attributes on Mark Pilgrim's blog.
Listing 4: Support for Autodiscovery Using the Link Element
<link rel="alternate" type="application/rss+xml" title="RSS" href="">
<!-- or -->
<link rel="alternate" type="application/atom+xml" title="RSS" href="">
Another way to help people both find your feed, and know that it has been updated, is to send an XML-RPC message to a Ping server. Generally speaking, you should notify appropriate ping servers whenever you update your feed, as it helps both search engines and aggregators know your feed has been updated without having to explicitly poll your website. Some of the most popular servers are Technorati and blo.gs, though there are many others available. Which and how many ping servers you should contact depends on the type and scale of the audience you wish to reach, as well as the amount of work you want your computer to do every time you update your feed.
In addition to the documents discussed in this article, the documents, books, and articles below will help you find more specific information about RSS and Atom.
XMLHttpRequest
Updated: 2008-03-03
Get information on Apple products.
Visit the Apple Store online or at retail locations.
1-800-MY-APPLE | http://developer.apple.com/internet/deliveringcontentwithrss.html | crawl-002 | refinedweb | 1,775 | 54.63 |
<stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
char *
readline (const char *prompt);
environment variable. If that variable is unset, the default is
~/.inputrc.
If that file does not exist or cannot be read, the ultimate default is
/etc example, placing
M-Control-u: universal-argument
into the
inputrc
would make M-C-u execute the readline command
universal.
The name and key sequence are separated by a colon. There can be no
whitespace between the name and the colon. specifying
key sequences is
In addition to the GNU Emacs style escape sequences, a second
set of backslash escapes is available: modified
with the
bind
builtin command. The editing mode may be switched during interactive
use by using the
-o
option to the
set
builtin command. Other programs using this library provide
similar mechanisms. The
inputrc
file may be edited and re-read if a program does not provide
any other means to incorporate new bindings. execute.
The following is a list of the default emacs and vi bindings.
Characters mentioned are
bound to
self-insert.
Characters assigned to signal generation
Chet Ramey, Case Western Reserve University
chet.ramey@case.edu.
this manual page should be directed to
chet.ramey@case.edu.
It's too big and too slow. | http://linuxhowtos.org/manpages/3/readline.htm | CC-MAIN-2018-22 | refinedweb | 211 | 59.3 |
I am having trouble importing modules in python. Can someone help me so I can do object oriented programmed games.
Importing Modules in Python
Started by LeafieTail, Mar 12 2011 01:34 AM
3 replies to this topic
#1 Members - Reputation: 99
Posted 12 March 2011 - 01:34 AM
Sponsor:
#2 Members - Reputation: 198
Posted 12 March 2011 - 02:27 AM
Many people can probably help you, but you have to be more specific: show the error, the problematic import code, and whether the module is installed on your system.
#3 Members - Reputation: 154
Posted 13 March 2011 - 08:59 AM
import antigravity
Did you know that actually works?
You must have some weird error, since to import module foo, you do:
import foo
#4 Crossbones+ - Reputation: 2342
Posted 14 March 2011 - 09:05 PM
The most likely reason is that your module is not in the search path.
From the python module docs.
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight | http://www.gamedev.net/topic/597451-importing-modules-in-python/ | CC-MAIN-2014-42 | refinedweb | 170 | 64.64 |
Next: Structures with Mex-Files, Previous: Character Strings in Mex-Files, Up: Mex-Files [Contents][Index]
One can perform exactly the same operations on Cell arrays in mex-files as in oct-files. An example that duplicates the function of the celldemo.cc oct-file in a mex-file is given by mycell.c as shown below.
#include "mex.h" void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwSize n; mwIndex i; if (nrhs != 1 || ! mxIsCell (prhs[0])) mexErrMsgTxt ("ARG1 must be a cell"); n = mxGetNumberOfElements (prhs[0]); n = (n > nlhs ? nlhs : n); for (i = 0; i < n; i++) plhs[i] = mxDuplicateArray (mxGetCell (prhs[0], i)); }
The output is identical to the oct-file version as well.
[b1, b2, b3] = mycell ({1, [1, 2], "test"}) ⇒ b1 = 1 b2 = 1 2 b3 = test
Note in the example the use of the
mxDuplicateArray function. This is
needed as the
mxArray pointer returned by
mxGetCell might be
deallocated. The inverse function to
mxGetCell, used for setting Cell
values, is
mxSetCell and is defined as
void mxSetCell (mxArray *ptr, int idx, mxArray *val);
Finally, to create a cell array or matrix, the appropriate functions are
mxArray *mxCreateCellArray (int ndims, const int *dims); mxArray *mxCreateCellMatrix (int m, int n); | https://docs.octave.org/v4.4.0/Cell-Arrays-with-Mex_002dFiles.html | CC-MAIN-2022-40 | refinedweb | 207 | 60.55 |
Hi,
I am using the following lines of code to select features from a polygon layer by using the Redline (Line) tool.
var filter = new OM.filter.AnyInteract(geometry_of_redline_line);
vectorLayer.selectFeatureByFilter(filter);
I expect it returns all of the features from vectorlayer that interact th e Line. But it only returns polygons that interact with the vertices of Line tool (redline).
Using: oraclemaps version 2 javascript API
I wasn't able to reproduce this with 11.1.1.7.1 using the tutorial example E02 which I modified to use a Line instead of a polygon.
Could you provide more details (or maybe contact us offline and send us a test case).
jsharma, I was using 11.1.1.7 and then upgraded to 11.1.1.7.1 and the problem resolved. thanks.
.... However I have encountered some other issues:
mapviewer : 11.1.1.7.1, browser: firefox v22
1- The distance tool doesn't show distance.
2-The scalebar shows incorrect values.
3-When I turn on/off vector layers visibility programatically (e.g. vectorLayer.setVisible(false)) then the LayerControl Object will not update the check marks.
Futhuremore,
SRID:32639 (UTM PROJECTION)
Test case:
shapefile and Html link:
import shapefile> create theme> create tilelayer
Both (scale bar and distance toll errors) seem to be bugs. Can you file one?
also can you contact me (or lj) via email.
I don't have your email and couldn't find it. Please send me an email (c u t e c la ssic player <<at>> yahoo) and I will contact you. although I gave you a link to the file in my previous post. And what about the layer control?
p.s.
ignore spaces from the email address. | https://community.oracle.com/message/11099581?tstart=0 | CC-MAIN-2014-15 | refinedweb | 288 | 60.21 |
The Windows Phone 8 SDK allowed the developer to use the EmailComposerTask launcher to send emails from the application . One of the restrictions that it had was that the attaching file programmatically which was not possible.
The Windows Phone 8.1 SDK provides an option for the developer to send emails with attachment using the EmailMessage and EmailManager class .
Note that the Minimum supported phone version for the EmailMessage and the EmailManager is Windows Phone 8.1 .
1. EmailMessage
The EmailMessage class defines the actual email that will be sent. You can specify the recipients (To , CC , BC) , Subject and the Body of the email .
2. EmailManager
The EmailManager class is defined in the Windows.ApplicationModel.Email namespace . The EmailManager class provides a static method ShowComposeNewEmailAsync which accepts the EmailMessage as argument . The ShowComposeNewEmailAsync will launch the Compose email Screen with the EmailMessage which allows the users to send an email message.
How to Programatically Send Emails with attachment in Windows Phone 8.1 Apps ?
Step 1 : Lets create a file called “developerpublish.txt” within your application and return it . This will be the file that will be attached with the email.
Below is a sample code snippet on how to create a text file programmatically in Windows Phone 8.1.
// Creates a text file and returns it private static async Task<StorageFile> GetTextFile() { var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; var file = await localFolder.CreateFileAsync("developerpublish.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting); await Windows.Storage.FileIO.WriteTextAsync(file, "This is a developerpublish File"); return file; }
Step 2 : The next step would be create the instance of the EmailMessage and prepopulate the necessary fields. Lets attach the file that we received from the GetTextFile().
// Send an Email with attachment EmailMessage email = new EmailMessage(); email.To.Add(new EmailRecipient("test@developerpublish.com")); email.Subject = "Blog post by @isenthil"; var file = await GetTextFile(); email.Attachments.Add(new EmailAttachment(file.Name, file)); await EmailManager.ShowComposeNewEmailAsync(email);
Step 3 : When the EmailManager.ShowComposeNewEmailAsync method is called , You will be listed with the apps / email accounts that are configured on your phone . Select the email account from which you need to send email from .
Step 4 : This will display the Email Compose Dialog with the screen already filled with the EmailMessage data that was passed to the ShowComposeNewEmailAsync method. Clicking on the Send button in the application bar will send the email with the attachment .
How to share Text or Image to Whatsapp, Facebook, SMS, and other Social Network in Windows Phone 8.1 Runtime app?
and images?
It seems works only in Windows Phone 8.1 and not in Windows 8.1.. So if you any solution for Windows 8.1 then please share
Is there anyway to find out whether the email was sent or not? | http://developerpublish.com/windows-phone-8-1-and-windows-runtime-apps-how-to-2-send-emails-with-attachment-in-wp-8-1/ | CC-MAIN-2018-13 | refinedweb | 462 | 50.43 |
Timing a Pythonista endeavor
November 24, this post yesterday morning, he asked this question,
Does the base 10 expansion of 2^n always contain the digit 7 if n is large enough?
and wrote a little Python program that suggested the answer may be “yes” for [n > 72]. The program isn’t a proof, of course, it just tests up to [n = 10,000].
The program was, I thought, a little odd in that he created a set of all the digits in [2^n] rather than just doing a string comparison. I thought it worth looking into the relative speeds of doing it each way.1 Because my MacBook Air was all the way on the other side of the room, I decided this was a good chance to give Pythonista a try.
Here’s my first crack at the comparison. I copied the code from John’s post, pasted it into a new Pythonista script, and added some new functionality.
python: 1: #!/usr/bin/python 2: 3: def digits(n): 4: s = set() 5: while n > 0: 6: s.add(n%10) 7: n /= 10 8: return s 9: 10: def numerals(n): 11: return '%d' % n 12: 13: for i in range(71, 2000): 14: p = 2**i 15: if 7 not in digits(p): 16: print i, p 17: 18: for i in range(71, 2000): 19: p = 2**i 20: if '7' not in numerals(p): 21: print i, p
John’s original code had only the
digits function and the loop in Lines 13-16. Also, his
range in Line 13 had an upper limit of 10,000, not 2000; I lowered it to get reasonable run times on my iPhone 5.
As I said, it seemed more natural to me to turn the number [2^n] into a string and look for instances of the character
7. My function
numerals and the loop in Lines 18-21 solved the problem that way.
I should mention at this point that although Pythonista can run code that uses either spaces or tabs for indentation, code that’s written in Pythonista uses tabs. There is, at present, no way to tell the Pythonista editor to insert spaces when the Tab key is tapped. If you’re writing code from scratch, this is no problem, but because my script was a mix of pasted code (that used spaces) and original code (that used tabs), it threw indentation errors until I went in and replaced all my tabs with spaces.
I had a brief Twitter discussion about this with Pythonista’s developer, Ole Zorn, and he acknowledged the problem. I hope he adds the ability to auto-expand tabs, not just because I prefer spaces, but also because pasting and editing is probably a pretty common use case.
Once I got my script running, it was immediately clear that the string method was much faster than the set method. But how much faster? I decided to give the standard
timeit library a whirl. After fighting a bit with
timeit’s so-called convenience functions (which I’ll discuss in a bit), I ended up with this script:
python: 1: #!/usr/bin/python 2: 3: from timeit import timeit 4: 5: def digits(n): 6: s = set() 7: while n > 0: 8: s.add(n%10) 9: n /= 10 10: return s 11: 12: def numerals(n): 13: return '%d' % n 14: 15: def time_digits(n): 16: for i in range(72, n): 17: p = 2**i 18: if 7 not in digits(p): 19: print i, p 20: 21: def time_numerals(n): 22: for i in range(72, n): 23: p = 2**i 24: if '7' not in numerals(p): 25: print i, p 26: 27: for i in range(1, 5): 28: print i*1000 29: t = timeit('time_digits(i*1000)', 30: 'from __main__ import time_digits, i', 31: number=1) 32: print 'Digits: %f' % t 33: t = timeit('time_numerals(i*1000)', 34: 'from __main__ import time_numerals, i', 35: number=1) 36: print 'Numerals: %f' % t 37: print
The results were
1000 Digits: 1.845313 Numerals: 0.054590 2000 Digits: 8.365773 Numerals: 0.238395 3000 Digits: 21.571197 Numerals: 0.653563 4000 Digits: 43.310401 Numerals: 1.419421
which shows that the string method is more than an order of magnitude faster than the set method. This didn’t surprise me, there’s a lot of work being done in the
digits function.
Just for fun, I later ran the same script on my 2010 MacBook Air. The results were
1000 Digits: 0.233390 Numerals: 0.008770 2000 Digits: 1.266341 Numerals: 0.031867 3000 Digits: 3.823505 Numerals: 0.078629 4000 Digits: 8.306719 Numerals: 0.160169
which is less than an order of magnitude faster than the iPhone 5. I choose to see this as evidence that I have a fast phone, not that I have a slow laptop.
What I disliked about the
timeit function was that I needed to include the
from __main__ import code chunks as the second argument. When I first tried this script, I didn’t include those arguments and got errors like
NameError: global name 'time_digits' is not defined
I found the answer in this Stack Overflow discussion, but I wasn’t happy with it. The documentation refers to
timeit as a “convenience function,” but there’s nothing convenient about having to import the names of all your global variables and functions whenever you want to time them. It’s completely non-intuitive to have to import from
__main__ when I’m already in
__main__.
It’s not that I don’t understand the reasons behind it—I just think the library should take care of the importing for me when I’m using a convenience function in what must be the most common case: timing a function at the top level. This, like the clumsy way the
subprocess module works, is a case of Python being too Pythonic for its own good.
In summary:
- The Endeavor: good.
- Pythonista: good, but needs to auto-expand tabs.
- The
timeitlibrary: frustrating. Needs a Kenneth Reitz makeover. | http://leancrew.com/all-this/2012/11/timing-a-pythonista-endeavor/ | CC-MAIN-2017-39 | refinedweb | 1,025 | 79.19 |
Use Default Code Snippets in .NET to Accelerate Coding
Posted September 25, 2012 by Vishwanath Dalvi in Computer programming, Windows
Knowing how to use default code snippets in .NET is really beneficial for any programmer. Code snippets are pre-written codes in .NET which programmer can quickly insert using shortcut keys. This makes programmer’s job easy by not having to retype frequent reused structures of code.
Code snippets are an excellent way to accelerate your coding. Most frequently used code constructions are included. I’ll use MessageBox in my first sample.
Whenever you need to use MessageBox.Show method, you write the entire one line code like this:
MessageBox.Show(“Tech-recipes”);
But using default Code Snippets you could save time and build more productivity.
Type ‘mbox’ and press Tab key twice, and the Visual Studio IDE will fill in MessageBox.Show method for you.
MessageBox.show(“Test”);
Let us try another. Type ‘for’ and press Tab key twice. IDE will generate the loop syntax automatically.
for (int i = 0; i < length; i++)
{
}
Like this way, you can use the following default code snippets.
These are the available Code snippets in Visual Studio IDE.
#if Creates #if and #endif directive. #region Creates #region and #endregion directive. ~ Creates a Destructor. attribute Creates a declaration for a class that derives from Attribute. checked Creates a checked code block. class Creates a class declaration. ctor Creates a constructor. cw Creates a Console.Writline code block. do Creates a do while loop. else Creates an else code block. enum Creates an enum declaration. equals Creates a method declaration that overrides the Equals method. exception Creates a declaration for a class that derives from an exception. for Creates a for loop. foreach Creates a foreach loop. forr Creates a for loop with decrementing loop variable. If Creates a if block. Indexer Creates an index declaration. Interface Creates an interface declaration. Invoke Creates a block that invoke an event. Iterator Creates an iterator. Iterindex Creates a "named" iterator and indexer pair by using a nested class. lock Creates a lock block. mbox Creates a call to MessageBox.Show method. namespace Creates a namespace declaration. prop Creates an auto-implemented property declaration. propfull Creates a property declaration with get and set successors. propg Creates a read-only auto-implemented property with a private "set" accessor. sim Creates a static int Main method declaration. struct Creates a struct declaration. svm Creates a static void Main method declaration. switch Creates a switch block. try Creates a try-catch block. tryf Creates a try-finally block. unchecked Creates an unchecked block. unsafe Creates an unsafe block. using Creates a using directive. while Creates a while loop.
About Vishwanath Dalvi
View more articles by Vishwanath Dalvi
The Conversation
Follow the reactions below and share your own thoughts. | http://www.tech-recipes.com/rx/21217/use-default-code-snippets-in-net/ | CC-MAIN-2017-09 | refinedweb | 467 | 63.76 |
In this tutorial we are going to create a simple image gallery powered by Google's Picasa Web Albums. In order to enhance the user's experience, we'll throw some jQuery into the mix and create a scrollable album carousel.
Overview
We are going to use PHP's SimpleXML extension to sort and access the data inside the XML feed provided by Picasa Web Albums. jQuery will be responsible for the DOM manipulation and AJAX request. We are also going to use the Scrollable library, which is part of jQuery Tools to create the carousel. Next, we'll use jQuery's MouseWheel plug-in to allow for cross-browser mouse wheel support. Finally, we'll use the Fancybox plug-in to each image in a "lightbox."
What We Need
- Picasa Web Album ID (usually the same as your Gmail or Google account ID)
- PHP with SimpleXML (it is enabled by default with new PHP install)
- Latest jQuery
- Recently Discovered jQuery Tools from flowplayer.org
- Fancybox plug-in for jQuery
- 960 Grid CSS (it is not required but I'm using it in this tutorial)
Getting Started
We'll begin by downloading the files and putting them into the same folder. I also combined all of the Fancybox images with jQuery Tools ones, and placed them inside the img folder.
PHP files
For our project, we are going to use following PHP files:
- index.php
- _ajax.php
- _conf.php
- index.php will be responsible for displaying albums, images, and sending requests to _ajax.php.
- _ajax.php will be handling dynamic request and returning formatted thumbnails
- _conf.php, as you may have guessed, will contain some configuration information that will be used by both files.
_code.php
This file is very simple and short.
// First we need to set some defaults $gTitle=""; // title of your gallary, if empty it will show: "your nickname' Photo Gallary" $uName= "kozlov.m.a"; // your picasaweb user name $tSize="72c"; // thumbnail size can be 32, 48, 64, 72, 144, 160. cropt (c) and uncropt (u) $maxSize="720u"; // max image size can be 200, 288, 320, 400, 512, 576, 640, 720, 800. These images are available as only uncropped(u) sizes.
Basically, in this file we set the username (Picasa Web Album ID), thumbnail size, and max image size that we are going to show in our gallery.
index.php
This file requires a bit more to make the gallery work. We begin with referencing our configuration file (_conf.php):
<?php include './_conf.php'; // getting constants
Next we need to load the album feed. We are only retrieving publicly available albums, so our request will look something like: "".
<code> $file = file_get_contents("".$uName."?kind=album&access=public&thumbsize=".$tSize); </code>
file_get_contents will load content from the XML feed into $file variable. As you can see, we used the $uName variable defined in _conf.php to get the right feed. We also passed the additional parameter "thumbsize;" so that the returned feed will contain thumbnails of our chosen size.
Now, let's convert the contents of the feed into a SimpleXml object and define the namespaces we are going to use:
$xml = new SimpleXMLElement($file); $xml->registerXPathNamespace('gphoto', ''); $xml->registerXPathNamespace('media', '');
You can find all namespaces used in the API feeds by visiting..., but we'll only be using "media" and "gphoto" in our tutorial; you do not have to worry about the rest of them.
Next, we'll get the web album's name in case we did not already set one in __conf.php file:
if($gTitle == null){ // if empty Gallery title will be "user id's Photo Gallery" $nickname = $xml->xpath('//gphoto:nickname'); // Mikhail $gTitle =$nickname[0]."'s Photo Gallery"; } ?>
Finally, it is time for some simple HTML. We'll set our header and reference a few CSS files.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""> <html> <head> <title><?php echo $gTitle; ?></title> <link rel="stylesheet" href="reset.css" type="text/css" /> <link rel="stylesheet" href="960.css" type="text/css" /> <link rel="stylesheet" href="style.css" type="text/css" /> <link rel="stylesheet" href="fancybox.css" type="text/css" /> </head> <body> <div class="container_16"> <div class="grid_16"> <?php echo "<h1>". $gTitle ."</h1>";?>
As you can see, we've set the page title to $gTitle and have added some CSS to make things pretty.
Style Files
I do not think that reset.css needs any additional explanation, so let's skip over it and take a closer look at the other stylesheet.
- 960.css allows for a more grid-like layout.
- style.css comes from the provided stylesheet from jQuery Tools.
- And fancybox.css is part of the FancyBox plug-in.
Note: Please make sure that you change image path in both fancybox.css and style.css, so all background images point to img folder.
Album Holder and Navigational Elements
It is time to create our album holder and navigational elements. This is where jQuery Tools is a huge help. For the album navigation, we'll be using the Scrollable library. If you visit the Scrollable reference page and take a look at some of the examples, you'll see that we're using it almost without any modifications.
<div> <a id="prev"> </a> <!-- Prev controll--> </div> <div id="albums"> <div> <!-- php code will go here --> </div> </div> <div> <a id="next"> </a><!-- Next controll--> </div> <div> </div> <div id="navi"></div> <!-- Pagination holder--> <div> </div>
We'll also need a holder for the album picture thumbnails, and the album title that will be loaded via AJAX:
<h2 id="a_title"></h3> <div id="pic_holder"> </div> </div> </div>
JavaScript
Let's finish our page by referencing the JavaScripts we'll be using.
<script type="text/javascript" language="JavaScript" src=""></script> <script type="text/javascript" language="JavaScript" src="jquery.tools.min.js"></script> <script type="text/javascript" language="JavaScript" src="jquery.easing.1.3.js"></script> <script type="text/javascript" language="JavaScript" src="jquery.fancybox-1.2.1.pack.js"></script> </body> </html>
PHP
Now it is time to go through the XML file and sift the album thumbnails out. Place the following PHP code inside the </div element.
<?php foreach($xml->entry as $feed){ $group = $feed->xpath('./media:group/media:thumbnail'); $a = $group[0]->attributes(); // we need thumbnail path $id = $feed->xpath('./gphoto:id'); // and album id for our thumbnail echo '<img src="'.$a[0].'" alt="'.$feed->title.'" title="'.$feed->title.'" ref="'.$id[0].'" />'; ?> }
Our plan was to load album pictures once visitors click on a specific thumbnail, therefore we have to create some kind of reference to connect the two. For this purpose, we are putting a ref attribute into each album's img tag; so it will look something like this when compiled:
<img ref="5364767538132778657" title="2009-07-31 - Beach Ocean City, MD" alt="2009-07-31 - Beach Ocean City, MD" src="" />
AJAX
Finally, we'll spice it all up with some jQuery. Firstly, we need to initialize the jQuery Tools plug-in with some additional parameters:
$("div.scrollable").scrollable({ size: 10, // number of pictures per "page" next: '#next', // id of next control element prev: '#prev', // id of prev control element navi:'#navi' // id of navigation control holder });
The code above will automatically add scrollable controls.
Note: It is better to set the scrollable size to an odd number. This way, selected images will appear right in the middle.
Next we'll create on click event for the album thumbnail:
$("#albums img").bind("click", function(){ $("#a_title").text($(this).attr('title')); $("#pic_holder").html('<div><img src="/images/loading.gif" alt="Loading..."></div>').load("_ajax.php",{"aID":$(this).attr("ref")},function(){ $("#pic_holder").find("a").fancybox(); }); });
Let's take close look at what we are doing here. First we define our click event trigger:
$("#albums img").bind("click", function(){
We use bind instead of the simple click because we do not want to interrupt the work of the scrollable plug-in that we just initiated above.
Next, we'll apply the album title into the h2 tag with id "a_title" from the title attribute of the anchor tag:
$("#a_title").text($(this).attr('title'));
Finally, we send an AJAX request to _ajax.php and let Fancybox re-index the freshly loaded images:
$("#pic_holder").html('<div><img src="/images/loading.gif" alt="Loading..."></div>').load("_ajax.php",{"aID":$(this).attr("ref")},function(){ $("#pic_holder").find("a").fancybox(); });
As you probably noticed, we are inserting a "loading image" inside "pic_holder" before sending the AJAX request. This will provide the user with some feedback to let them know that their request is currently being processed. Once we receive a response from the server, jQuery will replace the contents of the "pic_holder" with data that came from _ajax.php.
_ajax.php
Now it is time to serve the contents of the album to our visitors. Our plan is to show thumbnails linked to originals on the Picasa server. Once a thumbnail is clicked, Fancybox will take over and create a lightbox-like image gallery. We'll start with the entire contents of the file, and then go over each line:
<?php include './_conf.php'; // getting constants if(isset($_POST['aID'])){ $aID = $_POST['aID']; // let's put album id here so it is easie to use later $file = file_get_contents(''.$uName.'/albumid/'.$aID.'?kind=photo&access=public&thumbsize=72c&imgmax='.$maxSize); // get the contents of the album $xml = new SimpleXMLElement($file); // convert feed into SimpleXML object $xml->registerXPathNamespace('media', ''); // define namespace media foreach($xml->entry as $feed){ // go over the pictures $group = $feed->xpath('./media:group/media:thumbnail'); // let's find thumbnail tag $description = $feed->xpath('./media:group/media:description'); // file name appended by image captioning if(str_word_count($description[0]) > 0){ // if picture has description, we'll use it as title $description = $feed->title. ": ". $description[0]; }else{ $description =$feed->title; // if not will use file name as title } $a = $group[0]->attributes(); // now we need to get attributes of thumbnail tag, so we can extract the thumb link $b = $feed->content->attributes(); // now we convert "content" attributes into array echo '<a rel="'.$aID.'" href="'.$b['src'].'" title="'.$description.'"><img src="'.$a['url'].'" alt="'.$feed->title.'" width="'.$a['width'].'" height="'.$a['height'].'"/></a>'; } }else{ echo 'Error! Please provide album id.'; } ?>
First, we are going to reference our configuration file, so we can have access to the constant parameters: Picasa ID and thumbnail size.
include './_conf.php'; // getting constants
Then we'll check if the album ID was sent via POST request:
if(isset($_POST['aID'])){
If we did not find an album ID, we're simply going to print an error message:
}else{ echo 'Error! Please provide album ID.'; }
If _ajax.php received the album ID, we'll get an XML feed and start working on it, so let's create a link to the correct XML feed:
$aID = $_POST['aID']; // let's put the album id here so it is easier to use later $file = file_get_contents(''.$uName.'/albumid/'.$aID.'?kind=photo&access=public&thumbsize=72c&imgmax='.$maxSize); // get the contents of the album
As you can see, we use the album ID that came via the POST request as well as constants from _conf.php file. Again, we are using file_get_contents to load the XML feed and store it in the $file variable. Next we convert it to a SimpleXMLElement object cycle through each entry nodes that contain information about each picture. To do so, we'll use a simple foreach() loop.
foreach($xml->entry as $feed){ // go over the pictures
Next, we are ready to extract data needed for our link and thumbnail. I've commented every line and hopefully it is enough to understand what is going on:
$group = $feed->xpath('./media:group/media:thumbnail'); // let's find the thumbnail tag $description = $feed->xpath('./media:group/media:description'); // let's find the description tag if(str_word_count($description[0]) > 0){ // if the picture has description, we'll use it as the title $description = $feed->title. ": ". $description[0]; // file name appended by image captioning }else{ $description =$feed->title; // if not, will use file name as title } $a = $group[0]->attributes(); // now we need to get attributes of thumbnail tag, so we can extract the thumb link $b = $feed->content->attributes(); // now we convert "content" attributes into array
Finally, we are putting it all into HTML context. We'll echo a link to the original image and thumbnail image:
echo '<a rel="'.$aID.'" href="'.$b['src'].'" title="'.$description.'"><img src="'.$a['url'].'" alt="'.$feed->title.'" width="'.$a['width'].'" height="'.$a['height'].'"/></a>';
To force Fancybox to organize all of the images into a gallery, we are adding the rel attribute to each link. You can simply put same number or string as value, but I'm going to use the album ID.
Styling
As I mentioned before, most of the styling was taken straight from examples at the jQuery Tools website. All you must do here is simply adjust the height and width to suit the design of your website.
Mouse Wheel Scroll
Mouse Wheel Scroll is another beauty that you can easily use. As some may have noticed, we never initiated this plug-in; yet, if you hover over the album carousel and try to scroll with your mouse wheel, it will work thanks to jQuery Tools.
Conclusion
We've learned how to combine PHP's SimpleXML extension with a handful of plugins and Picasa to create a beautiful and dynamic image gallery. I hope you enjoyed and learned from it!
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles.
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/how-to-create-an-image-gallery-powered-by-picasa--net-7292 | CC-MAIN-2017-30 | refinedweb | 2,277 | 55.74 |
You want to read the data from a recordset.
Use the RecordSet.getItemAt( ) method to get a record at a particular index. Use RecordSet.getColumnNames( ) to get an array of the column names.
You can think of recordsets as being composed of rows and columns, like a grid. Each row represents a single record, and each column represents a field within each record. All recordsets have a getItemAt( ) method that returns a record object at a given row index.
#include "NetServices.as" // Create a recordset and populate it using addItem( ) (see Recipe 21.1). rs = new RecordSet(["COL0", "COL1", "COL2"]); rs.addItem({COL0: "a", COL1: "b", COL2: "c"}); rs.addItem({COL0: "d", COL1: "e", COL2: "f"}); rs.addItem({COL0: "g", COL1: "h", COL2: "i"}); // Get a single record from the recordset using getItemAt( ). record1 = rs.getItemAt(1); // Output the values from the record object. Displays: d e f trace(record1.COL0 + " " + record1.COL1 + " " + record1.COL2);
The getItemAt( ) method is all you need, as long as you know the column names. However, if you do not already know the column names (remember, recordsets are often retrieved from the server), use the getColumnNames( ) method to get an array of the recordset's column names. You can then use that array to loop through all the columns of a given recordset.
// Get a record from the recordset. record1 = rs.getItemAt(1); // Retrieve the column names. columnNames = rs.getColumnNames( ); /* Loop through all the columns and output the values for the record. Outputs: COL0: d COL1: e COL2: f */ for (var i = 0; i < columnNames.length; i++) { trace(columnNames[i] + ": " + record1[columnNames[i]]); }
You can also use the RecordSet.getLength( ) method to determine the number of records that a recordset contains. Using this value, you can loop through all the records.
// Get the column names. columnNames = rs.getColumnNames( ); // Loop through each record in the recordset from 0 to the length, as returned by // getLength( ). for (var i = 0; i < rs.getLength( ); i++) { // Display the record number. trace("record " + i); /* Loop through each column for each record and output the values. Displays: record 0 COL0: a COL1: b COL2: c record 1 COL0: d COL1: e COL2: f record 2 COL0: g COL1: h COL2: i */ for (var j = 0; j < columnNames.length; j++) { trace(" " + columnNames[j] + ": " + rs.getItemAt(i)[columnNames[j]]); } }
You can create a custom method that allows you to write the recordset data to the Output window during testing. The RecordSet.trace( ) method, as shown in the following code block, uses the same logic as the preceding code:
RecordSet.prototype.trace = function ( ) { var columnNames = this.getColumnNames( ); for (var i = 0; i < this.getLength( ); i++) { trace("record " + i); for (var j = 0; j < columnNames.length; j++) { trace(" " + columnNames[j] + ": " + this.getItemAt(i)[columnNames[j]]); } } }; // Example usage (if rs contains a recordset): rs.trace( ); | http://etutorials.org/Programming/actionscript/Part+II+Remote+Recipes/Chapter+21.+Recordsets/Recipe+21.2+Reading+Recordsets/ | CC-MAIN-2018-09 | refinedweb | 469 | 77.13 |
CodePlexProject Hosting for Open Source Software
I need to know whenever a item containing a part get published.
When any item that contains the part gets published I would like to go ahead and call a service passing along all of the items information.
Does that make sense? Anyone know if there is an event that I can hookup to or something like that?
Thanks,
I don't know of any such event, so you may have to write your own.
I think the OnPublishing would probably work. However, I didn't see something there that would allow me to fail the publication, for instance.
As I would like to get all the information from the item, then submit it to another service for additional validation.
Sure, but you mentioned when "the part" gets published, which suggests to me not just a content item with any part but a specific part. I don't think there's a configuration option for that out of the box.
Sorry, I meant a content item that a particular part, a part that I created. In that case OnPublishing would solve the problem for me, I just don't know how to stop the publishing if my call to my service fails or I get some error indicator from it.
Perhaps you mean a Content Type that you created? Because you do get to specify that.
Out of the box, there is the OnPublished event (I did not see an OnPublishing event. If you do, then please ignore the rest of this post :).
Handling the OnPublished event would be too late for you to cancel publication, so you would probably have to implement your own event that is triggered during the OnPublishing event ("contenthandler" event, not "rules" event). The OnPublishing
event receives a context that has a Cancel property that you can set to cancel the item from being published.
However, even when you do implement your own "OnPublishing" event and trigger that from your content handler, I don't think there's currently a way to inspect results from actions in order to set the Cancel property of the PublishContentContext.
Now I happen to know that Sebastien is working on some very cool workflow implementation that may replace the rules engine, which may support this kind of scenario without writing code, I don't know.
However, until then, you could implement a content handler in code that simply cancels the publication of the content item if your service call fails by handling the OnPublishing event.
This is kind of what I am looking for:
public class CustomPartHandler : ContentHandler
{
private readonly INotifier _notifier;
private readonly Localizer _T;
public ProductPartHandler(IRepository<CustomPartRecord> repository, INotifier notifier)
{
Filters.Add(StorageFilter.For(repository));
_notifier = notifier;
_T = NullLocalizer.Instance;
OnPublishing<CustomPart>((context, part) =>
{
// call service
if (callFailed)
{
_notifier.Error(_T("Publication failed!"));
context.Cancel();
}
});
}
}
This context does not have a cancel and I couldn't really find a cancel in the source code.
And let me try to explain again what I am trying to do: I want to create a part that can be attached to any type. Now, the user can create a type, attach the part and when the user tries to publish an item that contains that part I want to run some custom
validation and then depending on what happens there cancel the whole publication.
I see. It's a new property and is available when you're cloning the 1.x branch, so it is not part of 1.6 but will be part of 1.7:
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://orchard.codeplex.com/discussions/429354 | CC-MAIN-2017-13 | refinedweb | 630 | 61.97 |
• A component can contain multiple public activatable classes as well as additional classes that are internal only. All public classes must reside in the same root namespace, which has the same name as the component metadata file. • By default, all public classes in a component are visible to all other languages. A class can be hidden from JavaScript by applying the WebHostHiddenAttribute (that is, prefix the class declaration with [Windows.Foundation.Metadata.WebHostHidden] in C# or [Windows::Foundation::Metadata::WebHostHidden] in C++. This is appropriate for classes that work with UI (that cannot be shared with JavaScript, such as the whole of the Windows.Xaml namespace in WinRT) or others that are redundant with JavaScript instrinsics (such as Windows.Data.Json). • For some additional structural options, see the following samples in the Windows SDK (all of which use the WRL; see “Sidebar: The Windows Runtime C++ Template Library” under “Quickstart #2”): • Creating a Windows Runtime in-process component sample (C++/CX) • Creating a Windows Runtime in-process component sample (C#) • Creating a Windows Runtime EXE component with C++ sample • Creating a Windows Runtime DLL component with C++ sample Types • Within a component, you can use native language types (that is, .NET types and C++ runtime types). At the level of the component interface (the Application Binary Interface, or ABI), you must use WinRT types or native types that are actually implemented with WinRT types. Otherwise those values cannot be projected into other languages. In C++, WinRT types exist in the Platform namespace, and see Type System (C++/CX); in C#/VB, they exist in the System namespace, and see .NET Framework mappings of Windows Runtime types. • A component can use structures created with WinRT types, which are projected into JavaScript as objects with properties that match the struct members. • Collections must use specific WinRT types found in Windows.Foundation.Collections, such as IVector, IMap (and IMapView), and IPropertySet. This is why we’ve often encountered vectors throughout this book. • Arrays are a special consideration because they can be passed only in one direction as we saw in the quickstarts; each must therefore be marked as read-only or write-only. See Passing arrays to a Windows Runtime component. Arrays also have a limitation in that they cannot be effectively used with async methods, because an output array will not be transferred back to the caller when the async operation is complete. We’ll talk more of this in “Implementing Asynchronous Methods” below. 732
Component Implementation • When creating method overloads, make sure the arity (the number of arguments) is different for each one because JavaScript cannot resolve overloads only by type. If you do create multiple overloads with the same arity, one of them must be marked with the DefaultOverloadAttribute so that the JavaScript projection knows which one to use. • A delegate (an anonymous function in JavaScript parlance) is a function object. Delegates are used for events, callbacks, and asynchronous methods. Declaring a delegate defines a function signature. • The event keyword marks a public member of a specific delegate type as an event. Event delegates—the signature for a handler—can be typed (that is, EventHandler), which means that the eventArgs to that handler will be an object of that type. Do note that typed event handlers like this, to support projection into JavaScript, require a COM proxy/stub implementation; see the four samples linked to above in the “Component Structure” section. Also see the topic Custom events and event accessors in Windows Runtime Components for .NET languages. • Throwing exception: use the throw keyword in C#, VB, and C++. In C#/VB, you throw a new instance of an exception type in the System namespace. In C++, you use throw ref new with one of the exception types within the Platform namespace, such as Platform::InvalidArgumentException. These appear in JavaScript with a stack trace in the message field of the exception; the actual message from the component will appear in Visual Studio’s exception dialog. Implementing Asynchronous Methods For as fast as the C# and C++ routines that we saw in the quickstarts might be, fact of the matter is that they still take more than 50ms to complete while running on the UI thread. This is the recommended threshold at which you should consider making an operation asynchronous. This means running that code on other threads such that the UI thread isn’t blocked at all. To see the basics, the following sections show how to implement asynchronous versions of the simple countFromZero function we saw earlier in the “Sidebar: Managed vs. Native” section. We’ll do it first with a worker and then in C# and C++. For C#/VB and C++ there is quite extensive documentation on creating async methods. The cookbook topics we’ve referred to already cover this in the subsections called Asynchronous operations and Exposing asynchronous operations for C#, and the “Adding asynchronous public methods to the class” section in the C++ walkthrough. There is also Creating Asynchronous Operations in C++ for Windows Store apps, along with a series of comprehensive posts on the Windows 8 Developer Blog covering both app and component sides of the story: Keeping apps fast and fluid with asynchrony in the Windows Runtime, Diving Deep with Await and WinRT, and Exposing .NET tasks as WinRT asynchronous operations. Matching the depth of these topics would be a pointless exercise in 7 | https://www.yumpu.com/en/document/view/59794928/microsoft-press-ebook-programming-windows-8-apps-with-html-css-and-javascript-pdf/733 | CC-MAIN-2018-26 | refinedweb | 900 | 51.38 |
Code crashing when using multiprocessing.Pool
Hey all!!
My first post here! Exciting.
I'm starting to learn drawBot lately, things are developing pretty well by now. But so are my scripts and the complexity. It now takes me 2 hours to render 8 seconds with 24 fps... Hmm yeah, this way I can do only 4 renders in one working day. That's not gonna fly
(yes, I could cleanup and make it more efficient. But I want the code flexible and modular for reuse)
I was looking at multiprocessing paralell processing for the loop, since this is a simple repetitive loop that doesn't share data with another item/frame.
BUT! it seems to crash when using drawBot in the pool. I've undressed the code as much as possible to get to the essence.
-- Edit --
Forgot to mention that the process just crashes without an error. Just gives me a crash popup and the console seems to freeze. I can still cancel in the console with command-c though to exit.
-- End edit --
As for the question.
How could I fix this or is there another/better way for multiprocessing?
import multiprocessing import drawBot canvasWidth = 500 canvasHeight = 500 fps = 12 seconds = 10 duration = 1 / fps frames = seconds * fps def run(frame): print("frame: ", str(frame)) drawBot.newDrawing() # start from scratch, no multipage drawBot.newPage(canvasWidth , canvasHeight) # do cool stuff drawBot.saveImage(savePath + str(frame) + ".png") if __name__ == '__main__': savePath = '_export/export_' p = multiprocessing.Pool(processes = multiprocessing.cpu_count()-1) for frame in range(frames): p.apply_async(run, [frame]) p.close() p.join() print("Complete")
Jumping to
multiprocessingseems like a very pro-level step.
I would encourage you to find out what takes some much time?
I would not generate high def 5k video's... The size of the canvas determines a to the generation time.
User @MauriceMeilleur did already some heavy research on generating big data videos. The big speed up was to generate each frame into a folder and collect every frame in a move afterwards. This prevents your memory to be flooded the data for every frame.
A big win can also be achieved by installing drawBot as module and run
drawBotapp-less
import drawBot from drawBot.context.tools.mp4Tools import generateMP4 frames = 5 destinationPath = "/path/to/save/final/movie.gif" frameRate = 1/30 images = [] for i in len(frames): drawBot.newDrawing() drawBot.newPage(200, 200) # do stuff path = "/path/to/save_%s.png" % i drawBot.saveImage(path) images.append(path) generateMP4(images, destinationPath, frameRate)
also see
Hey @frederik, thanks for your reply!
Yeah,I've tried that approach already. Problem is that this takes even longer somehow. I've tried both options three times each. ( export as one gif and option 2 export seperate pngs and stitch them together.) But after 3 runs of each I found out it took 150% of the time exporting seperate png's compared to one gif option. (might have been because other processes? But I took 3 tests of each.)
And yes, I know the bottleneck of my script. It's not the size but the amount in the loops. Per frame I generate 80 rows and 100 columns of unique paths. Which comes down to 2400 paths per frame.
And yes, I know of a way to simplify this. But I really don't want to, since it will create different problems.
Debugging I get this error
objc[65010]: +[NSBezierPath initialize] may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug.
I focus on this:
We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug.
Googeling on this I find that this might be a security thing in OSX.
woeps could you show an example code that ends up in this error?
and threading slows things down in most cases.
Success!! But more on that later
@frederik, the error is from the code above. It was run from PyCharm. I think it gives a more detailed feedback?
Apparently there was an update with MacOs 10.13 that disabled some python functions. Throwing this error.
And yes, my goal is to mulitprocess and not multithread.
I've tied a different approach as described in this document:
Instead of fork() I now try spawn() and this seems to work!!! I've tested my script 3 times without multiproc and got 3 x 73 minutes.
And with multiproc I got 2 results of 34 minutes and one result of 13 minutes. Now that's a difference...
Too bad I only got 13 min once.
I'll post my stripped code later so you can see the concept and maybe someone can optimize it.
For example, I've got 60 frames and it launches 60 processes at once.
- MauriceMeilleur last edited by.
Hey @MauriceMeilleur, thanks for your reply!
Yeah, I saw your thread. Largest part of my implementation is based on that solution
I think you and @justvanrossum would recognize the code. Also Just would recognize more I think. In this demo/test I've used a basic animation he showed us at a workshop in Amsterdam.
I've been able to reproduce the 13 minute times again. Turns out I got impatient running the last to test counts and opened some applications to return to work on other projects. After closing all apps and just let the script run I was able to get the same 13 minutes counts again. 1/5 of the serial processing time.
This is my solution so far. it is based on: Drawbot on something more powerful than desktops and laptops?
I have 3 files for this:
- settings.py # these save the global settings. Would be a waste to (re)set them in both (all) the files.
- main.py # yeah, well the main script
- export_gif.py # after exporting I run this script to combine all the images to one animated gif file.
I'll show you the stripped base for this script. But first let me show you the base of the solution and work in progress: the part that calls multiple processes (with separated memory, if I'm not mistaken)
I still have two main obstacles to cross. I'll talk about them after the script. But first I'll show you the main part I'm currently focusing on, namely the multiprocessing part.."
That was the main focus. Now let's see all the scripts combined:
The settings.py are to share the same settings between, in this case, both scripts.
# settings.py canvasWidth = 500 canvasHeight = 500 fps = 12 seconds = 10 duration = 1 / fps frames = seconds * fps pathExport = '___export/' exportFileName = "export_" exportFileType = "gif"
The main.py. run() has two demo parts. One that creates an image to see you can create an animated gif out of it. (code from workshop with Just) And one part that puts some load on the processors. (without this part in this demo it would actually be more efficient to run the code in serial instead of parallel
Also, I've included a main() and main_mp(). One runs a serial loop and the other is the parallel multiproc. ( so I can benchmark both approaches)
# main.py import multiprocessing import datetime import drawBot # import settings as set def run(args): frame = args[0] print( "frame: ", frame) drawBot.newDrawing() # start from scratch, no multipage drawBot.newPage(set.canvasWidth, set.canvasHeight) time = frame / set.frames # teken een achtergrond drawBot.fill(1) # wit drawBot.rect(0, 0, set.canvasWidth, set.canvasHeight) drawBot.fill(0) # zwart angle = drawBot.radians(360 * time) x = set.canvasWidth / 2 + 100 * drawBot.sin(angle) drawBot.oval(x - 100, 200, 200, 200) drawBot.saveImage( set.pathExport + set.exportFileName + str(frame) + "." + set.exportFileType ) for i in range(20): frame = frame * frame." def main(): for frame in range(set.frames): run( [ frame ] ) if __name__ == '__main__': startTime = datetime.datetime.now() #main_mp() main() print(datetime.datetime.now() - startTime) print("--End--")
And last but not least the export_gif.py
The input has to be gif for it to also output gif.
# export_gif.py import settings as set def exportGif(): from drawBot.context.tools.gifTools import generateGif destinationPath = set.pathExport + "/movie.gif" images = [] durations = [] for frame in range(set.frames): path = set.pathExport + set.exportFileName + str(frame) + "." + set.exportFileType images.append(path) durations.append(set.duration) generateGif(images, destinationPath, durations) if __name__ == '__main__': exportGif()
So, my main issue at this time is:
main_mp() is not finished yet. It's not using the/a queue. Which results in the script starting (in this case) 120 individual processes. Running all of them together is, I'm sure, not efficient. It switches between them all the time.
multiprocessing.cpu_count()
This gives the the information I have 8 cpu cores available. I think it would be more interesting to have cpu_count()-1 running.
As for my question at this moment:
Does anyone know how to make main_mp() more efficient and/or how to properly implement a processing queue?
New intrigued question:
Also, @MauriceMeilleur, could you elaborate on you mentioning placing saveImage() outside the for-loop? How would you accomplice that?
I might have found a solution. I have to go somewhere soon, so I don't have much time to double check my findings. But I've added a function for making a working pool:
def main_pool(): multiprocessing.set_start_method('spawn') p = multiprocessing.Pool( processes = (multiprocessing.cpu_count()-1)) p.map(run, range(set.frames)) p.close
main() # serial processing in 15.65 seconds
main_mp() # multiprocessing in 10.50 seconds
main_pool() # multiprocessing with a pool in 4.55 seconds
I have only tried this with the script above. But not with my bigger project.
Now, I think what remains is some insight on saveImage() outside a loop.
Im not very familiar with multiprocessing and how to get the full potential out of it. But please report back!
- MauriceMeilleur last edited by MauriceMeilleur
!
@fred. | https://forum.drawbot.com/topic/65/code-crashing-when-using-multiprocessing-pool/6 | CC-MAIN-2019-13 | refinedweb | 1,667 | 69.38 |
#include <Spectra/SymEigsSolver.h>
This class implements the eigen solver for real symmetric matrices, i.e., to solve \(Ax=\lambda x\) where \(A\) is symmetric.
Spectra is designed to calculate a specified number ( \(k\)) of eigenvalues of a large square matrix ( \(A\)). Usually \(k\) is much less than the size of the matrix ( \(n\)), so that only a few eigenvalues and eigenvectors are computed.
Rather than providing the whole \(A\) matrix, the algorithm only requires the matrix-vector multiplication operation of \(A\). Therefore, users of this solver need to supply a class that computes the result of \(Av\) for any given vector \(v\). The name of this class should be given to the template parameter
OpType, and instance of this class passed to the constructor of SymEigsSolver.
If the matrix \(A\) is already stored as a matrix object in Eigen, for example
Eigen::MatrixXd, then there is an easy way to construct such a matrix operation class, by using the built-in wrapper class DenseSymMatProd that wraps an existing matrix object in Eigen. This is also the default template parameter for SymEigsSolver. For sparse matrices, the wrapper class SparseSymMatProd can be used similarly.
If the users need to define their own matrix-vector multiplication operation class, it should define a public type
Scalar to indicate the element type, and implement all the public member functions as in DenseSymMatProd.
Below is an example that demonstrates the usage of this class.
And here is an example for user-supplied matrix operation class.
Definition at line 134 of file SymEigsSolver.h.
Constructor to create a solver object.
Definition at line 157 of file SymEigsSolver.h. | https://spectralib.org/doc/classspectra_1_1symeigssolver | CC-MAIN-2021-31 | refinedweb | 272 | 54.93 |
Exchange 2007 Ships with a tool called test-umconnectivity that can be used to verify the health of your Exchange Unified Messaging installation.
It has a couple of modes of operation:
In this mode, the task will run on a machine that has the Exchange Unified Messaging role installed. It will run diagnostics against the local UM server.
The way to run this, is to invoke test-umconnectivity without any parameters.
In this mode, the task verifies that the UMService is listening and responding to incoming INVITES.
[PS] D:\users\Administrator>test-umconnectivity
UmserverAcceptingCallAnsweringMessages : TrueCallAnswerQueuedMessages : 0CurrCalls : 0UmIPAddress : 10.197.228.62Latency : 2121OutBoundSIPCallSuccess : TrueEntireOperationSuccess : TrueReasonForFailure :Identity : 62caff65-7a68-46ab-b2a3-ef52a31e431eIsValid : True
This is an end-to-end test. It verifies that the connectivity from UMServer to Gateway to PSTN is working fine. In this mode, the task does the following:
1) Makes an outbound call to a given phone number using a gateway.
2) The gateway will then send the call to the PBX.
3) The call will then come back to the gateway from the PBX.
4) The Gateway sends the call to a UM server that is linked to the gateway.
5) UM server will respond to the incoming INVITE with some DTMF tones, that are then verified by the task.
This test can be run from any machine that has the Exchange 2007 admin tools installed. It can also be run from any machine that has the Microsoft Operations Manager (MOM) installed, along with the Exchange Management Pack.
For example, I have a UM server setup with an IPGateway. I also have an autoattendant configured with an extension 74808. I want to make sure that my autoattendant is answering calls.
[PS] D:\users\Administrator>get-umipgateway
Name Address HuntGroups OutCallsAllowed Status---- ------- ---------- --------------- ------UNSECURE_GATEWAY 10.198.250... {74809:UNS... True EnabledSECURE_GATEWAY securegw.e... {} True Enabledsipphonegw 157.56.146.19 {:UNSECURE... True Enabled
[PS] D:\users\Administrator>get-umautoattendant
Name UMDialPlan PilotIdentifier SpeechEnabled Status List---- ---------- --------------- ------------- ------aa1 UNSECURE_DIA... {74808} True Enabled
[PS] D:\users\Administrator>test-umconnectivity -UMIPGateway unsecure_gateway -Phone 74808
CurrCalls : 0UmIPAddress : 10.197.228.62Latency : 43236OutBoundSIPCallSuccess : TrueEntireOperationSuccess : TrueReasonForFailure :Identity : 385bbfdf-26fc-460e-9ccb-a1f14b750c0bIsValid : True
The output of the command shows which UM server answered the call, the call latency, etc.
In this mode, the task will test that the UM server can connect to a mailbox in a site. This is used to make sure that the UM sever has good connectivity to mailbox servers that have the mailboxes for UM enabled user that the UM server is servicing.
In order to run this command, we need a UM enabled mailbox with an extension. Also, this command needs to be run on a UMServer.
[PS] D:\users\Administrator>test-umconnectivity -tuiLogon:1 -UMDialPlan:unsecure_dialplan -phone:74808 -pin:147258
Posted
Saturday, December 20, 2008 1:41 PM
by
Feroze Daud |
While writing a unit test for a particular feature, I was faced with an interesting problem. My unit test has different scenarios. These scenarios test that a certain data item is propagated all the way down from the called function.
For eg, I have a method that I need to test - lets call it CFoo:DomSometing().
We pass in a data item to this method - so as part of the changes I change the method to CFoo::DoSomething(int data)
I need to make sure, in my tests, that the 'data' item is properly consumed by the function.
It turns out that for different functions that I call as part of each of my scenario, the way of checking is different. For eg, for one scenario, I have to call the function 'n' times, whereas for another scenario, I have to call the function for a particular duration.
I want to encapsulate all of this, so that I can write one test function that does the following
bool RunTest ( RunTestDelegate testMethod, int data, ILoopIterator iterator) { foreach (int i in iterator.GetValues()) { // call the test method testMethod (data); } }
Here, the RunTestDelegate will be used to encapsulate each method that I need to test, so that I dont have to write one RunTestXXX method per each method I want to test.
The question is: how do you implement the ILoopIterator? Clearly, the first requirement is that it should be returning an IEnumerable<int> because that is what the foreach loop is iterating over.
Also, as discussed above, we need it so that we can iterate over both a range of values, as well as for a time duration.
In order to solve this, I implemented the interface as follows:
interface ILoopIterator { IEnumerable<int> GetValues(); }; } } }}
This code used the .NET/2.0 C# features - i.e generics & yield statement for implementing enumerators.
The caller will use a different factory method, depending on how he wants the iteration to be performed.
For duration based iteration, use LoopIterator .CreateTimed(TimeSpan duration)
For normal iteration (like a for loop) use LoopIterator .CreateCounted(int count)
The utility of this pattern, is that the client (which is using ILoopIterator ) does not need to change!
Posted
Monday, November 03, 2008 5:26 PM
by
Feroze Daud |
2 Comments
This post is going to give an explanation of what the various greetings mean, for the autoattendant.
The posting will be divided into two sections. First, I will describe the common structure. Next, I will describe how this manifests itself at runtime for the DTMF AutoAttendant, and the ASR AutoAttendant respectively.
The greetings are configured for the AutoAttendant using the set-umautoattendant command in Powershell, or by using the Exchange Management Console MMC snapin that ships with Exchange Server 2007. When using set-umautoattendant, the following parameters are available to customize the greetings
If you want to set the Autoattendant greetings using the Exchange Management Console MMC snapin, then you should navigate to the Greetings tab of the autoattendant properties page.
The Greetings for the Main Menu of the autoattendant are played in the following sequence.
First, the autoattendant plays the WelcomeGreeting defined on the AutoAttendant. If no greeting is defined, then the default greeting is played. The default welcome greeting is "Welcome to Microsoft Exchange Automated Attendant".
If the call was received during Holiday Hours (as defined in the holiday schedule), then the greeting associated with that holiday is played. After this, the Informational Announcement is played (if defined).
If a custom menu is defined, then the prompt defined in the AutoAttendant's BusinessHoursMainMenuCustomPromptFilename is played. The custom menu can be defined by setting the BusinessHoursCustomMenuKeyMapping. To enable the custom menu, set the BusinessHoursCustomMenuKeyMappingEnabled property to true.
If a custom menu prompt filename is not defined, then the server will do a best effort to render a TTS (Text to Speech) greeting using the CustomMenu options that were defined.
When a CustomMenu prompt filename is not defined, then the system will TTS the custom menu prompt. In order to TTS the prompt, it will sort the Custom menu in increasing order by the Key that has been defined. Then it will use greeting templates defined for the language of the autoattendant to generate Greeting segments, one for each menu item. The greeting segments are then concatenated to give the final greeting.
For a normal (non-timeout) menu option, the following greeting template is used to generate the greeting segment.
For <description> Press <key>
For <description> Press <key>
And if you have a timeout option defined in the custom menu, then the following template is used.
Or, stay on the line for <description>
Or, stay on the line for <description>
The following table shows the greeting segment that are generated from the custom menu definition.
Once we have the greeting segment, the final greeting is generated by concatenating each individual greeting segment:
For Sales Press One. For Support, Press Two. Or, stay on the line for directions.
For Sales Press One. For Support, Press Two. Or, stay on the line for directions.
The following section describes how the autoattendant sounds when different combinaions of greetings are configured, along with some of the other options that effect greeting playback.
This is the case where an autoattendant was created, and no settings were modified on the autoattendant. The autoattendant will sound as follows:
Welcome to Microsoft Exchange Automated Attendant.
Welcome to Microsoft Exchange Automated Attendant.
You can change the welcomg greeting of the autoattendant by specifying a Business/AfterHours WelcomeGreetingFilename, and setting the corresponding Business/AfterHours WelcomeGreetingEnabled flag to TRUE. Once you do this, the system will sound as follows:
Welcome to Contoso Corporation.
Welcome to Contoso Corporation.
You can configure an informational greeting to let the callers know about extraordinary situations like unforeseen closures etc.. This greeting can be configured by setting the InfoAnnouncementFilename & InfoAnnouncementEnabled properties of the autoattendant. If you set this greeting, then the system will sound like this:
Welcome to contoso corporation. We are closed due to year end Inventory processing.
Welcome to contoso corporation. We are closed due to year end Inventory processing.
If you set the InfoAnnouncementEnabled property value to Uninteruptible, then this greeting cannot be interrupted by the caller. This means that the entire main menu greetings will become uninterruptible. This includes the welcome greeting, informational greeting, and the holiday greeting as well.
You can also configure a holidy schedule for the autoattendant. When a call comes in during a holiday, the autoattendant will play a greeting specified for that holiday. Normally, it doesnt make sense to have both an Informational greeting and holiday greeting active at the same time, so we will assume for this scenario, that the informational greeting is not configured.
You can specify a holday schedule and greeting for the autoattendant by setting the autoattendant's HolidaySchedule property using Powershell. Or, if you are using the MMC, you can navigate to the Times tab, and set the Holiday Schedule there.
If you specify a holiday schedule for Christmas, for example, and also specify a greeting for that holiday, then this is how the main menu will sound when a user calls in.
Welcome to Contoso Corporation. The office will be closed on the 24th and 25th of December for Christmas. Normal hours will resume from the 26th of december.
Welcome to Contoso Corporation. The office will be closed on the 24th and 25th of December for Christmas. Normal hours will resume from the 26th of december.
If a custom menu is defined, then the next greeting that will be played is the custom menu greeting. As explained earlier, the autoattendant will use the greeting defined in the Business/AfterHoursMainMenuCustomPromptFilename. If no greeting is defined, then a TTS greeting will be played to the caller.
If you assume that the custom menu has three options: Sales, Support, Directions as described in the section above, then this is what the caller will hear when no custom menu greeting is defined:
Welcome to Contoso Corporation. For Sales Press One. For Support, Press Two. Or, stay on the line for directions.
Welcome to Contoso Corporation. For Sales Press One. For Support, Press Two. Or, stay on the line for directions.
Additionally, if Transfer to operator and directory search are enabled for the autoattendant, the autoattendant will give the caller these options as well:
Welcome to Contoso Corporation. For Sales Press One. For Support, Press Two. Or, stay on the line for directions. To contact someone, press the Pound key. To speak to an operator, press Zero.
Welcome to Contoso Corporation. For Sales Press One. For Support, Press Two. Or, stay on the line for directions. To contact someone, press the Pound key. To speak to an operator, press Zero.
If the call came in during a holiday, then the holiday greeting will be played after the welcome greeting. In that case, this is what the callers will hear:.
However, if you define a greeting for the custom menu, then this is what the caller will hear:
Welcome to Contoso Corporation. The office will be closed on the 24th and 25th of December for christmas. Normal hours will resume from the 26th. of December.
To talk to our sales department, press One. For support issues, press Two. Or, you can stay on the line for directions.
To talk to our sales department, press One. For support issues, press Two. Or, you can stay on the line for directions.
If you compare this greeting flow with the flowchard given in the begining, you will noticed that the custom menu greeting did not give the caller an option for transferring to the operator, or doing directory search by pressing the Pound key. If you want to give callers this option, you must record these into your custom menu greeting.
If you dont want to give callers this option, you can disable them on the autoattendant.
Posted
Monday, October 22, 2007 10:17 AM
by
Feroze Daud |
1 Comments
If you are the administrator of an Exchange Unified Messaging server, you might want to know why the UM worker process is recycling and how often. The following one line PowerShell script will print out all the reasons why the process recycled:
get-eventlog application | where { ($_.EventId -ge 1049 -and $_.EventId -le 1055) -or $_.EventId -eq 1092 } | ft -wrap
get-eventlog application | where { ($_.EventId -ge 1049 -and $_.EventId -le 1055) -or $_.EventId -eq 1092 } | ft -wrap
If you run this command, you will get an output like so:
Posted
Thursday, March 15, 2007 10:24 PM
by
Feroze Daud |
Many>
mmc.exe /a eventvwr.msc /AUXSOURCE=<machine name or ip>
Posted
Friday, September 22, 2006 7:27 PM
by
Feroze Daud |
I have been stumped from time to time on how to attach VS debuggers to a process on process startup. I knew how to do it with Windbg, by setting ImageFileExecutionOptions for the target process. However I did not know how to do it for VS.
Well, I need to fret no more. A colleague forwarded me th is blog entry by Greg, in which he has some good info on how to use ImageFileExecutionOptions to attach to a process on startup.
Posted
Tuesday, April 04, 2006 12:05 PM
by
Feroze Daud |
In this part, we will add some networking code to the code we have thus far. When we get done, we should have a working Ping utility.
Take the program that we wrote in the Ping: Part III and add the following code.
using System;
using System.Text;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
namespace ping
{
public class ICMP_PACKET
{
public ICMP_PACKET(Byte kind, Byte code, UInt16 id, UInt16 seq, byte[] data)
{
...
}
public ICMP_PACKET(byte[] data, int offset, int count)
this.i_type = data[offset++];
this.i_code = data[offset++];
this.i_cksum = ByteToUint(data, offset);
offset += 2;
this.i_id = ByteToUint(data, offset);
this.i_seq = ByteToUint(data, offset);
this.data = new byte[count - headerLength];
Array.Copy(data, offset, this.data, 0, this.data.Length);
public static UInt16 ByteToUint(byte [] networkBytes, int offset)
return BitConverter.ToUInt16(new byte[] { networkBytes[offset+1], networkBytes[offset] }, 0);
}
class Program
static void Main(string[] args)
if (args.Length != 1)
{
Usage();
}
if (0 == String.Compare(args[0], "/?", true, CultureInfo.InvariantCulture)
|| 0 == String.Compare(args[0], "-h", true, CultureInfo.InvariantCulture)
|| 0 == String.Compare(args[0], "-?", true, CultureInfo.InvariantCulture))
string target = args[0];
IPAddress [] heTarget = Dns.GetHostAddresses(target);
IPAddress ipTarget = null;
foreach (IPAddress ip in heTarget)
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
ipTarget = ip;
break;
}
IPAddress[] heSource = Dns.GetHostAddresses(Dns.GetHostName());
IPAddress ipSource = null;
foreach (IPAddress ip in heSource)
ipSource = ip;
IPEndPoint epLocal = new IPEndPoint(ipSource, 0);
Socket pingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
pingSocket.Bind(epLocal);
byte [] data = Encoding.ASCII.GetBytes("1234567890abcdef");
Console.WriteLine("Ping {0}({1}) with {2} bytes of data...",target, ipTarget.ToString(), data.Length);
Console.WriteLine();
for (int i = 0; i < 3; i++)
ICMP_PACKET packet = ICMP_PACKET.CreateRequestPacket(111, 222, data);
IPEndPoint epRemote = new IPEndPoint(ipTarget, 0);
pingSocket.SendTo(packet.Serialize(), epRemote);
byte[] receiveData = new byte[1024];
EndPoint epResponse = (EndPoint)new IPEndPoint(0, 0);
int read = pingSocket.ReceiveFrom(receiveData, ref epResponse);
ICMP_PACKET recvPacket = new ICMP_PACKET(receiveData, 20, read);
Console.WriteLine("Reply from:{0} bytes = {1}", ((IPEndPoint)epResponse).Address.ToString(), recvPacket.PayloadLength);
...
A couple of important points that I wanted to bring to your attention:
1) I have uncommented the code which checks the validity of command-line parameters in Program::Main.
2) We have added a new constructor ICMP_PACKET(byte [], int, int). This is to parse the response returned by the server.
3) The ByteToUInt(byte [], int) method is used to convert from Network Order to Host Order. This is needed because the bytes on the wire are in Network Order, which is BigEndian
4) In Main(), when we resolve the IPAddress of the source and destination, we need to make sure that we work with the correct IP address. Since this program is limited to IPv4, we need to make sure that we do not accidently work with IPv6 addresses. The IPv6 address may be returned when the host that you are trying to resolve is IPv6 enabled.
5) When we read the response from the socket, we get back more bytes that the size of the ICMP packet sent by the server. This is because we opened the Socket with SocketType.Raw. In this mode, we will also get back the IPv4 header that is encapsulating the ICMP packet. So, when we process the response packet, we need to make sure that we skip past the IP header. That is why we skip the first 20 bytes of the packet when we try to create an ICMP_PACKET with the returned data.
If you compile and run this program, you will be able to ping a host without any problems.
As utilities go, this is a very barebones utility. It does not handle errors from the network very well. For the interested, here are some things that you can do to this to make it more robust:
Be ready to handle exceptions from Socket.SendTo() and Socket.ReceiveFrom().
The utility does not handle timeouts. It would be a simple matter to add code and set a timeout on the Receive() call. That way, if the response doesnt come back within a certain time interval, you can print an error ( or an asterisk like the Ping utility that comes with the OS).
Give a command line option to change the #bytes sent in the payload.
Well, that is it then. Now we have a working Ping utility. Hopefully you have learned how to convert a protocol specification into a working program.
Posted
Wednesday, October 26, 2005 2:53 PM
by
Feroze Daud |
In Part II of this article, we saw how we are going to use the ICMP protocol to implement a simple Ping client. We also saw a skeleton of this program which showed how to translate the ICMP packet specification into a C# structure.
In this part, we will write a routine to calculate the checksum of the packet, and a routine to serialize the packet into a byte array. Recall from PartII that the request and reply packets have a particular encoding on the wire. We will have to write a routine that will encode the packet into a byte array, so that the array can be sent on the wire.
Take the skeleton that we created in Part II and add the following (lines in blue):
...
this.i_type = kind;
this.i_code = code;
this.i_id = ToNetworkOrder(id);
this.i_seq = ToNetworkOrder(seq);
this.data = data;
this.i_cksum = Checksum();
public static ICMP_PACKET CreateRequestPacket(UInt16 id, UInt16 seq, byte[] data)
return new ICMP_PACKET(8, 0, id, seq, data);
public static byte[] GetBytesInNetworkOrder(UInt16 number)
byte[] bytes = BitConverter.GetBytes(number);
if (BitConverter.IsLittleEndian)
return new byte[] { bytes[1], bytes[0] };
else
return bytes;
public static UInt16 ToNetworkOrder(UInt16 number)
byte[] networkBytes = GetBytesInNetworkOrder(number);
return BitConverter.ToUInt16(networkBytes, 0);
public UInt16 Checksum()
int cksum_buffer_length = (int)(Length / 2);
byte [] packetBytes = Serialize(this);
//
// first, convert the serialized bytes into a UInt16 array
// we will use the UInt16 array to do the checksum
UInt16[] checksumBuffer = new UInt16[cksum_buffer_length];
int index = 0;
int i = 0;
while (index < Length)
checksumBuffer[i] = BitConverter.ToUInt16(packetBytes,index);
index += 2;
++i;
int checksum = 0;
for (i = 0; i < checksumBuffer.Length; i++)
checksum += Convert.ToInt32(checksumBuffer[i]);
checksum = (checksum >> 16) + (checksum & 0xffff);
checksum += (checksum >> 16);
return (UInt16)(~checksum);
public byte[] Serialize()
return Serialize(this);
public static byte[] Serialize(ICMP_PACKET packet)
// first, find out how many bytes to allocate for the serialized packet
int packet_size = packet.Length;
bool isLittleEndian = BitConverter.IsLittleEndian;
UInt16 cksum = packet.i_cksum;
UInt16 id = packet.i_id;
UInt16 seq = packet.i_seq;
//allocate the byte array
byte[] packetArray = new byte[packet_size];
// now serialize the packet into the array.
packetArray[index++] = packet.i_type;
packetArray[index++] = packet.i_code;
// the checksum is 16 bits.
byte[] temp = BitConverter.GetBytes(cksum);
// copy it into the packetArray at the required offset
Array.Copy(temp, 0, packetArray, index, temp.Length);
index += 2;
// similarly, copy the rest.
temp = BitConverter.GetBytes(id);
// copy seq#
temp = BitConverter.GetBytes(seq);
// copy payload
if (packet.PayloadLength > 0)
Array.Copy(packet.data, 0, packetArray, index, packet.PayloadLength);
return packetArray;
};
class Program
//if (args.Length != 1)
//{
// Usage();
//}
//if (0 == String.Compare(args[0], "/?", true, CultureInfo.InvariantCulture)
//|| 0 == String.Compare(args[0], "-h", true, CultureInfo.InvariantCulture)
//|| 0 == String.Compare(args[0], "-?", true, CultureInfo.InvariantCulture))
byte [] data = new byte[32];
int j = 0;
for (int i = 0; i < 32; i++)
data[i] = (byte)((int)'a' + j);
j = (j + 1) % 23;
ICMP_PACKET packet = ICMP_PACKET.CreateRequestPacket(0x200, 0x9603, data);
byte[] serialized = packet.Serialize();
for (int i = 0; i < serialized.Length; i++)
Console.Write("{0:X} ", serialized[i]);
}
1) I have commented out the code which checks the validity of command-line parameters. While we are developing this application, we will sometimes be running this program with no command line arguments, so I didn’t want that code there. We will put it back in later.
2) As you might recall, the Platform/CPU stores data in a certain order. This is called Endianness. Intel (X86) platform, on which I am writing this program is Little-Endian. However it turns out that the byte-order on the network is always Big-Endian. Hence we need to convert multi-byte numbers from LittleEndian to Big-Endian before we send them on the network. Therefore, I have written the functions GetBytesInNetworkOrder() and ToNetworkOrder() to do the conversion from Little-Endian to Big-Endian.
3) The functions Serialize() and Checksum() are used to serialize the packet into a byte array, and calculate the checksum respectively. Note that as per the RFC, while calculating the checksum, we should assume that the i_cksum field of the packet structure has a value of zero. Once the checksum is calculated, we write the value into the structure, and then serialize the structure to get the final bytes on the wire.
4) In Part II of this series, I showed you the network trace of the Ping.exe routine that comes with the OS. In this part, I created a request packet with the same data, to make sure that our serialization routine and checksum routines are right. You can compile the program, and run it to verify.
If you compare this output with the Ethereal trace of the actual Ping command that I ran in Part II, you will see that they match. This tells us that the Checksum and serialization routines that we wrote are correct.
If you compare this output with the Ethereal trace of the actual Ping command that I ran in Part II, you will see that they match. This tells us that the Checksum and serialization routines that we wrote are correct.
Posted
Monday, October 24, 2005 11:48 AM
by
Feroze Daud |
If you see the ping utility that comes with your OS, you will notice that it has many options. However, the one we are going to develop will just take one argument:
C:\ping>ping <hostname> | <ipaddress>
Example: ping
Example: ping 127.0.0.1
C:\ping>ping <hostname> | <ipaddress>
Example: ping
Example: ping 127.0.0.1
Let us start out by looking at requirements of the Ping client. Basically, the task of the tool is to find out if a specified server is alive, and on the network. The way it achieves this is by sending an “echo” packet to the server. The server responds with an “echo” response. If the server responds within a certain time interval, then we can assume that there is network connectivity from the client to the server. If it doesn’t respond, then it could indicate a variety of things that could be wrong, for eg:
We will not concern ourselves with “why” a server is not responding to the Ping request, as it could be another topic in itself.
Where was I? Oh yeah, the Ping client. It so happens that we have a protocol (ICMP) that has the echo request and reply operations that we need to implement the Ping client. Read the ICMP RFC to get information about all the features offered by the ICMP protocol. As we know, the ICMP protocol is at the same layer as the IP protocol in the OSI layering scheme.
For the ping utility, we will be using the ICMP Echo Request and response messages. The client will send the ICMP echo request message, and the server will reply with an Echo response message. If you look at the Rfc, it describes how an RFC message looks like:
Offset
Field Name
Size (octets)
Description
0
Type
1
Specified type of the operation. It should be set to 8 for request message and 0 for reply messages
8
Code
This field is Zero.
16
Checksum
2
One’s complement checksum of the ICMP message
32
Identifier
Used to correlate request and reply
48
Sequence Number
64
Data
Variable
Optional data to be sent with the request. This must be sent back by the server.
Looking at the table above, we can come up with a C# class that corresponds to what the packet will look like:
public class ICMP_PACKET
public Byte i_type; // type of message
public Byte i_code; // sub code
public UInt16 i_cksum; // ones complement checksum of header
public UInt16 i_id; // identifier
public UInt16 i_seq; // sequence number
public Byte[] data;
I used Ethereal to sniff the network while doing a Ping, to see what a Ping request/response looks like on the wire. The request packet looks like this:
0020 59 99 08 00 b5 58 02 00 96 03 61 62 63 64 65 66 Y....X.. ..abcdef
0030 67 68 69 6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 ghijklmn opqrstuv
0040 77 61 62 63 64 65 66 67 68 69 wabcdefghi
Let us dissect the packet:
i_type = 0x08 ( Echo Request)
i_code = 0x00
i_cksum = 0xb558
i_id = 0x0200
i_seq = 0x9603
data = 32 bytes ( abcedf…. )
The ICMP echo reply looks as follows:
0020 59 9a 00 00 bd 58 02 00 96 03 61 62 63 64 65 66 Y....X.. ..abcdef
0030 67 68 69 6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 ghijklmn opqrstuv
i_type = 0x00 ( Echo Reply)
i_cksum = 0xbd58
Given what we have learned so far, we can now come up with a skeleton for the program that we will develop:
Byte i_type; // type of message
Byte i_code; // sub code
UInt16 i_cksum; // ones complement checksum of header
UInt16 i_id; // identifier
UInt16 i_seq; // sequence number
Byte[] data;
private const int headerLength = 8;
// Total size of the packet (header + payload)
public int Length
get { return HeaderLength + PayloadLength; }
// Size of the packet header (excluding data)
public int HeaderLength
get { return headerLength; }
// Size of the payload
public int PayloadLength
get { return (data == null) ? 0 : data.Length; }
public byte PacketType
get { return i_type; }
public byte Code
get { return i_code; }
public UInt16 Identifier
get { return i_id; }
public UInt16 SequenceNumber
get { return i_seq; }
this.i_id = id;
this.i_seq = seq;
this.i_cksum = 0;
static void Usage()
Console.WriteLine("ping <hostname> | <ipaddress>");
Console.WriteLine("\tExample: ping");
Console.WriteLine("\tExample: ping 127.0.0.1");
Environment.Exit(0);
Posted
Sunday, October 23, 2005 8:24 AM
by
Feroze Daud |
3 Comments.
Posted
Thursday, October 20, 2005 9:18 AM
by
Feroze Daud |
2 Comments
In a previous blog post, I wrote about how printer manufacturers are embedding tracking information in their printers.
Well, today, via Slashdot, I learned that folks at EFF have figured out the encoding in atleast one printer (those made by Xerox).
The following link has more details...
Posted
Tuesday, October 18, 2005 1:56 PM
by
Feroze Daud |
Durgaprasad, the test lead for System.Net has a very informative entry on using Tracing facilities in whidbey.
Posted
Thursday, September 22, 2005 4:54 PM
by
Feroze Daud |
In whidbey, System.Net has a cool retail tracing implementation. It writes most calls made to public API's to a TraceListener. You can setup your own tracelisteners, or use the config file to setup a default listener.
This facility is very useful in debugging problems with applications.
Here is the example config file which enables Verbose tracing.
<>
NOTE: If you are doing logging inside of the ASP.NET process, make sure to give the ASP.NET process identity WRITE permissions to the directory where you want the log to be written.
Posted
Thursday, May 12, 2005 1:09 PM
by
Feroze Daud |
A:
If you look at the request sent on the wire, you will notice that this program sends the following request to the server "myserver"
GET HTTP/1.1Host:
Whereas the actual request you want sent is:
GET /test.aspx HTTP/1.1Host:.
Posted
Thursday, March 31, 2005 2:46 PM
by
Feroze Daud |
1 Comments
When. For example, imagine that you have a 3-tier architecture, where the client is talking to an asp.net application, which in turn is hitting a backend webserver. The asp.net webapplication (henceforth called the MiddleTier) is using HttpWebRequest to talk to the back-end, and the back-end is secured by Windows Integrated Authentication.
If the middle-tier web application ends up getting a lot of requests, it will inturn issue a lot of requests to the back-end. The default behavior of webrequest is to create a new connection for each request, and over time, the middle-tier might end up running out of wildcard TCP ports, causing the HttpWebRequest to fail with a "Unable to connect to the remote server" exception.
To mitigate this, you want to use a property on the webrequest called UnsafeAuthenticatedConnectionSharing . Setting this property will cause HttpWebRequest to reuse authenticated connections (making sure that it honors ServicePoint.ConnectionLimit).
Security Note: You dont want to use this property lightly. It has security consequences.
Posted
Monday, November 22, 2004 7:40 PM
by
Feroze Daud | | http://blogs.msdn.com/feroze_daud/ | crawl-002 | refinedweb | 5,123 | 56.96 |
Asked by:
ArgumntNullException was unhandled - Please Help
Question
Hi, I am doing a coding course and have run into a problem in one of the assignments. I have 3 textures (bear0, bear1, bear2) which I intend to call upon randomly, based on a random generation of 0-2. The value generated should tell the code to assign one of the textures with my variable, currentSprite. however, when I attempt to run my program, currentSprite is showing as having null value, and it breaks the program. If I replace currentSprite with bear0 in the draw function, the program works.
I have highlighted the relevant code in bold, however I put all my code in as it could very well be anything at this point (I have spent hours trying to fix this).
My code (note that the program is not finished):
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;namespace ProgrammingAssignment2
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
const int WindowWidth = 800;
const int WindowHeight = 600;GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;// STUDENTS: declare variables for three spritesTexture2D bear0;
Texture2D bear1;
Texture2D bear2;// STUDENTS: declare variables for x and y speedsint bear0SpeedX = 0;
int bear0SpeedY = 0;int bear1SpeedX = 0;
int bear1SpeedY = 0;int bear2SpeedX = 0;
int bear2SpeedY = 0;
// used to handle generating random values
Random rand = new Random();
const int ChangeDelayTime = 1000;
int elapsedTime = 0;// used to keep track of current sprite and location
Texture2D currentSprite;Rectangle drawRectangle = new Rectangle();public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";graphics.PreferredBackBufferWidth = WindowWidth;
graphics.PreferredBackBufferHeight = WindowHeight;
}/// base.Initialize();
}/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);// STUDENTS: load the sprite images here
bear0 = Content.Load<Texture2D>("teddybear0");
bear1 = Content.Load<Texture2D>("teddybear1");
bear2 = Content.Load<Texture2D>("teddybear2");
// STUDENTS: set the currentSprite variable to one of your sprite variables}/// ();
//bear0 = currentSprite;elapsedTime += gameTime.ElapsedGameTime.Milliseconds;
if (elapsedTime > ChangeDelayTime)
{
elapsedTime = 0;// STUDENTS: uncomment the code below and make it generate a random number
// between 0 and 2 inclusive using the rand field I provided
int spriteNumber = rand.Next(0,3);//sets current sprite
//STUDENTS: uncomment the lines below and change sprite0, sprite1, and sprite2
// to the three different names of your sprite variables
if (spriteNumber == 0)
{
currentSprite = bear0;
// Console.WriteLine("bear0");
}
else if (spriteNumber == 1)
{
currentSprite = bear1;
// Console.WriteLine("bear1");
}
else if (spriteNumber == 2)
{
currentSprite = bear2;
// Console.WriteLine("bear2");
}// STUDENTS: set the drawRectangle.Width and drawRectangle.Height to match the width and height of currentSpritedrawRectangle.Width = (currentSprite.Width);
drawRectangle.Height = (currentSprite.Height);// STUDENTS: center the draw rectangle in the window. Note that the X and Y properties of the rectangle
// are for the upper left corner of the rectangle, not the center of the rectangle
//TO DO: CENTER drawRectangle IN WINDOW
// STUDENTS: write code below to generate random numbers between -4 and 4 inclusive for the x and y speed
// using the rand field I provided
// CAUTION: Don't redeclare the x speed and y speed variables here!}// STUDENTS: move the drawRectangle by the x speed and the y speed
base.Update(gameTime);
}/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);// STUDENTS: draw current sprite here
spriteBatch.Begin();//code works if 'currentSprite' is replaced with 'bear0'
spriteBatch.Draw (currentSprite, drawRectangle, Color.White);spriteBatch.End();
base.Draw(gameTime);
}
}
}
All replies
My guess would be that the issue is this line:
int spriteNumber = rand.Next(0,3);
If you look at the documentation for Random.Next you will see it accepts a min value and a max value which you are setting to 0 and 3. So there is a 1 in 4 chance that spriteNumber will be set to 3, even though you only have textures 0, 1 and 2!
PS: You may want to consider putting your textures into a Texture2D array rather than 3 separate variables. Then you can just pick out the value from the array and remove the need to do a big "if (spriteNumber==0) etc etc" test :)
currentSprite = bear[spriteNumber];
I will need to look into an array.
Regarding the rand.Next, according to many forums I have looked at, the min value of 0 will be inclusive, and the max value (3) will be exclusive, meaning 0-2 will be generated.
Thanks for the reply
You are correct. I am an idiot.
2nd attempt:
Have you checked that all your Load<Texture2D> methods have successfully worked and that you haven't ended up with a bearN variable set to null?
Is it possible that the Draw() method is getting called before the first call to Update()? If this is the case you just need to initialise currentSprite to one your bear variables in LoadContent.
You probably forget to follow the comment “// STUDENTS: set the currentSprite variable to one of your sprite variables”. Maybe assign any initial bear to currentSprite here. Then when Update is executed, it will select another bear.
- Edited by Viorel_MVP Monday, February 12, 2018 6:22 PM
- Proposed as answer by Fei HuModerator Tuesday, February 27, 2018 8:04 AM | https://social.msdn.microsoft.com/Forums/en-US/9ef7dbb8-79d3-46b6-a4c0-d87b2659807e/argumntnullexception-was-unhandled-please-help?forum=csharpgeneral | CC-MAIN-2020-40 | refinedweb | 894 | 55.64 |
Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Also made a correction to handle a complex type that extends another type but does not add any elements or attributes.
Also rolled version numbers to 2.2.4 in advance of the next release. Holding off for a week or two to see if anymore defects come in.
Added support where max occurs is defined at the sequence level.
Implements:
6ee947f218 -- Byte Order Marker from some servers not handled
fc2ccda89c -- Add support for Wibble 0.2
4a72ac4b11 Code_Defect Redirects not being followed
3de47c423b Code_Defect Invalid command name Tcl error when parsing WSDL xml
83bd219e9a Code_Defect extra level in typeInfo dict
35e25c0a53 Code_Defect typos
Also fixes for:
[a2b1add55a] German umlauts not working (at least with SugarCRM)
[ced827a9da] Client: Convert XML to UTF-8
Also add recording of which namespaces were imported.
Utilities fix to build RPC Encoded messages. | https://core.tcl-lang.org/tclws/timeline?c=bae7b452ec52dcb76473 | CC-MAIN-2021-49 | refinedweb | 148 | 56.86 |
Introduction: Getting Started Learning C# the Hard [sic] Way
So you want to learn to program in C# huh? This is the first in a series of guides that will show you how to do exactly that, but do so requiring only the simplest of tools and the most basic of setups, at no cost to you.
I believe in learning by doing and leveraging the experience of others.
For these reasons, I am going to borrow a pedagogical method and a value system from the learncodethehardway.org books.
You should be able to get by on nothing more than the tools a programming language ships with. Reducing your dependance on particular tools actually increases your options, which is also a good argument for learning more than one programming language, eventually.
I am not saying your life will ever depend on knowing how to write a program with nothing more than csc.exe and notepad in a stuck elevator in a building on fire with no internet connection, but if it did, wouldn't you like to be not completely lost in that article
Let's get started. You are going to need a few things and going to have to do some small chores before we can start coding in C#.
The first thing we'll need is CSharpRepl. It is an interactive programming environment for C# that ships with Mono. You can download it here. As of the time of this writing, you are going to want to download Mono 5.0.1.
Alternatively, if you are on a Mac with homebrew installed, you can simply:
brew install mono
Submitted by Brazos Valley Makerspace for the Instructables Sponsorship Program
Step 1: REPL-ing
To start the REPL (read-eval-print loop), open a command prompt.
On Windows: press the Windows Key and R together to bring up the run box, then type in "cmd". Then navigate to the folder you installed Mono to by issuing a command like cd "C:\Program Files (x86)\Mono-3.0.10\bin". NOTE: the path to where your Mono executable files live may be different than mine, especially if you downloaded a newer version of Mono.
Alternatively, there is a mono command line. You may find it by typing "mono" into the search box of your start menu (Windows Vista or newer).
To run the REPL, type "csharp" in the new window you just launched with the black background and blinking white cursor (cmd.exe a.k.a. Command Prompt) and press the enter key.
On OS X: press Command key and the space bar together to bring up Spotlight. Then type in "Terminal" and press the Enter key.
When you pressed the Windows Key and the R key together (or Command and Space), you used what is called a keyboard shortcut. Throughout this guide, and related guides, keyboard shortcuts will be represented in the form Key + Key (for example you just used Windows + R).
On either platform:
Now, you should see:
csharp>
followed by a blinking cursor.
Type:
1+1;
and press the enter key. You should see ">2" on the screen. Congratulations! You've just written your first bit of C#.
A bit of housekeeping for Windows Users
You aren't going to want to navigate to the Mono bin directory every time you start the REPL. So we are going to add the path to the Mono bin directory to your system Path environment variable. I've added some images to this step to try to illustrate the process. I'm using Windows 7. It may look slightly different on your system.
- Open the Control Panel
- Click "Edit the system environment varialbles" link
- Click the "Environment Variables..." button
- In the list labeled "System variable", find Path
- Click on Path
- Click on the "Edit..." button
- At the very end of the box labeled "Variable value", type a semi-colon if there isn't one already there (at the end)
- Type the path to your Mono installation's bin folder (more than likely C:\Program Files\Mono\bin)
- Click "OK" three times
- Open the Run Box (Windows Key + R)
- Type cmd into the Run Box and press Enter
- Type echo %Path% into the command prompt and press Enter
- You should see the path to the Mono bin folder printed to the screen
- Type csharp into the command prompt and press Enter
- You should now be looking at the Mono C# REPL prompt
Useful commands
Typing this into the REPL will clear the screen:
System.Console.Clear()
Typing this into the REPL will print the online help:
Typing this into the REPL will quit the REPL:
quit;
Step 2: Express[ion] Yourself
The text you just typed "1+1" is called an expression, Expressions are the most basic building blocks of computer programs.
Now type "var i =0;" at the cursor and hit the enter key. What you just typed is called an assignment expression. That means you created a variable (an integer variable in this case) and assigned the value 1 to it.
You might be thinking, "That's nice, but what good is it?" Just a minute, and I'll show you.
Type the following:
Console.WriteLine(i);
and press the enter key. Now you should see a 0 on the following line. The last instruction you gave to the REPL is what's called a method expression.
As you are working along in the REPL, you may feel like clearing the screen. Typing:
Console.Clear();
and pressing Enter will do just that.
From here on out, when I instruct you to type some text into the command prompt, I am also implying that you need to press the Enter key after doing so.
Step 3: Handling the Unexpected
Type the following:
Console.WriteLine("Foo"
then press Enter.
You should see something like this:
csharp>Console.WriteLine("Foo"
>
Here the REPL is giving you a chance to finish the expression. Try typing a ")" and pressing Enter.
The REPL should now look as follows:
csharp>Console.WriteLine("Foo"
>)
If the REPL shouts some technobabble at you, just copy the english looking portions of it into a browser search box and hit enter. The ability to perform internet searches well is actually a very important skill for any programmer (hobbyist or otherwise) to have.
Let's try deliberately causing an error.
Type:
csharp>Console.WriteLine("Bar
and press Enter.
You may have noticed that when we are writing text for the computer to do something with, we enclose it in typewriter (a.k.a. straight or dumb) quotes (e.g. "Foo" above). The compiler generally doesn't like it when there is a line break in text (a string literal in programming parlance).
So, lets type the ending typewriter quote mark, skip a line, type the closing ")" and see what happens:
>" >)
Now you should see something like the following:
csharp> Console.WriteLine("Bar
>" > ) (1,23): error CS1010: Newline in constant (2,1): error CS1010: Newline in constant
A quick internet search for "CS1010: Newline in constant" will turn up this:... Perhaps not the best explanation, but it gets the point across. Websites such as stackoverflow.com may be more useful than the actual documentation.
Try the following instead:
csharp> Console.WriteLine(@"Foo
> Bar > ")
The result should look like:
Foo
Bar
The @ before the typewriter quote is used to create a verbatim string literal. Among other things a verbatim string literal allows for line breaks in strings. You can read more about verbatim string literals and string literals in general at
You have written arithmetic expressions, assignment expressions, and method expressions. You are well on you way to being able to write a computer program.
Step 4: Keeping It Classy
C# and Java are object oriented to a fault. That is, in order to do anything useful with them, you have to have an object. To get an object, you need a class. A class is like a mold for making objects.
Fire up the csharp REPL, and lets define a really simple class:
csharp> public class Person
> { > } >
That's the simplest class definition you will ever see. It is also not very useful.
Continuing on, we'll add fields to classes as a means to store information.
Step 5: Getting Methodical
First, kill your current REPL session. You may achieve this by typing:
Environment.Exit(0)
A convenient way to do the same thing that is baked into the REPL is to type:
quit;
Now you should see the normal command prompt. Start a new session. You may do this by typing "cs" then pressing the tab key (on OS X you may have to type "csha"). "csharp" should now appear on your screen. What just happened is called tab completion, it is a feature of the Command Prompt, Linux Consoles, and some text editors. It can be very useful, especially if you are not a big fan of typing the same thing over and over again. Start the new session by pressing the enter key.
Now type the following:
csharp> using System.Text;
> class Greetings >{ > public void SayHi() > { > var sb = new StringBuilder(); > sb.Append('H'); > sb.Append('e'); > sb.Append('l');
Now rather than typing "sb.Append('l');" a second time. Hit the up arrow if you have a direction pad (a.k.a. dpad) on your keyboard.
The command line should now look like:
> sb.AppendLine('l');
Now type the remaining lines below to complete our class with it's one method:
> sb.Append('l');
> sb.Append('o'); > sb.Append(" world"); > Console.Write(sb.ToString()); > } >}
We can make use of what we just wrote by typing the following:
<p>> var greetings = new Greetings();<br>> greetings.SayHi();</p>
What just happened is that you wrote a class called Greetings containing a method called SayHi. Then you created an instance of that class and called (invoked) its SayHi method. A method is basically just a convenient way to group a set of instructions (statements) together and provide a means of executing those instructions.
If you are familiar with a structured programming language such as C, methods are basically just functions that belong to classes or structs or objects (instances of a class or struct). Methods allow objects to do things (behavior). Now lets move on to fields, which allow objects to know things (state).
Step 6: Taking the Field
Now for something different. Type the following into the REPL
class Person
{ public string HairColor; public Person(string hairColor) { HairColor = hairColor; } }
var robert = new Person("brown");
print(robert.HairColor);
The previous code example creates a class named Person, defines a constructor (constructors are methods that always have the same name as the class they belong to and no return type because it is implied), and defines a field named HairColor. The code also creates a Person object with brown HairColor. The constructor takes one parameter (a.k.a. argument) and uses that parameter to set the value of the HairColor field.
Classes are basically descriptions of objects. Creating an instance of a class is like making a part from a mold. Classes can be thought of as a description of a particular kind of object. In programming, objects are things that contain state and behavior. State is a computer science-esque way of saying condition. In the real world, some conditions are permanent while others are temporary. The same is true of the conditions (state) of objects. For instance. At the time of this writing, if I were to create an object to represent myself, if the type of object I'd created had a field named "HairColor" I would set its value to be brown. In ten years, I'd probably have to set its value to be grey. Fields are one way to represent state in classes. Fields define attributes of classes. Fields can be public (visible from anywhere in the system—they can be accessed or modified from any part of the program) or private. There are other visibility modifiers, but you can learn more about them on your own. The convention in C# is to leave fields private, unless they are constants (their value cannot be changed), and to access or change their value using properties or methods. Try this:
class Person
{ private string hairColor;
public void SetHairColor(string color) { hairColor = color; } }
Oops! You should have seen a message like the following after you pressed enter the last time:
warning CS0414: The private field `Person.hairColor' is assigned but its value is never used Having a field that we can set but can't use isn't very helpful. Try this instead:
class Person
{ private string hairColor; public void SetHairColor(string color) { hairColor = color; }
public string GetHairColor() { return hairColor; } }
var robert = new Person(); robert.SetHairColor("maroon"); robert.GetHairColor();
After that call to robert.GetHairColor(), you should see the text "maroon" parroted back to you by the REPL. That SetHairColor method seems like it would come in pretty useful on game day.
What happens if you try typing the following after the example above:
print(robert.hairColor);
You should see a message like the following:
error CS0122: `Person.hairColor' is inaccessible due to its protection level That simply means that hairColor isn't public anymore. Now that we have some idea about fields and how they are used, let's move on to properties.
Step 7: Other People's Properties
Let's look at some other ways to set the state of our objects. Enter the following code snippet into the REPL:
class Inbox
{ public int MessageCount {get; set;} }
var inbox = new Inbox(); inbox.MessageCount = 1; print(inbox.MessageCount);
After the print(inbox.MessageCount); line you should see a "1". Let's review. You created a class named Inbox and gave it an integer property named MessageCount. Specifically you gave it an auto-property.
Another way to create an equivalent property would have been:
private int messageCount;
public int MessageCount { get { return messageCount; } set { messageCount = value; } }
With auto properties, the compiler creates what is known as the backing field (less commonly known as a backing store) for you.
As you can see by the use of return in the get above, properties are basically just a shorthand for methods in C#. They take the place of getter/setter methods in languages that do not support them like Java. Properties can have a getter and a setter, only a getter, or only a setter. It is common to see properties with a getter an no setter where implementing a setter would break the encapsulation of the class implementing it. For instance, you can give a puppy food, but you can't change it's height. The puppy does that on its own. When you're implementing properties and methods, ask yourself if it makes sense for something else to be able to change the state of your object. Let's try out the following:
class Inbox
{ public int MessageCount { get; private set;} public ArrayList Messages {get;} public void AddMessage(string message){ Messages.Add(message); MessageCount++; }
public Inbox() { Messages = new ArrayList(); } } var inbox = new Inbox(); inbox.AddMessage("Hello There!"); print(inbox.MessageCount); print(inbox.Messages[0]);
Let's examine what just happened. We created a class called Inbox. This Inbox class contains a List called Messages and method called AddMessage to add messages to that list.. We also printed the first item in the Messages list to the screen. The left and right square brackets ("[" and "]") after Messages is called an indexer. An indexer is a special type of property that is conventionally used to retrieve items by using a key. In this case, the key is a numerical index. Note that indices in collections in C# are zero-based. That's just a fancy way of saying that the first item will be at index 0 rather than at index 1.
The default protection level of a getter is public. So, that means code that doesn't belong to the Inbox class can access the messages list.
Let's try the following:
> inbox.Messages.Add("Another Message");
> print(inbox.MessageCount); 1 > print(inbox.Messages[0]); Hello There! > print(inbox.Messages[1]); Another Message
Oops, that's not right. One really nasty side effect of making of your properties publicly accessible (especially if they are collections) is that your object can be placed into a state where it is inconsistent with itself.
Now that we've encountered collections, they probably deserve a more formal introduction.
Step 8: Collecting Speed
Perhaps by the very nature of programming—specifically its use in handling large quantities of data, operations, or things—a good understanding of collections, how they work, and what types are available is essential to good programming practice.
Let's revisit the list:
class MessageBox
{ private List messages = new List();
public int MessageCount { get { return messages.Count; } }
public string this [int i] { get { return messages[i]; } set { messages[i] = value; } }.
NOTE: List is pronounced "List of string". An unbound generic list (or list with no type parameter) is pronounced "List of T" where T is just a placeholder for the type that will be eventually bound to the generic class. Ok lets try to do something with our inbox.
csharp> var msgBox = MessageBox()
csharp> msgBox[0] = "A message" System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Well, that's not very useful. But it is instructive. We have to be very careful with indexers. Lists are initialized to have a size of zero, so we can't swap out an item at index if there's nothing at that index.
Copy the class definition from here and paste it into the REPL.
Copy/pasting into a terminal is a little easier on OS X, but it can still be done in Windows. You simply have to right-click the cmd.exe window and select "Paste" from the context menu.
Add, Find, and Remove methods and index operators wrapping container logic make it possible to easily swap out containers should the need arise. Not to mention that feature envy is just gross.
Lets exercise our new MessageBox class:
csharp> var msgBox = new MessageBox();
csharp> msgBox.AddMessage("Message 1"); csharp> msgBox.AddMessage("Message 2"); csharp> msgBox.AddMessage("Message 3"); csharp> print(msgBox) Message 1 Message 2 Message 3 csharp> msgBox.RemoveMessage("Message 2") csharp> print(msgBox) Message 1 Message 3
Say that we want to make our inbox give us messages in reverse chronological order, then we could use a stack instead. A stack is what is known as a LIFO (last in-first out) container.
Quit the REPL by typing quit; and pressing the Enter key.
As an alternative to pasting large amounts of text into the REPL, it supports a feature called Startup Files. This will let us save things like class definitions into files that end in .cs that are loaded when the REPL starts.
In OS X, the folder to place your .cs files into is ~/.config/csharp.
On Windows, it is slightly tricker, but not difficult. You simply type the following in to the REPL:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
That will print the folder path of your AppData folder to the REPL.
Typing the following into the REPL will actually open the folder you need to create the csharp directory inside in Windows Explorer:
var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); System.Diagnostics.Process.Start("" + path);
Once you've got your "csharp" folder created save this in a file named MessageBox.cs in your csharp folder.
Now let's take our stack-based MessageBox for a spin. Start the REPL again and type the following:
csharp> var msgBox = new MessageBox();
csharp> msgBox.AddMessage("Message 1"); csharp> msgBox.AddMessage("Message 2"); csharp> msgBox.AddMessage("Message 3"); csharp> print(msgBox); Message 3 Message 2 Message 1 csharp> msgBox.RemoveMessage("Message 2"); csharp> print(msgBox); Message 3 Message 1
We can see that with this new MessageBox, messages are displayed in reverse chronological order.
We've seen three types of collections. There are many more to be found in the System.Collections and System.Collections.Generic namespaces.
Message Box Using Generic List
Message Box Using Generic Stack
Step 9: Wrapping Up
To recap, we've covered expressions, classes, methods, fields, properties, and containers. That should be more than enough to started on your programming journey. If you have any questions, don't hesitate to comment below.
Discussions | https://www.instructables.com/id/Getting-Started-Learning-C-the-Hard-sic-Way/ | CC-MAIN-2018-34 | refinedweb | 3,406 | 65.22 |
A thread can be created by implementing the Runnable interface and overriding the run() method. Then a Thread object can be created and the start() method called.
A thread can be stopped using a boolean value in Java. The thread runs while the boolean value stop is false and it stops running when the boolean value stop becomes true.
A program that demonstrates this is given as follows:
class ThreadDemo extends Thread { public boolean stop = false; int i = 1; public void run() { while (!stop) { try { sleep(10000); } catch (InterruptedException e) { } System.out.println(i); i++; } } } public class Demo { public static void main(String[] args) { ThreadDemo t = new ThreadDemo(); t.start(); try { Thread.sleep(10000); } catch (InterruptedException e) { } t.stop = true; System.out.println("The thread is stopped"); } }
1 2 3 4 5 The thread is stopped | https://www.tutorialspoint.com/use-boolean-value-to-stop-a-thread-in-java | CC-MAIN-2021-49 | refinedweb | 136 | 68.47 |
RE: Non-Blocking UDP in VB.NET for beginners?
- From: Tommy Long <TommyLong@xxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Fri, 25 Jul 2008 06:27:01 -0700
Ok, I believe I have worked out for myself how to get around the blocking
issue. Whether it is the correct way to do it, is yet to be determined.
Basically the Functions/Procedures involved in the UDP
transferring/receiving I've passed over to a worker, and started
multithreading. I had no idea I could multithread in VS05 so easily, so I'm
glad I've had this problem and learnt something of use.
My application at the moment, whilst loading up a login screen, attempts to
test the UDP connection. With my lack of knowledge in UDP/TCP I have no idea
if its even possible. But to test the connection I attempt to get the
computer to listen out on port ####, using my newly learnt worker. The main
thread then attempts to send a bytearray across the same port, addressed to
the local computers IP.
I was kind of hoping that the packet would be sent off to the router, and
the router would then bounce it back as the intended recipient is also the
source. With my lack of knowledge I don't even know if thats
allowed/possible.
The error I am getting is when the main thread attempts to send a packet, I
get the message:
"Cannot send packets to an arbitrary host while connected."
Now it is my understanding that UDP works without establishing a connection.
Its just sends something off and doesn't care where it ends up or whether it
arrives anywhere at all, whereas TCP sets up a connection, and verifies
everything? Is that about right?
However, reading through microsoft articles I see that their instances of
UDPClients use the .Connect method, so thats what I have done with both my
'listening instance, and my 'sending instance' of UDPClient. Due to the
order of things the main thread which handles the 'sending instance' is the
second to use the connect method, immediately after which it attempts to
send:
sUDPClient.Send(sendBytes, sendBytes.Length, RecipientIP, RecipientPort)
At the same time my worker thread is sat (blocked) on the line:
receiveBytes = rUDPClient.Receive(RemoteIpEndPoint)
It is the 'sUDPClient.Send.....' that throws the above error. Is anyone
able to tell me where I've gone wrong (other than "trying to program")?
Thanks in advance guys.
--
-------------------------------
Please respond to my posts via the newsgroup as the e-mail provided is not
monitored.
"Tommy Long" wrote:
I apologise in advance for this question has been answered at least in this.
thread:
Unfortunately I'm pretty new at all this and still can't get the jist.
Basically I've implemented a UDPClient.Send and Receive, run the program and
realised what was ment by 'blocking' when i read the MSDN article. My
program hangs, waiting to receive something.
As the title says, I'm looking for a way to achieve this without blocking,
probably as answered in the thread I've linked, but in an example format, or
at least easier than even lamens terms?
I know I'm being a pain, thus the apologies.
Here is an example of the blocking udpclient procedure I'm using at the
moment: (oUDPClient is currently declared globally while I tried to figure
things out...)
--------------------------------------------
Public Function HandleIncoming() As Boolean
Dim SendersIP As String
Dim ReceivedEx As String
Try
Dim receiveBytes As [Byte]() =
oUDPClient.BeginReceive(RemoteIpEndPoint)
Dim returnData As String = Encoding.ASCII.GetString(receiveBytes)
SendersIP = RemoteIpEndPoint.Address.ToString()
ReceivedEx = returnData.ToString()
'Do stuff with ReceivedEx...
HandleIncoming = True
Catch ex As Exception
HandleIncoming = False
Exit Sub
End Try
End Function
--------------------------------------------
To add to the above, I'm using Visual Studio 2005 Standard Edition. I've
created a VB project and this networking stuff which I have no experience in,
is just a small, but unfortunately crucial part of it.
What I need the above procedure to do is trigger when an incoming
transmission is detected. The procedure can then 'select case' and react
depending on what it has received. All of which I'd like to do without the
application hanging/being blocked - so the user can go on using other
features whilst the UDPClient listens in the background.
I don't mind doing this with some sort of timer checking if there has been
something received, if there is no event that can be triggered available.
I'd prefer it if it didn't involve having to download someone's .DLL and
referencing that, but if thats the only way to do so then c'est la vie.
I've already had a look at two such methods, one provided by 'UnoLibs' and
another by the name of 'TinyServer'. Both of which do not appear to have
been written in Visual Studion 2005 and refer to lots of old/obsolete
namespaces which I've failed to update to be compliant/usable/error free, in
my VS05 SE.
Thanks in advance for any help you guys can provide.
--
-------------------------------
Please respond to my posts via the newsgroup as the e-mail provided is not
monitored.
- References:
- Non-Blocking UDP in VB.NET for beginners?
- From: Tommy Long
- Prev by Date: Re: program will not run on another pc
- Next by Date: Help - LINQ to XML Issues
- Previous by thread: Non-Blocking UDP in VB.NET for beginners?
- Next by thread: program will not run on another pc
- Index(es): | http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.vb/2008-07/msg00859.html | crawl-002 | refinedweb | 912 | 64.2 |
Deregistering Service Instances
Before you can delete a service, you must deregister all service instances that were registered using the service.
To deregister a service instance, perform the following procedure.
To deregister a service instance
Sign in to the AWS Management Console and open the AWS Cloud Map console at
.
In the navigation pane, choose Namespaces.
Choose the option for the namespace that contains the service instance that you want to deregister.
On the Namespace:
namespace-namepage, choose the option for the service you used to register the service instance.
On the Service:
service-namepage, choose the option for the service instance that you want to deregister.
Choose Deregister.
Confirm that you want to deregister the service instance. | https://docs.aws.amazon.com/cloud-map/latest/dg/deregistering-instances.html | CC-MAIN-2020-29 | refinedweb | 118 | 56.76 |
The process of defining methods with same name but with different functionalities is termed method overloading. For example, an overloaded draw() method can be used to draw anything, from a circle to an image. Methods with same name, namely, draw, but with different arguments can be used for all cases.
When in a class, we have more then one method with similar name but with different type signatures i.e. with different number of parameters or with different types of parameters, then we say that the method is overloaded. Compiler will recognize which method to execute on the basis of the type and number of parameters used while calling the method. certainly refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.
Inheritance is one the most powerful concepts in an object-oriented language. Through inheritance the code developed for one class can be used in another class. That is, the data members made in a class can be used in another class. Inheritance is done by creating new classes that are extensions of other classes. The new class is known as a subclass. The original class is known as a superclass. The subclass has all the attributes of the superclass, and in addition has attributes that it defines itself. A class can have only one superclass. This is known as single inheritance. A superclass can have multiple subclasses.
A static nested class or a top-level class is a class that is declared inside another class with a static modifier. Like static methods, a static nested class can only refer directly to static members of the enclosing classes, even if those members are private.
Anonymous inner classes are the local inner classes that are declared without a name. All of the code for the anonymous class is coded within the method where we need to create an instance of the anonymous class. Since anonymous inner classes do not have a name so you cannot use the new keyword in the usual way to create an instance of the class. In fact, anonymous inner classes are declared and instantiated at the same time.
A local inner class or simply a local class is an inner class that is declared inside a method or constructor or initialization block of the enclosing class. Like regular inner classes, the local classes are associated with a containing instance and can access any member, including the private members of the enclosing class. In addition, it can also access local variables in the method and parameters passed to the method only if the variables are declared final. Just like local variables, the inner class cannot be accessed outside the code block. It is useful when a computation in a method requires the use of specialized class that is not used elsewhere.
A.
Unlike.
When one interface inherits from another interface, that sub-interface inherits all the methods and constants that its super interface declared. In addition, it can also declare new abstract methods and constants. To extend an interface, you use the extends keyword just as you do in the class definition. Unlike a subclass which can directly extend only one subclass, an interface can directly extend multiple interfaces. This can be done using the following syntax
[public] interface InterfaceName
A class can implement more than one interface. For this, you write the names of all interfaces that the class implement separated by commas following the implements keyword and the class body must provide implementations for all of the methods specified in the interfaces. The syntax for implementing multiple interfaces is .
Sometimes you may want to prevent a subclass from overriding a method in your class. To do this, simply add the keyword final at the start of the method declaration in a superclass. Any attempt to override a final method will result in a compiler error.. For example, The abstract method area () of the Shape superclass will be written as
Sometimes it is useful to know the type of the object at runtime. For example, if you try to make a cast that is invalid, an exception will be thrown. You can overcome this problem if you are able to verify that the object is of the type you expect before you make the cast. This is possible using the instanceof operator. The general from of instanceof operator is objRef instanceof type
You can cast an object to another class type provided a class is a subclass of other i.e. casting takes place within an inheritance hierarchy, so that the source and destination are within the same hierarchy.
As we know that in order to declare a variable that references an object, we use the following
syntax.
ClassName variableName;
Here, variableName is the name of the reference variable and ClassName is the name of its class. Thus, variablename can reference any object of class ClassName. However, it can also reference any object whose class is a subclass of ClassName. For example: If a class A is a superclass of class B and class B is a superclass of class C then in that case, variable of class A can reference any object derived from that class (i.e. object of class B and class c). This is possible because each subclass object is an object of its superclass but not vice versa.
All the classes in Java that you have defined so far are subclasses by default whether or not you have specified the superclass. The class which all classes in Java are descendent of (directly or indirectly) is java .lang. Object class. So each class inherits the instance methods of Object class. It is important to be familiar with the methods provided by the Object class so that you can use them in your class.
Inheritance is suitable only when classes are in a relationship in which subclass is a (kind of) superclass. For example: A Car is a Vehicle so the class Car has all the features of class Vehicle in addition to the features of its own class. However, we cannot always have. is a relationship between objects of different classes. For example: A car is not a kind of engine. To represent such a relationship, we have an alternative to inheritance known as composition. It is applied when classes are in a relationship in which subclass has a (part of) superclass.
In Our Example illustrates Multilevel Inheritance, Here Class B is derived from superclass A which itself acts as a superclass for the subclass C. The class C inherits the members of Class B directly as it is explicitly derived from it, whereas the members of class A are inherited indirectly into class c (via class B). So the class B acts as a direct superclass and A acts as a indirect superclass for class C.
A subclass inherits methods from a superclass. However in certain situations, the subclass need to modify the implementation (code) of a method defined in the superclass without changing the parameter list. This is achieved by overriding or redefining the method in the subclass.
A subclass inherits the accessible data fields and methods from its superclass, but the constructors of the superclass are not inherited in the subclass. They can only be invoked from constructors of the subclass( es) using the keyword super.
A protected field or method in a public class can be accessed directly by all classes within the same package and its subclasses even if the subclasses are in different packages. It is more restrictive than default (or package) access.
Inheritance is a mechanism of creating a new class from an existing class by inheriting the features of existing class and adding additional features of its own. When a class is derived from an existing class, all the members of the superclass are automatically inherited in the subclass. However, it is also possible to restrict access to fields and method of the superclass in the subclass. This is possible by applying the access Specifiers to the member of the superclass. If you do not want a subclass to access a superclass member, give that member private access. The private members of the superclass remain private (accessible within the superclass only) in the superclass and hence are not accessible directly to the members of the subclass. However, the subclass can access them indirectly through the inherited accessible methods of the superclass.
Inher.
An interface is a way of describing what classes should do, without specifying how they should do it. A class can implement more than one interface. In Java, an interface is not a class but a set of requirements for the class that we want to conform to the interface. All the methods of an interface are by default public. So, it is not required to use the keyword public when declaring a method in an interface. Interfaces can also have more than one method. Interfaces can also define constants but do not implement methods. An interface is defined like a class. Its general form is:
The final keyword has the following uses in the inheritance.
If you want the method must not be overridden then defined that method as final.. It is the responsibility of the concrete subclass to implement all abstract method of superclass. To declare any method as abstract use the following form: abstract accessmodifer retumtype methodName( <parameterlist>);
Another important feature of the Java is polymorphism. A famous phrase 'one interface, multiple methods' or 'once instance, multiple forms' is for polymorphism. General classes of actions are defined, and according to the exact nature of situation the specific action is called. A set of related activities are designed in a generic interface, and same interface is used to specify a general class of action. To select the specific action is the responsibility of the compiler's job. Polymorphism allows you to create a sensible, readable, clean, and resilient code.
The class member attributes (fields) and methods are bounded with some accessibility modifier, which defines the access scope of the member. In this section, we'll study how to access the data members (attributes) of the class. | http://ecomputernotes.com/java/inheritance | CC-MAIN-2017-30 | refinedweb | 1,700 | 54.12 |
Because RabbitMQ was a new third-party piece of software to be used as a critical component of our system, I wanted to test its integration throughly. That involved multiple tests against a local cluster of three nodes (all running on my local machine), as well as the same tests running against a remote RabbitMQ cluster. The tests involved tearing down, recreating, and configuring the cluster in different ways, and then stress-testing it. Setting up and configuring a remote RabbitMQ cluster involves multiple steps, each normally taking less than a second. But, on occasion, one can take up to 30 seconds. Here is a typical list of the necessary steps for configuring a remote RabbitMQ cluster:
- Shut down every node in the cluster
- Reset the persistent metadata of every node
- Launch every node in isolated mode
- Cluster the nodes together
- Start the application on each node
- Configure virtual hosts, exchanges, queues, and bindings
I created a Python program called Elmer that uses Fabric to remotely interact with the cluster. Due to the way RabbitMQ manages metadata across the cluster, you have to wait for each step to complete for every node in the cluster before you can execute the next step; and checking the result of each step requires parsing the console output of shell commands (yuck!). Couple that with node-specific issues and network hiccups and you get a process with high time variation. In my tests, in addition to graceful shutdown and restart of the whole cluster, I often want to violently kill or restart a node.
From an operations point of view, this is not a problem. Launching a cluster, or replacing a node, are rare events and it's OK if it takes a few seconds. It is quite a different story for a developer who want to run a few dozen cluster tests after each change. Another complication is that some use cases require testing unresponsive nodes, which can lead to the halting problem (is it truly unresponsive or just slow?). After suffering through multiple test runs where each test was blocked for a long time waiting for the remote cluster, I ended up with the following approach:
- Elmer (the Python/Fabric cluster remote control program) exposes every step of the process
- A C# class called
Runnercan launch Python scripts and Fabric commands and capture the output
- A C# class called
RabbitMQutilizes the
Runnerclass to control the cluster
- A C# class called
Waitcan dynamically wait for an arbitrary operation to complete
The key was the
Wait class. The
Wait class has a static method called
Wait.For() that allows you to wait for an arbitrary operation to complete until a certain timeout. If the operation completes quickly, you will not have to wait for the time to expire, and
Wait will bail out quickly. If the operation doesn't complete in time,
Wait.For() will return after the timeout expires.
Wait.For() accepts a duration (either a
TimeSpan or number of milliseconds), and a function returns
bool. It also has a
Nap member variable that defaults to 50 milliseconds. When you call
Wait.For(), it calls your function in a loop until it returns
true or until the duration expires (napping between calls). If the function returns
true, then
Wait.For() returns
true; but if the duration expires, it returns
false.
public class Wait { public static TimeSpan Nap = TimeSpan.FromMilliseconds(50); public static bool For(TimeSpan duration, Func<bool> func) { var end = DateTime.Now + duration; if (end <= DateTime.Now) { return false; } while (DateTime.Now < end) { if (func.Invoke()) { return true; } Thread.Sleep(Nap); } return false; } public static bool For(int duration, Func<bool> func) { return For(TimeSpan.FromMilliseconds(duration), func); } }
Now, you can efficiently wait for processes that may take highly variable times to complete. Here is how I use
Wait.For() to check whether a RabbitMQ node is stopped:
private bool IsRabbitStopped() { var ok = Wait.For(TimeSpan.FromSeconds(10), () => { var s = rmq("status", displayOutput: false); return !s.Contains("{mnesia,") && !s.Contains("{rabbit,"); }); return ok; }
I call
Wait.For() with a duration of 10 seconds, which I wouldn't want to block on every time I check whether a node is down (since it happens all the time). The anonymous function I pass in calls the
rmq() method with the
status command. The
rmq() method runs the
status command on the remote cluster, then returns the command-line output as text. Here is the output when the Rabbit is running:
Status of node rabbit@GIGI ... [{pid,8420}, {running_applications, [{rabbitmq_management,"RabbitMQ Management Console","2.8.2"}, {xmerl,"XML parser","1.3"}, {rabbitmq_management_agent,"RabbitMQ Management Agent","2.8.2"}, {amqp_client,"RabbitMQ AMQP Client","2.8.2"}, {rabbit,"RabbitMQ","2.8.2"}, {os_mon,"CPO CXC 138 46","2.2.8"}, {sasl,"SASL CXC 138 11","2.2"}, {rabbitmq_mochiweb,"RabbitMQ Mochiweb Embedding","2.8.2"}, {webmachine,"webmachine","1.7.0-rmq2.8.2-hg"}, {mochiweb,"MochiMedia Web Server","1.3-rmq2.8.2-git"}, {inets,"INETS CXC 138 49","5.8"}, {mnesia,"MNESIA CXC 138 12","4.6"}, {stdlib,"ERTS CXC 138 10","1.18"}, {kernel,"ERTS CXC 138 10","2.15"}]}, {os,{win32,nt}}, {erlang_version,"Erlang R15B (erts-5.9) [smp:8:8] [async-threads:30]\n"}, {memory, [{total,19703792}, {processes,6181847}, {processes_used,6181832}, {system,13521945}, {atom,495069}, {atom_used,485064}, {binary,81216}, {code,9611946}, {ets,628852}]}, {vm_memory_high_watermark,0.10147532588839969}, {vm_memory_limit,858993459}, {disk_free_limit,8465047552}, {disk_free,15061905408}, {file_descriptors, [{total_limit,924},{total_used,4},{sockets_limit,829},{sockets_used,2}]}, {processes,[{limit,1048576},{used,181}]}, {run_queue,0}, {uptime,62072}] ...done.
The function is making sure that the
mnesia and
rabbit components don't show up in the output. Note that if the node is still up, the function will return
false and
Wait.For() will continue to execute it multiple times.
Wait.For() decreases the sensitivity of my tests to occasional spikes in response time (I can
Wait.For() longer without slowing down the test in the common case), and has reduced the runtime of the whole test suite from minutes to seconds.
Conclusion
The sum total of this series of articles has shown a variety of design principles and testing techniques to deal with hard-to-test systems. Nontrivial code will always contain bugs, but deep testing is guarantied to reduce the number of undiscovered issues.
Gigi Sayfan specializes in cross-platform object-oriented programming in C/C++/ C#/Python/Java with emphasis on large-scale distributed systems, and is a long-time contributor to Dr. Dobb's.
Related Articles
Testing Complex C++ Systems | http://www.drdobbs.com/windows/net-development-on-linux/windows/testing-python-and-c-code/240147927?pgno=3 | CC-MAIN-2017-09 | refinedweb | 1,082 | 56.86 |
libmcrypt - encryption/decryption library
Synopsis
Description
Authors
[see also mcrypt.h for more information]
The libmcrypt is a data encryption library. The library is thread safe and provides encryption and decryption functions. This version of the library supports many encryption algorithms and encryption modes. Some algorithms which are supported: SERPENT, RIJNDAEL, 3DES, GOST, SAFER+, CAST-256, RC2, XTEA, 3WAY, TWOFISH, BLOWFISH, ARCFOUR, WAKE and more.
OFB, CBC, ECB, nOFB, nCFB and CFB are the modes that all algorithms may function. ECB, CBC, encrypt in blocks but CTR, nCFB, nOFB, CFB and OFB in bytes (streams). Note that CFB and OFB in the rest of the document represent the "8bit CFB or OFB" mode. nOFB and nCFB modes represents a n-bit OFB/CFB mode, n is used to represent the algorithms block size. The library supports an extra STREAM mode to include some stream algorithms like WAKE or ARCFOUR.
In this version of the library all modes and algorithms are modular, which means that the algorithm and the mode is loaded at run-time. This way you can add algorithms and modes faster, and much easier.
LibMcrypt includes the following symmetric (block) algorithms:
DES: The traditional DES algorithm designed by IBM and US NSA. Uses 56 bit key and 64 bit block. It is now considered a weak algorithm, due to its small key size (it was never intended for use with classified data).
3DES or Triple DES: DES but with multiple (triple) encryption. It encrypts the plaintext once, then decrypts it with the second key, and encrypts it again with the third key (outer cbc mode used for cbc). Much better than traditional DES since the key is now 168 bits (actually the effective key length is 112 bits due to the meet-in-the-middle attack).
CAST-128: CAST was designed in Canada by Carlisle Adams and Stafford Tavares. The original algorithm used a 64bit key and block. The algorithm here is CAST-128 (also called CAST5) which has a 128bit key and 64bit block size.
CAST-256: CAST-256 was designed by Carlisle Adams. It is a symmetric cipher designed in accordance with the CAST design procedure. It is an extention of the CAST-128, having a 128 bit block size, and up to 256 bit key size.
xTEA: TEA stands for the Tiny Encryption Algorithm. It is a feistel cipher designed by David Wheeler & Roger M. Needham. The original TEA was intended for use in applications where code size is at a premium, or where it is necessary for someone to remember the algorithm and code it on an arbitrary machine at a later time. The algorithm used here is extended TEA and has a 128bit key size and 64bit block size.
3-WAY: The 3way algorithm designed by Joan Daemen. It uses key and block size of 96 bits.
SKIPJACK: SKIPJACK was designed by the US NSA. It was part of the ill-fated "Clipper" Escrowed Encryption Standard (EES) (FIPS 185) proposal. It operates on 64bit blocks and uses a key of 80 bits. SKIPJACK is provided only as an extra module to libmcrypt.
BLOWFISH: The Blowfish algorithm designed by Bruce Schneier. It is better and faster than DES. It can use a key up to 448 bits.
TWOFISH: Twofish was designed by Bruce Schneier, Doug Whiting, John Kelsey, Chris Hall, David Wagner for Counterpane systems. Intended to be highly secure and highly flexible. It uses a 128bit block size and 128,192,256 bit key size. (Twofish is the default algorithm)
LOKI97: LOKI97 was designed by Lawrie Brown and Josef Pieprzyk. It has a 128-bit block length and a 256bit key schedule, which can be initialized using 128, 192 or 256 bit keys. It has evolved from the earlier LOKI89 and LOKI91 64-bit block ciphers, with a strengthened key schedule and a larger keyspace.
RC2: RC2 (RC stands for Rivest Cipher) was designed by Ron Rivest. It uses block size of 64 bit and a key size from 8 to 1024 bits. It is optimized for 16bit microprocessors (reflecting its age). It is described in the RFC2268.
ARCFOUR: RC4 was designed by Ron Rivest. For several years this algorithm was considered a trade secret and details were not available. In September 1994 someone posted the source code in the cypherpunks mailing list. Although the source code is now available RC4 is trademarked by RSADSI so a compatible cipher named ARCFOUR is included in the mcrypt distribution. It is a stream cipher and has a maximum key of 2048 bits.
RC6: RC6 was designed by Ron Rivest for RSA labs. In mcrypt it uses block size of 128 bit and a key size of 128/192/256 bits. Refer to RSA Labs and Ron Rivest for any copyright, patent or license issues for the RC6 algorithm. RC6 is provided only as an extra module to libmcrypt.
RIJNDAEL: Rijndael is a block cipher, designed by Joan Daemen and Vincent Rijmen, and was approved for the USAs NIST Advanced Encryption Standard, FIPS-197. The cipher has a variable block length and key length. Rijndael can be implemented very efficiently on a wide range of processors and in hardware. The design of Rijndael was strongly influenced by the design of the block cipher Square. There exist three versions of this algorithm, namely: RIJNDAEL-128 (the AES winner) , RIJNDAEL-192 , RIJNDAEL-256 The numerals 128, 192 and 256 stand for the length of the block size.
MARS: MARS is a 128-bit block cipher designed by IBM as a candidate for the Advanced Encryption Standard. Refer to IBM for any copyright, patent or license issues for the MARS algorithm. MARS is provided only as an extra module to libmcrypt.
PANAMA: PANAMA is a cryptographic module that can be used both as a cryptographic hash function and as a stream cipher. It designed by Joan Daemen and Craig Clapp. PANAMA (the stream cipher) is included in libmcrypt.
WAKE: WAKE stands for Word Auto Key Encryption, and is an encryption system for medium speed encryption of blocks and of high security. WAKE was designed by David J. Wheeler. It is intended to be fast on most computers and relies on repeated table use and having a large state space.
SERPENT: Serpent is a 128-bit block cipher designed by Ross Anderson, Eli Biham and Lars Knudsen as a candidate for the Advanced Encryption Standard. Serpents design was limited to well understood mechanisms, so that could rely on the wide experience of block cipher cryptanalysis, and achieve the highest practical level of assurance that no shortcut attack will be found. Serpent has twice as many rounds as are necessary, to block all currently known shortcut attacks. Despite these exacting design constraints, Serpent is faster than DES.
IDEA: IDEA stands for International Data Encryption Algorithm and was designed by Xuejia Lai and James Massey. It operates on 64bit blocks and uses a key of 128 bits. Refer to Ascom-Tech AG for any copyright, patent or license issues for the IDEA algorithm. IDEA is provided only as an extra module to libmcrypt.
ENIGMA (UNIX crypt): A one-rotor machine designed along the lines of Enigma but considerable trivialized. Very easy to break for a skilled cryptanalyst. I suggest against using it. Added just for completeness.
GOST: A former soviet unions algorithm. An acronym for "Gosudarstvennyi Standard" or Government Standard. It uses a 256 bit key and a 64 bit block.
The S-boxes used here are described in the Applied Cryptography book by Bruce Schneier. They were used in an application for the Central Bank of the Russian Federation.
Some quotes from gost.c: The standard is written by A. Zabotin (project leader), G.P. Glazkov, and V.B. Isaeva. It was accepted and introduced into use by the action of the State Standards Committee of the USSR on 2 June 1989 as No. 1409. It was to be reviewed in 1993, but whether anyone wishes to take on this obligation from the USSR is questionable.
This code is based on the 25 November 1993 draft translation by Aleksandr Malchik, with Whitfield Diffie, of the Government Standard of the U.S.S.R. GOST 28149-89, "Cryptographic Transformation Algorithm", effective 1 July 1990. (Whitfield.Diffie@eng.sun.com) Some details have been cleared up by the paper "Soviet Encryption Algorithm" by Josef Pieprzyk and Leonid Tombak of the University of Wollongong, New South Wales. (josef/leo@cs.adfa.oz.au)
SAFER: SAFER (Secure And Fast Encryption Routine) is a block cipher developed by Prof. J.L. Massey at the Swiss Federal Institute of Technology. There exist four versions of this algorithm, namely: SAFER K-64 , SAFER K-128 , SAFER SK-64 and SAFER SK-128. The numerals 64 and 128 stand for the length of the user-selected key, K stands for the original key schedule and SK stands for the strengthened key schedule (in which some of the "weaknesses" of the original key schedule have been removed). In mcrypt only SAFER SK-64 and SAFER SK-128 are used.
SAFER+: SAFER+ was designed by Prof. J.L. Massey, Prof. Gurgen H. Khachatrian and Dr. Melsik K. Kuregian for Cylink. SAFER+ is based on the existing SAFER family of ciphers and provides for a block size of 128bits and 128, 192 and 256 bits key length.
A short description of the modes supported by libmcrypt:
STREAM: The mode used with stream ciphers. In this mode the keystream from the cipher is XORed with the plaintext. Thus you should NOT ever use the same key.
ECB: The Electronic CodeBook mode. It is the simplest mode to use with a block cipher. Encrypts each block independently. It is a block mode so plaintext length should be a multiple of blocksize (n*blocksize).
CBC: The Cipher Block Chaining mode. It is better than ECB since the plaintext is XORed with the previous ciphertext. A random block should be placed as the first block (IV) so the same block or messages always encrypt to something different. It is a block mode so plaintext length should be a multiple of blocksize (n*blocksize).
CFB: The Cipher-Feedback Mode (in 8bit). This is a self-synchronizing stream cipher implemented from a block cipher. This is the best mode to use for encrypting strings or streams. This mode requires an IV.
OFB: The Output-Feedback Mode (in 8bit). This is a synchronous stream cipher implemented from a block cipher. It is intended for use in noisy lines, because corrupted ciphertext blocks do not corrupt the plaintext blocks that follow. Insecure (because used in 8bit mode) so it is recommended not to use it. Added just for completeness.. This mode operates in streams.
nCFB: The Cipher-Feedback Mode (in nbit). n Is the size of the block of the algorithm. This is a self synchronizing stream cipher implemented from a block cipher. This mode operates in streams.
CTR: The Counter Mode. This is a stream cipher implemented from a block cipher. This mode uses the cipher to encrypt a set of input blocks, called counters, to produce blocks that will be XORed with the plaintext. In libmcrypt the counter is the given IV which is incremented at each step. This mode operates in streams.
Error Recovery in these modes: If bytes are removed or lost from the file or stream in ECB, CTR, CBC and OFB modes, are impossible to recover, although CFB and nCFB modes will recover. If some bytes are altered then a full block of plaintext is affected in ECB, nOFB and CTR modes, two blocks in CBC, nCFB and CFB modes, but only the corresponding byte in OFB mode.
Encryption can be done as follows:
A call to function: MCRYPT mcrypt_module_open( char *algorithm, char* algorithm_directory, char* mode, char* mode_directory);
This function associates the algorithm and the mode specified. The name of the algorithm is specified in algorithm, eg "twofish", and the algorithm_directory is the directory where the algorithm is (it may be null if it is the default). The same applies for the mode. The library is closed by calling mcrypt_module_close(), but you should not call that function if mcrypt_generic_end() is called before. Normally it returns an encryption descriptor, or MCRYPT_FAILED on error.
A call to function: int mcrypt_generic_init( MCRYPT td, void *key, int lenofkey, void *IV);
This function initializes all buffers for the specified thread The maximum value of lenofkey should be the one obtained by calling mcrypt_get_key_size() and every value smaller than this is legal. Note that Lenofkey should be specified in bytes not bits. The IV should normally have the size of the algorithms block size, but you must obtain the size by calling mcrypt_get_iv_size(). IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes. It needs to be random and unique (but not secret). The same IV must be used for encryption/decryption. After calling this function you can use the descriptor for encryption or decryption (not both). Returns a negative value on error.
To encrypt now call:
int mcrypt_generic( MCRYPT td, void *plaintext, int len);
This is the main encryption function. td is the encryption descriptor returned by mcrypt_generic_init(). Plaintext is the plaintext you wish to encrypt and len should be the length (in bytes) of the plaintext and it should be k*algorithms_block_size if used in a mode which operated in blocks (cbc, ecb, nofb), or whatever when used in cfb or ofb which operate in streams. The plaintext is replaced by the ciphertext. Returns 0 on success.
To decrypt you can call:
int mdecrypt_generic( MCRYPT td, void *ciphertext, int len);
The decryption function. It is almost the same with mcrypt_generic. Returns 0 on success.
When youre finished you should call:
int mcrypt_generic_end( MCRYPT td);
This function terminates encryption specified by the encryption descriptor (td). Actually it clears all buffers, and closes all the modules used. Returns a negative value on error. This function is deprecated. Use mcrypt_generic_deinit() and mcrypt_module_close() instead.
int mcrypt_generic_deinit( MCRYPT td);
This function terminates encryption specified by the encryption descriptor (td). Actually it clears all buffers. The difference with mcrypt_generic_end() is that this function does not close the modules used. Thus you should use mcrypt_module_close(). Using this function you gain in speed if you use the same modules for several encryptions. Returns a negative value on error.
int mcrypt_module_close( MCRYPT td);
This function closes the modules used by the descriptor td.
These are some extra functions that operate on modules that have been opened: These functions have the prefix mcrypt_enc_*.
int mcrypt_enc_set_state(MCRYPT td, void *state, int size); This function sets the state of the algorithm. Can be used only with block algorithms and certain modes like CBC, CFB etc. It is usefully if you want to restart or start a different encryption quickly. Returns zero on success. The state is the output of mcrypt_enc_get_state().
int mcrypt_enc_get_state(MCRYPT td, void *state, int *size); This function returns the state of the algorithm. Can be used only certain modes and algorithms. The size will hold the size of the state and the state must have enough bytes to hold it. Returns zero on success.
int mcrypt_enc_self_test( MCRYPT td);
This function runs the self test on the algorithm specified by the descriptor td. If the self test succeeds it returns zero.
int mcrypt_enc_is_block_algorithm_mode( MCRYPT td);
Returns 1 if the mode is for use with block algorithms, otherwise it returns 0. (eg. 0 for stream, and 1 for cbc, cfb, ofb)
int mcrypt_enc_is_block_algorithm( MCRYPT td);
Returns 1 if the algorithm is a block algorithm or 0 if it is a stream algorithm.
int mcrypt_enc_is_block_mode( MCRYPT td);
Returns 1 if the mode outputs blocks of bytes or 0 if it outputs bytes. (eg. 1 for cbc and ecb, and 0 for cfb and stream)
int mcrypt_enc_get_block_size( MCRYPT td);
Returns the block size of the algorithm specified by the encryption descriptor in bytes. The algorithm MUST be opened using mcrypt_module_open().
int mcrypt_enc_get_key_size( MCRYPT td);
Returns the maximum supported key size of the algorithm specified by the encryption descriptor in bytes. The algorithm MUST be opened using mcrypt_module_open().
int* mcrypt_enc_get_supported_key_sizes( MCRYPT td, int* sizes)
Returns the key sizes supported by the algorithm specified by the encryption descriptor.. The returned value is allocated with malloc, so you should not forget to free it.
int mcrypt_enc_get_iv_size( MCRYPT td);
Returns size of the IV of the algorithm specified by the encryption descriptor in bytes. The algorithm MUST be opened using mcrypt_module_open(). If it is 0 then the IV is ignored in that algorithm. IV is used in CBC, CFB, OFB modes, and in some algorithms in STREAM mode.
int mcrypt_enc_mode_has_iv( MCRYPT td);
Returns 1 if the mode needs an IV, 0 otherwise. Some stream algorithms may need an IV even if the mode itself does not need an IV.
char* mcrypt_enc_get_algorithms_name( MCRYPT td);
Returns a character array containing the name of the algorithm. The returned value is allocated with malloc, so you should not forget to free it.
char* mcrypt_enc_get_modes_name( MCRYPT td);
Returns a character array containing the name of the mode. The returned value is allocated with malloc, so you should not forget to free it.
These are some extra functions that operate on modules: These functions have the prefix mcrypt_module_*.
int mcrypt_module_self_test (char* algorithm, char* directory);
This function runs the self test on the specified algorithm. If the self test succeeds it returns zero.
int mcrypt_module_is_block_algorithm_mode( char* algorithm, char* directory);
Returns 1 if the mode is for use with block algorithms, otherwise it returns 0. (eg. 0 for stream, and 1 for cbc, cfb, ofb)
int mcrypt_module_is_block_algorithm( char* mode, char* directory);
Returns 1 if the algorithm is a block algorithm or 0 if it is a stream algorithm.
int mcrypt_module_is_block_mode( char* mode, char* directory);
Returns 1 if the mode outputs blocks of bytes or 0 if it outputs bytes. (eg. 1 for cbc and ecb, and 0 for cfb and stream)
int mcrypt_module_get_algo_block_size( char* algorithm, char* directory);
Returns the block size of the algorithm.
int mcrypt_module_get_algo_key_size( char* algorithm, char* directory);
Returns the maximum supported key size of the algorithm.
int* mcrypt_module_get_algo_supported_key_sizes( char* algorithm, char* directory, int* sizes);
Returns the key sizes supported by the algorithm.. This function differs to mcrypt_enc_get_supported_key_sizes(), because the return value here is allocated (not static), thus it should be freed.
char** mcrypt_list_algorithms ( char* libdir, int* size);
Returns a pointer to a character array containing all the mcrypt algorithms located in the libdir, or if it is NULL, in the default directory. The size is the number of the character arrays. The arrays are allocated internally and should be freed by using mcrypt_free_p().
char** mcrypt_list_modes ( char* libdir, int *size);
Returns a pointer to a character array containing all the mcrypt modes located in the libdir, or if it is NULL, in the default directory. The size is the number of the character arrays. The arrays should be freed by using mcrypt_free_p().
void mcrypt_free_p (char **p, int size);
Frees the pointer to array returned by previous functions.
void mcrypt_free (void *ptr);
Frees the memory used by the pointer.
void mcrypt_perror(int err);
This function prints a human readable description of the error err in the stderr. The err should be a value returned by mcrypt_generic_init().
const char* mcrypt_strerror(int err);
This function returns a human readable description of the error err. The err should be a value returned by mcrypt_generic_init().
int mcrypt_mutex_register ( void (*mutex_lock)(void) , void (*mutex_unlock)(void) );
This function is only used in multithreaded application and only if compiled with dynamic module loading support. This is actually used internally in libltdl. Except for the dynamic module loading libmcrypt is thread safe.
Some example programs follow here. Compile as "cc prog.c -lmcrypt", or "cc prog.c -lmcrypt -lltdl" depending on your installation. Libltdl is used for opening dynamic libraries (modules).
/* First example: Encrypts stdin to stdout using TWOFISH with 128 bit key and CFB */
#include <mcrypt.h> #include <stdio.h> #include <stdlib.h> /* #include <mhash.h> */
main() {
MCRYPT td; int i; char *key; char password[20]; char block_buffer; char *IV; int keysize=16; /* 128 bits */
key=calloc(1, keysize); strcpy(password, "A_large_key");
/* Generate the key using the password */ /* mhash_keygen( KEYGEN_MCRYPT, MHASH_MD5, key, keysize, NULL, 0, password, strlen(password)); */ memmove( key, password, strlen(password));
td = mcrypt_module_open("twofish", NULL, "cfb", NULL); if (td==MCRYPT_FAILED) { return 1; } IV = malloc(mcrypt_enc_get_iv_size(td));
/* Put random data in IV. Note these are not real random data, * consider using /dev/random or /dev/urandom. */
/* srand(time(0)); */ for (i=0; i< mcrypt_enc_get_iv_size( td); i++) { IV[i]=rand(); }
i=mcrypt_generic_init( td, key, keysize, IV); if (i<0) { mcrypt_perror(i); return 1; }
/* Encryption in CFB is performed in bytes */ while ( fread (&block_buffer, 1, 1, stdin) == 1 ) { mcrypt_generic (td, &block_buffer, 1);
/* Comment above and uncomment this to decrypt */ /* mdecrypt_generic (td, &block_buffer, 1); */
fwrite ( &block_buffer, 1, 1, stdout); }
/* Deinit the encryption thread, and unload the module */ mcrypt_generic_end(td);
return 0;
}
/* Second Example: encrypts using CBC and SAFER+ with 192 bits key */
#include <mcrypt.h> #include <stdio.h> #include <stdlib.h>
main() {
MCRYPT td; int i; char *key; /* created using mcrypt_gen_key */ char *block_buffer; char *IV; int blocksize; int keysize = 24; /* 192 bits == 24 bytes */
key = calloc(1, keysize); strcpy(key, "A_large_and_random_key");
td = mcrypt_module_open("saferplus", NULL, "cbc", NULL);
blocksize = mcrypt_enc_get_block_size(td); block_buffer = malloc(blocksize); /* but unfortunately this does not fill all the key so the rest bytes are * padded with zeros. Try to use large keys or convert them with mcrypt_gen_key(). */
IV=malloc(mcrypt_enc_get_iv_size(td));
/* Put random data in IV. Note these are not real random data, * consider using /dev/random or /dev/urandom. */
/* srand(time(0)); */ for (i=0; i < mcrypt_enc_get_iv_size(td); i++) { IV[i]=rand(); }
mcrypt_generic_init( td, key, keysize, IV);
/* Encryption in CBC is performed in blocks */ while ( fread (block_buffer, 1, blocksize, stdin) == blocksize ) { mcrypt_generic (td, block_buffer, blocksize); /* mdecrypt_generic (td, block_buffer, blocksize); */ fwrite ( block_buffer, 1, blocksize, stdout); }
/* deinitialize the encryption thread */ mcrypt_generic_deinit (td);
/* Unload the loaded module */ mcrypt_module_close(td); return 0;
}
The library does not install any signal handler.
Questions about libmcrypt should be sent to:
Version 2.4 Copyright (C) 1998-1999 Nikos Mavroyanopoulos (nmav@hellug.gr).
Thanks to all the people who reported problems and suggested various improvements for mcrypt; who are too numerous to cite here. | http://manpages.sgvulcan.com/mcrypt.3.php | CC-MAIN-2017-26 | refinedweb | 3,694 | 65.42 |
import java.util.Scanner; public class Palindromes { public static boolean isPal(String s) { if(s.length() == 0 || s.length() == 1) return true; if(s.charAt(0) == s.charAt(s.length()-1)) return isPal(s.substring(1, s.length()-1)); return false; } public static void main(String[]args) { boolean quit = true; Scanner sc = new Scanner(System.in); System.out.println("Enter a word to test whether it is a palindrome or not. Type quit to end."); String x = sc.nextLine(); while(quit) { if(isPal(x)) System.out.println(x + " is a palindrome"); if else(x = quit) quit = false; else System.out.println(x + " is not a palindrome"); } } }
im trying to create a program that Prompts the user to input a word or phrase, Allows the user to continue entering input until they choose to quit, has a recursive method to determine if the word or phrase entered is a palindrome, and prints a message that tells the user whether the word or phrase is a palindrome. i have most of this, but im not sure if i am going about it the right way. i tried to make it so that it would continue over and over again, but im getting an error on my if else statement ')' expected. if anyone has any advice or a solution it is much appreciated. thanks. | http://www.dreamincode.net/forums/topic/142882-java-palindrome/page__p__853183 | CC-MAIN-2016-18 | refinedweb | 221 | 66.54 |
Bundling and minification an important part of your deployment process. It ensures all JavaScript files are bundled into 1 single file so only 1 HTTP request is required to download all your JS. It also minifies all JS files so they are significantly reduced in size. It does this by removing all comments, whitespace, renaming variables to single letters and rearranging some syntax and functions into to far smaller and far less human readable code.
This improves performance and will speed up your pages as there is less data for client browsers to download.
However, minification can causes problems with your development unless you separate it out correctly. The last thing you want is to be debugging minified JavaScript.
In this tutorial, I’ll be showing you how to best introduce bundling and minification into your ASP.NET MVC Web Application.
First thing you need to do is download the following extension by Mads Kristensen Called "Bundler & Minifier" you can view it here
Once installed you can start adding which JS files you want it to minify and update on each save. This works by adding a .json file into your solution called bundleconfig.json. Initially you need to add your JS files manually by highlighting your file in solution explorer and using the shortcut "Shift + Alt + F" This will add a new entry into your bundleconfig.json file and create a new min.js file of the same name. Unfortunalty there is now way at time of writing to select multiple JS files and add all at once, annoying I know, especially if you have a lot of files.
Once you have added all your files into your bundleconfig.json you can open the Task Runner Explorer window in Visual Studio and manage your minification from here. This allows you to clear all .min.js files and update them all in one hit. There is a command window to the right that gives you an insight into any errors or files that cannot be minified.
So you now have .min.js files for all your JavaScript. Now you need to set it up so only your .min.js files are called on your production server and not your dev/local environment. This is so you can debug and develop your JS without it automatically referencing the minified versions.
To set this up we need to create a new AppSetting in Web.Config. This is an environment setting which has a value of "DEV" or "LIVE" for your development and live environments.
<!--App settings--> <add key="Environment" value="DEV" />
We can use this setting in the BundleConfig.cs, RegisterBundles method. All we are doing is setting up an IF statement to test the Environment. If its live all the bundle JS files are .min.js. If its Dev then we are referencing the non-minified versions. See the code below...
public class BundleConfig { // For more information on bundling, visit public static void RegisterBundles(BundleCollection bundles) { if (ConfigurationManager.AppSettings["Environment"] == "LIVE") { bundles.Add(new ScriptBundle("~/bundles/appscripts").Include( "~/Scripts/AppScripts/ArticleScript.min.js", "~/Scripts/AppScripts/IBScript.min.js", "~/Scripts/AppScripts/LoginScript.min.js", "~/Scripts/AppScripts/SearchScript.min.js", "~/Scripts/AppScripts/SignUp.min.js", "~/Scripts/AppScripts/UserProfile.min.js" )); } else { bundles.Add(new ScriptBundle("~/bundles/appscripts").Include( "~/Scripts/AppScripts/ArticleScript.js", "~/Scripts/AppScripts/IBScript.js", "~/Scripts/AppScripts/LoginScript.js", "~/Scripts/AppScripts/SearchScript.js", "~/Scripts/AppScripts/SignUp.js", "~/Scripts/AppScripts/UserProfile.js" )); }
So now we have set up bundling and minification. Awesome! Final thing we need to so is reference the bundle URL references. It most apps, you can simple add this to your layout page, which is the case for IntermittentBug.
@Scripts.Render("~/bundles/appscripts")
To test it, simply open your browser and F12 to the dev tools. If you invert the if statement in register Bundles to be != "Live" you can see your app referencing all your minified JS files. This will also show how much data is being downloaded. For IntermittentBug at time of writing, it got it down from 488kb down to just 81kb an 83% decrease.
Above - shows that all JS files are non minified. this is with != "LIVE" set in BundleConfig.cs
Above - shows that all JS files are minified. | https://www.intermittentbug.com/article/articlepage/bundling-and-minification-in-asp.net-mvc/2269 | CC-MAIN-2019-13 | refinedweb | 703 | 58.48 |
Hi,
I am trying to make a code that has multiple buttons, but the only way i know how to make action listeners are to either use inner classes (which require variable to be final, which isnt good for me), or to use AddActionListener(this), which only allows for one action listener.
Ive heard somehting about getSource(), but cant find any good examples of how its used... Are there any other ways to use multiple action listeners?
This is a code i was experimenting with getSource on, but i kept on getting an error:
Code :
import java.awt.*; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class FindAddPage implements ActionListener { public static void main (String[] args) { int counter = 0; //set up frame GridLayout myLayout = new GridLayout (2,1); JFrame myFrame = new JFrame ("Add/Find"); myFrame.setSize(400,200); JPanel myPanel = new JPanel(); myPanel.setLayout(myLayout); //make buttons JButton add = new JButton ("Add A Tutor"); JButton find = new JButton ("Find A Tutor"); if(event.getSource()==add){ counter++; } myFrame.setVisible(true); } } | http://www.javaprogrammingforums.com/%20awt-java-swing/12517-how-use-multiple-actionlisteners-printingthethread.html | CC-MAIN-2015-22 | refinedweb | 175 | 54.12 |
Shell Ditches Wind, Solar, and Hydro 883
thefickler writes "Shell has decided to end its investment in wind, solar and hydro projects because the company does not believe they are financially sound investments. Instead Shell is going to focus on carbon sequestration technologies and biofuels. Not surprisingly, and perhaps unfairly, bloggers have been quick to savage the company: 'Between Shell's decisions to stop its clean energy investments and to increase its debt load to pay for dividends, the company is solidifying an image of corporate greed over corporate responsibility.' Is Shell short sighted, or is it just a company trying to make its way in an uncertain world?"
Corporate culture (Score:5, Insightful)
As a company, if they can make more money on oil than on wind, then clearly the shareholders will demand oil. Oil is there bread and butter. I wouldn't expect them to innovate on something that is outside of their corporate culture. Like with the movie and music and software industries; you get innovation and creativity from smaller independent entities, and conservativism from the established entities.
Re:Corporate culture (Score:5, Insightful)
so the big question becomes: Is Shell an oil company, or an energy company?
while oil is currently very cheep, it's supply is limited to hundreds of years. Renewable energy is expensive now, but it will not run out for a very long time. (billions of years)
to use a car analogy, Shell has gotten off the future express way and is driving down a dead end street. it may be a very long road, but it will come to an end.
Re:Corporate culture (Score:5, Insightful)
while oil is currently very cheep, it's supply is limited to hundreds of years.
I'm not too sure about that. Regardless however, the equation remains stable: when the supply diminishes then prices increase. It's the paradox of people hunting animals to extinction; the more rare the animal the more money hunters can demand for it until there is no more left.
Oil company's need an excuse to change into generic energy companies. By hook or by crook they'll take the path of least resistance to the highest profit margin (whether it be with oil or solar panels).
Re:Corporate culture (Score:5, Insightful)
In this case, Shell simply decided that's it's marketing campaign of green energy investments was promoting threatening ideas and, generating insufficient advertising benefit. Bio-fuels (starving the third world) and burying pollution underground (at the tax payers expense) were far more profitable and in harsh economic times, knows that the public will be far to worried about keeping their home, feeding their family and panicking about possible medical emergencies, that they would largely ignore the end of the clean green PR=B$. Come on did anybody seriously believe shell was interested in alternative renewable energy beyond a cynical exercise in marketing.
The only source for funds for the development of cheap renewable energy has to be the government, there is no profit in it and the real benefits are the free benefits of a cleaner healthier environment, lower medical costs from a healthier population and of course cheap 'free' energy(beyond initial capital outlay and maintenance).
Re:Corporate culture (Score:5, Insightful)
Every project goes through a cost benefit analysis. Shell apparently did the analysis, and the conclusions were that investment in wind and solar are unlikely to pay for themselves, even in the long run. Or, more precisely, investments in wind and solar are unlikely to pay better than investments in oil and gas, even in the long run.
Besides, there's nothing to prevent them from re-entering the market if the economics change.
Re:Corporate culture (Score:5, Insightful)
The problem is, the economic viability of biofuels is questionable, and carbon sequestration definitely isn't viable from physics.
The problem isn't they chose to kill off technologies which are not promising, the problem is they chose to pursue those that are less energy efficient, if at all (and thus, unless they scam someone, less promising).
They expect they will market them to government or something, rather than solve ecological problems. That's why its wrong.
Re:Corporate culture (Score:5, Insightful)
less energy efficient != less profitable. When solar, wind, etc., become more profitable than oil, Shell will be clamouring to get back in, don't worry.
I've been saying for years that the only way to get the planet to switch to "green" technologies is to find a way to make the energy derived from them cheaper than the alternatives. Even now, the only reason we're still on coal and natural gas for generation of power is that they're cheaper politically (partially due to being the status quo) than nuclear power.
Re:Corporate culture (Score:5, Informative)
*facepalm*
Biofuels do not "starve the third world." Nobody credible on the subject of biofuels has seriously advocated using food crops for fuel ("credible" includes those who are not obviously shills for the corn growers here). The crops that, so far, have shown the best potential for fuel sources are not only not food/feed crops, but they can be grown on land that is otherwise unsuitable for food crops.
And maybe if we spent just a portion of our food providing efforts reforming their lands and teaching them to grow and maintain their own food, not only would they be better off in the long run but you'd create jobs where they are desperately needed.
So enough with the "starving the third world" nonsense. There is zero credibility in that argument.
=Smidge=
Re:Corporate culture (Score:4, Informative)
Sometime you should look up the break down of where corn goes.
Here's a spoiler for you: the vast majority of corn produced goes into animal feed. Not 50%. Not 60% More like 80%+. Corn used for ethanol fuel is a sliver of the human use percentage.
But yeah, we're totally starving third world countries to make ethanol. Totally.
Re:Corporate culture (Score:4, Insightful)
Demonizing their actions is stupid. Shell is a for profit corporation and it's clear they are predicting cheap oil for the foreseeable future. What they are doing is both reasonable and predictable. By their own admission the alt-energy projects weren't financially feasible. Their own stockholders can and will sue if they keep dumping money into non-starter projects.
Stop expecting them to behave like philanthropists. The government can dump all the money it wants into economically questionable ventures - like ethanol fuel - but that doesn't mean it will ever make money or even work. The simple fact of the matter is that oil is too cheap. When companies like Shell can bank on profits from a proven alt-energy source you'll see an explosion of investment.
Re:Corporate culture (Score:4, Insightful)
Bio-fuels (starving the third world)
Yeah, it's our fault that the third world is a toilet. We're not the ones who are running the regimes of their oppressive dictators. We're not the ones diverting international aid away from starving people. Yes, production of biofuels makes the cost of some food items increase. But if they'd grow their own fucking food, it wouldn't be an issue.
LK
Re:Corporate culture (Score:5, Insightful)
So, what you're saying is that interference from the outside cause the problem in the first place, and interference from outside is continuing the problems. And the people of the poor countries (who have ALWAYS been that way) have nothing to do with the situation.
Yes, it is always evil white people's fault. Always!
I'm kind of sick of the people who blame everything on Western Eurpopean culture. It is a fallacy. Japan was nearly wiped out after WWII, practically nuked into the stoneage. And yet they figured out how to crawl out of it in less than one generation. AND they have almost no natural resources.
And yet, we leave places like Afgahnistan alone for twenty years, and the Taliban take over and take a relatively modern nation back to the Stone Age. Yes, that was all Colonialism's fault. Because the Taliban wouldn't have ever taken over if it wasn't for the Russian invasion
...
The problem is, that you can always blame the current problems on something else. Obama is taking the problems of the Bush (who sucked royal eggs IMHO) Admin and REALLY is making them worse. But nobody seems to care because he speaks so eloquently (teleprompter mishaps not withstanding) and has a pretty smile.
Re:Corporate culture (Score:5, Interesting)
You know, I live in Finland, which was first Sweden's and then Russia's colony until 1917, underwent a devastating civil war right after gaining independence, and was attacked by the Soviet Union twice in World War II, and had to resettle 400,000 people and pay $300,000,000 in war preparations. And yet, after all this, we're somehow overproducing relative to our needs, despite the fact that the country sits on the Arctic Circle rather than at the equator.
At some point blaming some long-ago event for your problems becomes ridiculous. African countries have been independent for decades now, and even the Cold War ended over a decade ago; if they remain hellholes incapable of feeding their own population, the blame now rests on said population.
"Our forefathers were oppressed so we must keep on killing our farmers or at least stealing their land." Victim complex at its finest. Besides, Africa seems to be the only former colony to be having this problem...
Re:Corporate culture (Score:5, Insightful)
Uhhh....
everything is a pollutant when it is present in concentrations such that the current local environment can not deal with them.
Re:Corporate culture (Score:5, Funny)
Like Humans!
Yes, but you can make Soylent Green out of them.
Re:Corporate culture (Score:5, Insightful)
As it happens, one of the biggest sources of pollution for waterways is fertilizer. It gets washed from the fields into the water, where it promotes the growth of algae, turning a lake into a stinking pit. And the same happens in coastal areas where ever the conditions don't disperse it fast enough.
Your argument seems to be that something can't be both a fertilizer and a pollutant, which is wrong.
Re:Corporate culture (Score:5, Insightful)
Corporate profits are unfortunately something that is shortsighted. What is the *cost* of putting all the extra CO2 into the air? at this exact moment, probably fairly minimal, but over time as we continue the cost may very well be extreme.
The gov't is the leveling factor, by pricing oil artificially higher to encourage a different direction for a better long term result.
Some will say we don't need it, and while there is general scientific consensus that we do, factual evidence is scarce since we're making predictions about the future. By the time actual evidence exists it will be far to late to 'fix' the problem.
Shell probably sees the writing on the wall, their industry is a monopoly on our transportation...switching to electric or other renewables means they will no longer be that monopoly. Its the govt's responsibility to look beyond short term profits and move us to something sustainable.
Re:Corporate culture (Score:5, Insightful)
Let me say that firstly, CO2 is not a pollutant, it's a plant fertiliser.
By that definition, cow manure isn't a pollutant either. Just because plants enjoy it doesn't mean it won't cause us problems if there's too much of it.
Re:Corporate culture (Score:4, Insightful)
Re:Corporate culture (Score:5, Informative)
We really don't know how much oil there is down there, but it's not running out anytime soon.
We've a much better idea of how much oil is down there than in the 1920s. We've already found the easy/cheap-to-exploit stuff, any future finds will be more expensive than what we have now.
Re:Corporate culture (Score:5, Informative)
We're already running toward the end of cheap easy to extract oil. From the dawn of the oil age to the 1960s, new large oil fields were discovered close to the surface that were very inexpensive to extract (culminating in the Saudi Ghawar Field in 1948 which has production costs of well under $10/barrel). Here's [wikipedia.org] the list from Wikipedia. I found discovery dates for the missing Mesopotamian field (1961). Since then discoveries have gotten smaller (only three top 10 fields discovered after 1961 and all were under water, two under deep water, which raises the costs of extraction considerably). There will likely be additional oil finds, probably even major field finds, but I believe it's safe to say that we will never find anything that will be large and cheap like the fields that are currently huge producers.
Re:Corporate culture (Score:5, Insightful)
but is it really that hard to grasp that new technologies allow us to reach deeper (and sideways) for oil that was previously out of reach?
Not at all. After all, there MUST be pirate treasure buried in my backyard. The problem is that nobody's invented good enough metal detection technology to enable me to find it.
Re:Corporate culture (Score:5, Insightful)
to use a car analogy, Shell has gotten off the future express way and is driving down a dead end street. it may be a very long road, but it will come to an end.
That's not a very good analogy really. Right now, oil is probably more representative of a highway that comes to an abrupt end in a very dry and barren desert; you know that it's going to end at some point, but you are not 100% sure quite where that it is. Alternative energy is a maze of meandering side roads and dead ends that lie to either side of the high way that represent higher short-term running costs, research that leads to economically or environmentally nonviable solutions, or equally bad dead ends as oil. Some of those roads, however, do lead to the future express way and those are the ones we have to find, but the problem is we don't really have a good map yet.
I'd say Shell has simply decided that, right now, they need to sit out The Recession with what to them at least is a safe and financially sound proposition in the form of biofuels, by getting back onto the dead-end highway for a while. This is really just the same basic strategy being taken by all those other business that have been focusing on their core operating markets recently. At least that way they're still moving and they know that the road remains good for a while yet, and it doesn't preclude them from doing a little more exploring of the side roads later on, and there might even be some better maps by then...
Energy Return On Energy Input (Score:5, Interesting) [wikipedia.org]
Oil was 100:1
As the quality of the oil declines (e.g. to tar sands), so does the energy return (e.g. 5:1 or 3:1) and we have to spend more of our time simply trying to generate energy.
And if 30% of our time and energy are going into producing more energy... There isn't much time and energy available to do other things, like run a civilization.
Wind seems to average approximately 20:1 over the lifetime of a turbine.
What is interesting is that in the short term because of our sunk investment in oil, it is more profitable for companies to produce bio-oil at 8:1 EROEI than it is to produce wind turbines or solar panels.
Re:Energy Return On Energy Input (Score:5, Informative)
And if 30% of our time and energy are going into producing more energy... There isn't much time and energy available to do other things, like run a civilization.
If only we had the technology to produce energy with a favorable EROEI. Maybe one day we'll be able to split the atom or something.
Re:Energy Return On Energy Input (Score:5, Informative)
As much as I like to bash megacorps for their misbehavior... that is completely unfair. I grew up less than 20 minutes from the Duane Arnold Energy Center (a nuclear powerplant outside Cedar Rapids, IA). They've never had an accident.
In fact the WORST accident in the History of nuclear power in the United States was Three Mile - and it was only a disaster because of the misinformation is spread about nuclear energy. The TOTAL dose of radiation that managed to escape Three Mile was less than the dose you'd get from the radioisotopes in the granite making up the halls of congress in a day.
Furthermore there are more modern reactor designs in which they're design to be IMPOSSIBLE to have criticality excursions (aka melt downs) - things such as PBRs where the nuclear moderator used in it is designed to become more efficient at capturing neutrons at higher temperatures. Literally if the coolant system fails the reactor, just by nuclear physics, ramps itself down. They've tried to make a PBR melt down, you cannot do it - their design was a success.
There are also other designs that cannot have criticality excursions.
Then there is also research into fusion reactors - again something that cannot have criticality excursions.
Re:Energy Return On Energy Input (Score:5, Informative)
And that still haven't figured out what to do with the waste?
Amazingly enough France doesn't have this problem because they recycle the waste.
Waste, safety, weapons proliferation, and fuel sarcity make uranium/plutonium fission a dead end
The French have solved the waste problem, the "safety" issue is FUD, weapons proliferation can be dealt with through the existing channels (and seems to be happening anyway without much help from the civilian power industry) and I have yet to see any proof that we are running out of fissionable material.
Re: (Score:3, Insightful)
But when the oil is out they can benefit from others investments in renewable energy and expand in that area at a lower cost.
Re:Corporate culture (Score:5, Interesting)
Shell is an oil company. Hands down.
Now, this is where I have a problem with the vast majority of the posts on this article, including yours. Everyone is quick to make Shell out as the big bad oil company and for being shortsighted. I certainly take your comment, "future express way" and "dead end street" to mean exactly that.
Why?
I don't believe in Hydro, Wind, or Solar either. Not on a large scale. I think those technologies are perfect supplements. Point source implementations on single houses and small communities. It will just never scale to the point it can provide power for industry or transportation.
Hydro, Wind, and Solar are also being researched and developed by a heck of a lot of people. New technologies and patents are being developed at a rapid pace. There is a LOT of competition here.
Once again, Shell is an Oil Company.
They are sticking to what they know best. That is drilling and fuel. Carbon sequestration technologies are sorely needed. We have to put it somewhere. Why not a company that has a lot of experience drilling and fraccing? Sounds like a perfect match to me.
Biofuels are the other area that Shell has decided to concentrate on. Every time I pass one of their gas stations (note I said pass) they are always more than the competition. They have patented technology for fuel. These are people that have expertise in creating fuel. Why not have them work on new biofuels? Seems reasonable to me.
I am practical person and just as much a pro environment as anybody else. Let's just take a deep breath and be reasonable about it. I see no reason to make Shell out as the enemy here simply because they want to concentrate solely on two areas of environmental technology.
What they are doing is helping. So why all the hate from all the posters?
New large scale solar plant in Arizona (Score:4, Interesting) [inhabitat.com]
The entire midwest is ideal for Solar. Death Valley? Thousands of acres sitting empty. Who'd want to live there? Solar...
Just because something hasn't been done doesn't mean that it can't be or shouldn't be.
Re:New large scale solar plant in Arizona (Score:5, Interesting)
Thousands of acres sitting empty. Who'd want to live there? Solar...
Or we could build a single nuclear power plant that doesn't need thousands of acres as a footprint and would generate more power to boot. Just saying.....
Re:New large scale solar plant in Arizona (Score:5, Informative)
We already have cleaner nuclear fuel through the ability to reprocess the waste. The problem is that we have antiquated laws from the 1970s prevents us from being able to do so. Hell, we have to import our medicinal isotopes from Canada because we are not allowed to refine them here. Good read here [wsj.com].
Re: (Score:3, Insightful)
Re:Corporate culture (Score:4, Insightful)
Once oil will not be profitable enough....
Oil will *always* be profitable. Especially when you're sucking the last few barrels out of 100 year old wells and selling it to a captive market who either couldn't afford to switch to something renewable or have no real alternative.
You damn well charge what you want.
Re:Corporate culture (Score:4, Insightful)
Because people aren't, in general, all that bright. Do you see much evidence that people are moving away from cars & fossil fuel dependency?
To what? You give me an reasonably priced, safe car that can get me to work and back with the AC or heater on full every day that doesn't use fossil fuels, and I'll gladly drive it.
As for now, don't call me stupid because I don't drive a car that does not exist.
Re:Corporate culture (Score:5, Insightful)
Re: (Score:3, Insightful)
Re:Corporate culture (Score:4, Insightful)
Back when XEROX had the personal computer technology when nobody else did, their top brass decided not to go for it because it was outside their corporate culture. "We are a xerographic company"... The rest is history
:(
And what history is that? An incredibly rich and vibrant personal computing field? Companies stick to core competencies precisely because it is what they are good at. Leave getting good at personal computers to someone else, which someone else did.
When large corporations reach outside their core competency, danger looms. Microsoft is a software company. They attempted to build complicated hardware and got a two-thirds RROD rate. Examples like this abound.
Thats ok (Score:5, Interesting)
I mean can you say 'conflict of interests'?
Leave it to the little guys that are better (specialized/core business) at it anyway.
And at least now we truly know where they stand.
No Conflict. (Score:3, Insightful)
In fact, it's logical for the oil companies to be behind any future fuels. They already have much of the infrastructure required for it, there is no way any start up can build up to that level in a reasonable amount of time.
This isn't BIG OIL(ever notice how you can put "big" in front of any industry to make them sound evil?) killing renewable fuels, it's a business accepting that these technologies are unfeasible for them. Wind and solar are dicey at best as energy sources. Hydro is made impossible by t
It's fusion or bust (Score:5, Insightful)
Controlled fusion is the next step for our species. We won't know how hard it is except for retrospectively, but we haven't got much time left.
Nobody wants to save energy. There are billions of people on this planet that would like to use half as much energy as an average American, and no amount of wind or solar is going to deliver that.
No, no, no (Score:5, Insightful)
"[New energy source] or bust" is a very irresponsible thing to say; we need to learn to compromise. But I'll just focus on your particular suggestion of fusion:
Fusion is very promising, if only because it has no proliferation worries, but other than that all of the advantages that count are already available in fission reactors.
Think solar is renewable? Not as renewable as nuclear.
All we need is for the public to get their heads out of their asses and learn to accept compromise.
Re:No, no, no (Score:5, Insightful)
But your comments on Fission are out by quite a bit. First it is *not* cheap. The new reactors are costing upwards of 5billion and can be higher than 10B. That totally ignores waste management costs that are heavily controlled and fixed by government regulation. There is plenty of nuclear fuel if we reprocess and use Thorium fuel cycles. The US does not reprocess and hence on a pure U based cycle you are looking at a few 100s of years IIRC (so a few 1000s with reprocessing). Even with reprocessing 5 billion years of U fuel is not here- but thats long term planing in the extreme.
Now the "its available now" comes with a caveat. What to do with the waste? Lets at least plan a head a little. We could develop fast reactors and/or accelerators driven reactors to reduce the waste to something quite manageable. But this kind of R&D reactor will come in the 20B+ price bracket with a 10+ year program. Quite similar to Fusion. After than you only know it can work, we still need to build the reactors.
Personally I think we should invest R&D into both. We don't know if they will be economical. But it would be nice to have the option.
Re:No, no, no (Score:4, Insightful)
Now the "its available now" comes with a caveat. What to do with the waste?
Bury it. It's a relatively small problem which we can solve when we have better tech (assuming the waste won't become a commodity), we have bigger things to worry about now.
First it is *not* cheap.
"Cheap" is relative, and hard to work out. Should we include a portion of the potential cost of dealing with global warming into the price of a coal plant? Nuclear power, as you said, includes the cost of decommissioning and clean-up.
Also we don't know how long these plants last. Our current generations of reactors have been able to run long past their original estimated expiry dates; when the cost of the fuel is so cheap and plants last a very long time the cost of the plant has to be taken in context.
You forgot one major thing though. (Score:3, Insightful)
Well. Two.
NIMBY
BANANA
And the fact that if you say "nuclear" to some people, they do a GREAT imitation of a cat, arching their spines, hissing and spitting.
Whoops! Sorry! That was three wasn't it?
They'll KEEP pointing to archaic monstrosities like TMI and Chernobyl and go "BUT WHAT IF IT HAPPENS AGAIN!" until the end of time.
Yeah, and what if it started suddenly raining knives from the sky! Think of the children!
You simply CANNOT convince these people that it's safe and you cannot decouple "nuclear" from
Nuclear NEEDS to be done right (Score:4, Insightful)
We NEED to build the latest designs of reactors out of Europe and Asia and not the 1950s style Pressurized Water Reactors.
We NEED to get past the fear of nuclear proliferation and allow spent nuclear fuel to be reprocessed
If both of these things are done, it solves a lot of the current problems with nuclear power.
Newer reactor designs (pebble bed etc) are a lot safer.
Breeder Reactors and Reprocessing help solve the nuclear waste problem by taking all the waste currently sitting in cooling ponds and storage sites around the US and extract more energy from it. The result after waste has been reprocessed and run again and again and there is no more reprocessing that can be done to it is (IIRC) easier to store and takes less time to become totally inert than the current waste comming from existing reactors.
New reactor designs and other modern technology can use nuclear fuel (not just Uranium) that PWRs cannot.
Re:No, no, no (Score:5, Insightful)
You say that 'regulations could decrease this probability (of another accident) by orders of magnitude(...)'. Regulations?! Like SEC regulators that caught Madoff before he could do any real damage with his fraudulent operation? Oh, wait...
People don't create the fail-safe reactor by following guidelines and rules written by politicians who know shit about nuclear physics. They do it because the incentive of being the safest and most marketable reactor will make them a truckload of money!
The only thing regulation does is remove a characteristic of a product from the sphere of market competition and turn it into a standard throughout the industry.
I guess the corporations must like it, its one less thing to be concerned about, but for the rest of us? I don't know. If that's well thought of, great, no harm done, if not, tough luck people, we all blow up at the same time. Did we forget the old adage of 'having all eggs in one basket'?
I don't know where comes this blind faith in 'regulation'. Does _God_ write them?
Re:No, no, no (Score:4, Informative)
chernobyl was a second generation reactor
It was in fact a -1 generation reactor. Really. It didn't have even no brainier safety built in and no containment vessel. It had a negative void coefficient no documentation almost no training for the staff. Finally they did the evils of evils, they tried to restart a pile from a shutdown in under 24 hours. Due to Xe poisoning this is a really really bad idea.
Chernobyl is not an example of how unsafe nuclear is. Its a example of how unsafe we can build stuff to save a buck.
Re: (Score:3, Insightful)
Wind is abundant all over the place. Areas where solar may be restricted due to space (such as densely packed cities with tons of skyscrapers) are the perfect locations for wind power.
It's a well known fact that city streets act like wind tunnels. It may take a shift in construction architecture, to position wind turbines in the right spots(between buildings, up high, where the wind likes to go), but it is doable, and it'd reduce the burden on the power grid a bit.
I'm sure someone will come and say it isn't
Re:It's fusion or bust (Score:4, Interesting)
That's just plain idiotic nonsense.
Solar power can EASILY... TRIVIALLY, provide all the power we could ever want, very inexpensively, covering a tiny amount of land area, and could be in-place very soon. There just hasn't been nearly ANY investment in it, because coal and natural gas continues to provide a quicker return on the investment.
In fact, I suggest everyone look to west. In California, electric utilities are required to produce a large minority of their power from renewable energy, without loopholes. The ramping up to this rule has been over a decade in coming, and all attempts to overturn it have failed. Neither the people nor the politicians are blinking, this time around, unlike CARB with the electric vehicle mandate in the '90s.
California is either going to be getting ~ 10% of their electricity from solar in the next ten years, at grid prices, or the lights across the state will go out, and stay out. The grand experiment is in place, and the stage is set. It's simply time to sink or swim. This will either prove that power companies can make solar power increasingly profitable, at grid rates (once they have no way to get out of it) or else the 7th largest economy in the world is going to stop, for lack of energy.
Re:It's fusion or bust (Score:5, Funny)
I used to wonder if environmentalists were crazy conspiracy theorist whackjobs, but you've gone ahead and removed all of the uncertainty from that question.
Re: (Score:3, Interesting)
You cant, and thats the problem with generation systems where you don't control the minute to minute generating capacity yourself. Wind and solar also cannot handle the increase in peak production required during certain events.
Re: (Score:3, Interesting)
You're forgetting that the oil industries receive MASSIVE subsidies from the government. Not necessarily in outright funds, but in other ways. For example, look at how much we spend on the military to protect the oil company's interests in the Middle East.
When we invade Iraq to "stabilize the region" (code for "keep surrounding countries producing oil"), look at how much it costs. Even without including the Iraq war, look at the cost of keeping the "regular" military bases in the region.
If you add up al
Re: (Score:3, Insightful) [wikipedia.org] [treehugger.com] [windpower.org]
What the? (Score:5, Insightful)
FTA: Since biofuels frequently lead to greater emissions than either diesel or gas,
That's not really true... Using Biodiesel can result in 75% less CO2 emissions, at the exhaust pipe.
Some Biodiesels, eg, based on Coconut oil, are incredibly low on emissions.
People who claim biodiesel releases more CO2 are making an argument industry wide, including the converting of existing land not used for agriculture to produce biofuels.
Which is a little dishonest, because there are other technologies being developed that make use of badly salt-affected land to produce Biofuel. (Algae based production)
These technologies actually improve the situation and make use of land that otherwise cannot be used at all.
GrpA
Re: (Score:3, Informative)
While it may be true that biofuels can [potentially] result in 75% less emissions at the exhaust pipe, it's important to factor in the emissions from the process of producing, harvesting, refining, etc when making a comparison to fossil fuels. Excluding emissions from the product lifecycle when making an argument for biofuels is very misleading.
Devil's advocate (Score:4, Insightful)
Nuclear.... (Score:5, Insightful)
Compared to anything mentioned, the cleanest form of energy is nuclear power, all factors considered. It's the only thing we should be looking at in the long run as a primary source of power for the grid. Wind and solar are great for local uses but not on a large scale. They are incredibly land intensive for a very small output. A nuclear power plant's physical footprint for the power it generates is practically nil.
People just have to stop equating nuclear power with nuclear weapons, and realizing that modern reactors are far, far safer than reactors from half a century ago. Unfortunately, the United States has lost 30 or 40 years of reactor development time compared to other countries.
As usual, radical environmentalists are their own worst enemy. They advocate alternative energy, and then jump up and down when a new solar installation is built on a fictionally endangered habitat or a wind farm causes migratory bird strikes. You can't have it all ways.
You must find a viable replacement for fossil fuels before eliminating them or taxing them to death. Solar and wind alone are not a viable replacement at that scale.
flamebait (Score:5, Informative)
Biofuel is pretty unethical (Score:4, Insightful)
We don't have enough arable land on planet earth to fully convert from oil to biofuel.
Furthermore, it's a physical fuel that must be grown (on land, using fertilizers, pesticides and farm machinery), processed (expending energy) and then transported (expending energy).
Biofuel is only cheap because of gullible (or corrupt) politicians.
Re: (Score:3, Insightful)
We don't have enough arable land on planet earth to fully convert from oil to biofuel.
Who said anything about fully converting from oil to bio? Shell just wants to concentrate their investments on biofuel.
We all know it's going to take a portfolio of energy sources to get away from oil and coal and we're going to eventually need some sort of replacement fuels for all of those legacy motor vehicles that will be on the road. And you just know that folks will bitch about oil based fuel disappearing off of the market over night.
Some of you need to get over it (Score:5, Interesting)
Likewise, there are MANY other companies doing hydro and wind. Their pulling out will do nothing to harm them. IOW, they will continue.
That brings up the issue of bio-fuels. Far too many of you are thinking in terms of ethanol via corn, sugar cane, etc. That is a red herring (just like hydrogen production is). Skip that garbage and instead focus on converting crap (literally) to gas; ALGAE. There are several companies that are scaling up right now; Solix and Sapphire. Sapphire is doing gas production directly and they currently have it at less than 100/bl oil equivelence. BOTH of these companies need the price of oil to go up to around 80-85/bl and we are approaching that. These companies will likely get money from US and scale quickly. US MAY be a gas exporter within 4 years because of bio-fuels, combined with American cars moving towards electrical powering.
Even now, I look at the dependency that EU has on Russia for Natural Gas, and how Russia has used it. Shell can help break that. Ppl just need to think big and long term.
With that said, I am amazed that Shell, is walking away from things like hydro, and even wind. Foolish on their part. BUT, it still works out.
CSR (Score:5, Insightful)
Corporate Social Responsibility is another one of those dishonest and fraudulent business fads, flaunting secondary goal that often contradict with the primary goal of making money. When push comes to shove, guess which one would prevail. Shell is an oil company, set up to make money in oil business. Criticizing it for not being "socially responsible" (however you define it) is like berating a snake for not acting like a cow.
You want renewable energy, set up monetary incentive for it, and be prepared to pay for it.
Terrible PR investment (Score:4, Insightful)
If they hadn't gotten into renewable energy, sure there would have been some good PR lost, but take a look at the backlash they're going to get now pulling out of it. The mistake was to get in if they had no staying power.
Bah (Score:3, Insightful)
Bah, humbug.
Does this mean we can PLEASE break up/ditch/ignore the Corn Cartel... sorry, lobbying group... which is probably the single biggest reason that biofuel is expensive and inefficient and such a bad idea?
Although I'm unhappy to see Shells move, I can't blame them... they aren't really a R&D outfit, and other startups are taking over the role of expanding wind/hydro/solar and making it profitable. Now, if they would just dump all that money into deciding that algae (or, gasp, hemp!) is a much more efficient biofuel, and help get rid of Big Corn, then everyone could win...
This leaves them alone (Score:4, Insightful)
With BP, Arco and other companies at least acknowledging in TV ads that the current 100% reliance on fossil fuels is unsustainable and other solutions, along with simply using less, are a must. Shell is an awfully wealthy company and investing 1% of the money they spend on locating new oil sources would finance an awful lot of school/university projects to come up with financially viable forms of alternative energy. This investment would have more than paid for itself just on PR value.
I have never been particularly loyal to any brand of gas, but I think I will start using the BP station 3 blocks down the road that I drive to get home anyway rather than Shell which is just at the highway exit.
I understand this. (Score:3, Interesting)
Wind and solar are a load of shit. They require huge upfront costs, have low reliability, and are hard to transport. Bio fuels, esp. cellulose, TDP, and algaculture are efficient, require low or lower upfront cost and can use existing infrastructure owned by the company.
PGE, Marlborough New Zeland, and some companies in Texas are working with algae. What is algae but the product of billions of years of technical development to be the most efficient solar power device on the planet. It is self replicating and can turn our shit into oil. It can also be used for carbon sequestration (if you burn the oil on site you can vent the exhust through the growing algea to speed up production and capture CO2.) Algae in a best case scenario can create 20,000 gallons of bio fuel per acre of land vs. 18 gallon per acre by corn. It doesn't use up the soil resources, it doesn't need chemical fertilizers created with fossil fuels, and it can per pumped around in pipelines that we already own. When combined with TDP you don't even need to worry about having the most efficient producer of oil or getting contaminated with other strains or bacteria. You can just run the system on whatever green goo grows and then render it down into shorter carbon chains. If another better strain that is more efficient comes along later just inoculate with that one. Don't fucking wait for perfection, just get going.
Thinking you can produce a cost efficient solar system that completes with a primary biological producer shows a painful level of hubris. Want nano-tech power? Wow mother nature already does that.
Clean Coal is rubbish (Score:3, Informative)
They can no longer afford faking not to be evil (Score:3, Insightful)
Geothermal is where we are headed (Score:5, Interesting)
There is more free, clean energy in hot rocks 3-5km below the surface than all coal, oil and nuclear fuel combined. It cost nothing to extract other than the initial capital investment, and produces no harmful by-products other than the electricity that you an I take for granted in this modern age.
A bit more research money toward the economic construction of geothermal plants would see us free of fossil and nuclear fuel for the foreseeable future, and that is many, many generations of our species.
Buy the start-ups (Score:3, Insightful)
I wouldn't be suprised if Shell (or other oil companies) would opt to do this. They gather the money now so they can buy those renewable-energy start-up companies AFTER they've proven SUCCESSFUL (i.e. let the weaklings die, then invite the survival-tried to join the gang).
religion (Score:4, Insightful)
Its simple: eco-friendly is the new god to many. They see it as heresy to even suggest 'green' fuels aren't green, or aren't a better-than-break-even venture. Like most religious zealots, facts or reality mean nothing if those facts interfere with their faith or first beliefs. Simply put, logic be damned. (This is why we've got 'green terrorists' burning down SUV dealerships.)
Oh, also, it's plainly obvious why Shell is doing what they're doing. Large companies are not well suited for persuing emerging trends, or for that matter, quick-and-dirty R&D. This is particularly true during a recession/depression, when they've got to be careful to not be capsized utterly. On the flip side of things, this is why small R&D, and 'start ups' in general, tend to flourish during hard economic times (as Apple, MS, etc. did during the late-70s/early-80s): the big dogs are slow to maneuver due to a tightening belt, and are more risk/challenge averse.
If history can be any indication, some small start-ups will invent/discover the "next big thing" in terms of 'renewable' energy.
Oil versus Electricity Infrastructure (Score:4, Interesting)
Seriously, they are an oil company in the business of producing and refining crude oil, for a profit. That's what their entire infrastructure is built around. Thousands of miles of pipe, thousands of service stations, thousands of by-products and oil-derivatives, sea and land tanker fleets, claims to reserves, geological surveys, exploration, oil derricks, off-shore platforms, thousands of scientists, geeks, tradesmen, and explorers, and so on. None of which correlate well to Wind, Solar, or Hydro. Yes, you can use oil products to generate electricity, but Shell wants to deliver the fuel, not run the power plant.
Now that the price of crude oil has settled back to where the market dictates, instead of speculators, Shell is making far less money (along with every company/country in that sector). This isn't much more than a belt tightening and cutting projects that are not contributing to the core business.
Again, they're an oil company trying to profit. The world doesn't run on good intentions, well wishes, and fairy dust. It does run on money and oil though.
I think the other technologies show lots of promise, especially solar, but let someone who specializes in it do it. I am a realist and understand that its going to take a combination of everything to get us to whatever is next.
Patent troll? (Score:4, Insightful)
The only thing that concerns me is if they will use patents collected through their body of research into solar, wind and hydro to block technology developments and deployments creating the same sort of patent mess that is interfering with innovation in the information technology industry.
How to shove 1000 train cars of carbon under a rug (Score:5, Informative)
At Least Shell Is Honest About It (Score:5, Informative)
I worked for BP's orphan photo-voltaics lab in Toano, Virginia long enough for us to be featured in their big "Beyond Petroleum" advertising blitz...and then poof! they pulled the plug. Although we were doing first-rate science and pilot production of amorphous silicon PV cells, we were left with the impression that we were merely a "green" marketing asset left over from the Amoco merger.
We supplied the green paint, then they threw away the brush. So goes the oil business.
Re:Company motto is "Make sure to be evil" (Score:5, Funny)
Just because they're being shellfish doesn't mean you have to be crabby.
:-)
Re:Company motto is "Make sure to be evil" (Score:5, Funny)
Re:Company motto is "Make sure to be evil" (Score:4, Funny)
Re: (Score:3, Insightful)
Let's strap all oil company executives to bicycles instead, it would be a good learning experience for somebody that's never done any real work before~
Re:Neither. They're responsible (Score:5, Insightful)
Now, I'm down with the hippie hate, but I guess moderators really do like sucking corporate cock.
Re:Neither. They're responsible (Score:5, Insightful)
See, troll. Ad hominem and emotive attacks with little or no factual content.
If the evil oil companies are the ones raping the American people, I'm sure glad no American ever bought any oil related products, or voted for some kind of anti-environment President, otherwise they might be considered partly responsible themselves...oh, wait.
The chemical/energy industries are full of scientists, chemists and engineers. There is more of a green attitude in Shell than there is in Parliament/Congress/any government I can think of.
Re:Neither. They're responsible (Score:5, Insightful)
I'm not defending that philosophy at all. I don't know where you got that from.
You're defending the head-in-the-sand philosophy, where people blame 'big oil' because it's easier than taking personal responsibility for the impact one's actions have on the environment.
Oil companies don't destroy the environment and pump oil for shits and giggles, they do it because people are paying them hand-over-fist to do it. People are also willing to forgo legislation to protect the environment to save themselves a few bucks, and then bitch about how the environment is being wrecked.
Yeah, it sucks that Big Oil is ruining the planet man, I wish I could do something about it. What car? This car? No, I need that to drive to my air-conditioned gym.
Re:Neither. They're responsible (Score:4, Interesting)
The other consideration here is that it's not the oil executives job to weigh energy cost and the damage to the environment; that's a moral choice that has to be made by society as a whole, via government. Do you really want oil companies to start taking moral stands? What if an oil company executive decides that homosexuality is a sin, and stops selling petrol to gays? Is that really the kind of world you want to live in?
Re:Neither. They're responsible (Score:4, Interesting)
Don't get me wrong I'm not a crackpot who thinks you can power the world with solar/wind, but I do think oil companies need a bit of government coercion to invest in research.
Re: (Score:3, Interesting)
if they invest in solar/wind and managed to improve efficiency enough to reduce demand for oil then they lose money
Before someone comments that they'd be selling panels/turbines instead of oil; remember oil is a commodity, panels/turbines are a technology. They would much rather deal with selling energy rather than selling energy generators.
Re: (Score:3, Informative)
According to TFA, Shell have been investing in production facilities (wind farms), in that case they'd be selling energy, not technology.
I seem to remember they used to be one of the biggest investors in PV plants, for which your comment would be true.
Only if you ignore the rest of the world (Score:5, Interesting)
The problem here is that there is no profit in the alternative energy business, at least not on the scale Shell operates on. One day that will change, but there is still too much oil in the world for that to happen yet.
Another issue at play is the tragedy of the commons [wikipedia.org]. The free market model relies on every transaction reflecting the true value of the good changing hands. Thats the idea behind a subsidy; one party is selling a good or service to another party, but the public as a whole also benefits from the service, so the public helps pay for it.
Thats also the idea behind the failed-as-implemented idea of carbon credits. When I buy a gallon of gasoline and burn it, I just paid a company to pump the oil out of the ground, refine it, ship it to me, etc. I even paid taxes for the roads I drive on. But I went and blew all those toxic fumes into the atmosphere, a public resource, without paying for that resource.
The only viable solution to this is to impose a tax on every gallon of gasoline equivalent to the cost of removing a gasoline-gallon's worth of exhaust from the atmosphere. By forcing consumers to pay the true cost of gasoline we will allow the free market system to eventually correct the situation and make renewable energy a viable business model that much sooner. Of course some subsidies won't hurt either, but you can't just subsidize "good" without penalizing "bad".
Re:Neither. They're responsible (Score:5, Insightful)
Stupidest idea ever. Funny. But not insightful.
Why do you think this? Large companies are conservative and short-sighted. Even "long term" planning is at most 10-15 years. The markets are even more short-sighted and especially stupid. "Shareholders" comprise two groups: long-term investors (e.g., 401k's) that want slow, consistent growth. And then there are the short-term traders. They are either idiots or the scum of the earth. Nobody here is willing to take on a good risk on the 20-30 year horizon.
You shouldn't have such blind faith in the free market. It is darn good at solving short-term problems. But, boom-bust cycles are a counterexample to long-term efficacy of "market value."
Re: (Score:3, Informative)
If those alternative energy sources were even remotely feasible you can be sure they would be all over them.
Why? Because they are in a rush to make their existing oil lines, distribution networks, and stations obsolete, and want to shake up the system that is making them money? Not to say they have no interest, but they'd be all over them ONLY if they thought they could make even more money doing so, which they might not.
Re:Neither. They're responsible (Score:5, Insightful)
Oh yeah and another thing. Oil companies are not 'energy companies' they are 'resource extraction companies' there's a difference.
This relates to an argument about making furnaces better. The furnace company has very little incentive to make a more efficient furnace because they do not have to pay for the consumables and they make a profit off of parts and service. One idea to make HVAC more efficient is to make vertical monopolies within the industry that provide the server of heating or cooling. If the manufacturer has to pay capital costs and variable reoccurring costs then they will make a machine that lasts forever and uses as little resources per unit of heating or cooling as possible. This is why GM killed the EV because they want you to consume parts and service for the (short) life of the car. If GM gave you the service of having a car and had to pay for gas, parts and service you would have 100mpg cars in 10 years that would last a million miles without service. Don't think a million mile per engine car is possible? Look at the Volvo PS-1800, 2 million miles on single engine made in the 1960s.
Oil companies have generated more super wealthy people on this planet than any other human activity; don't underestimate people's ability to do evil when it comes to trillions of dollars.
Re:Neither. They're responsible (Score:4, Interesting)
That's a bit like saying bottled drinking-water companies would be all-over home water delivery and filtration, if it were remotely feasible...
Even if there are signs that the oil industry is slowly dying, an entrenched field, where you've got no competition is MUCH more profitable than jumping into new markets which ANYONE can compete in on an equal footing.
Re: (Score:3, Insightful)
"Alternative" energy sources are feasible, but they just don't make as much money as oil. In the long run "alternative" energy sources (like wind for example) are much more economically feasible (to ordinary citizens at least) because they don't cause global warming, smog, lung cancer, asthma, etc.
So you need to get your government to legislate for these externalities, because at the moment these have no effects on the economics at all. Shell is inherently a long-run enterprise, you can't just pull a chemical plant out of your backside and start making money. Shell are looking at the long-run and saying that governments will not have the courage to make difficult decisions and so they will scramble towards biofuels as an eco-sop and a way of subsidising farmers.
See here [shell.com], these have been published for
Re:Two contradictory theories... (Score:5, Insightful)
Exactly. Consider their Energy Scenarios [shell.com] study. Essentially, after this study, they asked governments to take the necessary decisions. If you look at what they're doing, they clearly believe that 'scramble' is the scenario we face, and are preparing the company for it.
Shell are a far-sighted company. As with all chemical engineering companies, they need to plan now to build in 5 years, and their plants need to operate at a profit for 20-odd years. The point I'm making is that over time they've become very good at predicting the future.
Re: Firehose:Shell ditches wind, solar and hydro (Score:5, Informative)
With over 50 foreign cars already on sale here, the Japanese auto industry isn't likely to carve out a big slice of the U.S. market.
- Business Week, 1958
Whatever happens, the U.S. Navy is not going to be caught napping.
- Frank Knox, U.S. Secretary of the Navy, on December 4, 1941
Stocks have reached what looks like a permanently high plateau.
- Irving Fisher, Professor of Economics, Yale University, October 16, 1929.
Re: (Score:3, Interesting)
While I agree that subsidies are bad, I don't understand how you then proceed to say that the 80 billion subsidies for alternative energies are 'good'.
How can stealing MORE resources from the US economy be better than simply ending all subsidies to whatever technology, ceasing government intervention in the energy market, actually using property rights laws to allow for the pollution externals to be correctly priced and internalized, and let the market, i.e. we the people, sort out which work better.
I s
Re:quick to savage the company... (Score:5, Funny)
Agreed. Sun Micro is a perfect example. IMO, Sun is the best workstation provider in history, a truly outstanding company. It's not Sun's fault that workstations are no longer in demand. Most people say Sun should have had the foresight to switch to a new business. I say bunk. A company that owns the #1 spot in their market should simply fade with it, and let a new generation of companies exploit new markets. As we approach peak oil, Shell, Exxon, and their competitors should continue to compete in oil even as their revenues fade. Making the jump to alternative energies makes little sense for them.
Re:quick to savage the company... (Score:5, Interesting)
You're modded as funny, but I'm not sure if that was your intent or not.
Companies evolve and survive. Nokia has been around since the 1800's [nokia.com], long before anyone ever heard of a cell phone.
Re:quick to savage the company... (Score:5, Funny)
Their early reception sucked.
functioning markets (Score:4, Insightful)
"If we had functioning markets that took all costs into account and didn't allow externalization, we'd never have developed a petroleum based economy."
Please. You make it sound like the first guy to develop an gasoline-powered automobile back in the turn of the 19th century actually knew all of those costs and externalizations and their cumulative effects. He didn't. He just wanted to get from point A to point B without stepping in horse manure.
They made their decisions based on the knowledge and technology and resources available to them at the time. We, on the other hand, have more knowledge and technology and resources available to us than they did.
As such, we can now do better. | https://news.slashdot.org/story/09/03/19/0319248/shell-ditches-wind-solar-and-hydro?sdsrc=next | CC-MAIN-2016-36 | refinedweb | 9,976 | 62.27 |
Web applications are developed using different programming languages for various components. Effecting changes to the database applications within the app is a cumbersome process and is time consuming. Object relational mapping is a lazy person’s way out, making it simple to migrate data.
ORM or object relational mapping is a technique or a toolkit to access the database from programming languages or frameworks. Though ORM has been used in the industry for a long time, many people are not too aware about it. This article throws light on this topic, with budding developers as its target audience.
The normal scenario of a project
Let’s look at a Web application. The front-end/Web pages might be programmed in HTML/ jQuery and the server side may be in any scripting language like PHP or a framework like Django. The database may be Oracle or SQL Server.
The connection to the database is coded (called the connection string) in the scripting language, specific to the database, by giving the following parameters:
dbname, user, password, port number, etc.
Inside the application, we might have written several SQL queries that are specific to the vendor database.
Disadvantages
Let’s look at a scenario in which, for certain business purposes, the client wants to change to some open source database like MySQL. It is a difficult/ cumbersome activity for the developers involved to change all the DB queries to MySQL, including the connection string. This would mainly affect the time required to do the development/changes and the testing – both of which might result in a lower profit margin.
How ORM fits into the picture
Tables in the database schema are defined as classes
in Django, the widely used and the most popular
framework of Python.
An example of an employee class/table is:
from django.db import models class Employee(models. Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) age = models.IntegerField()
After the classes are defined, we need to create the migration file.
Migration
Migration is to a database what GIT or SVN is to the code base. It keeps track of changes in the schema by creating files for each one. For each change, we need to create a migration file
and then execute this file to replicate the specified change to the underlying database. The commands for these operations vary based on the ORM we use.
Why ORM is needed
While developing any application, by using ORM, we get the following advantages.
1. Productivity
- Eliminates lots of repetitive code
- Database schema is generated automatically
2. Maintainability
- Fewer lines of code – easier to understand
- Easier to manage changes in the table/class
3. Performance
- Lazy loading – associations are fetched when needed
- Caching
4. Vendor-independent
- The underlying database is abstracted away
- In the code below, ORM supports multiple databases. A query in ORM looks like what follows:
Employee.objects.filter(first_name='xxxx')
…which is the same as what’s shown below:
select * from employee where first_name='xxxx'
In the above fashion, any SQL query can be written
in ORM. There is no need for the developer to write complex SQL queries. An ORM query is converted into an equivalent vendor-specific database query for execution. This is a lazy way of doing things, i.e unless we try to retrieve some properties from the query result set, the conversion process or the query execution won’t happen.
Django has its own built-in ORM. We can also use SQLalchemy, which is an open source ORM toolkit for the Python frameworks. Apart from these two, there are some other open source ORMs such as SQLObject, Propel, Redbean, and so on.
To learn more about the ORM in Django, go to. | https://www.opensourceforu.com/2019/07/simplify-database-migration-by-using-object-relational-mapping/ | CC-MAIN-2021-10 | refinedweb | 622 | 64.81 |
Dominique Lederer wrote: > Darryl Cousins schrieb: >> Hi Tim, >> >> On Sat, 2006-10-21 at 12:18 +0200, Tim Terlegård wrote: >>> Is there a way to add content without having @@+ in the URL? For >>> instance I'd like the url for adding events to be /addEvent. >>> >>> I get security problems when not having @@+ in the URL. I have this view: >>> >>> <browser:page >>>>>>>>>>> /> >>> >>> When I hit the submit button in this add form I get an error: >>> ForbiddenAttribute: ('add', <zope.app.folder.folder.Folder object at >>> 0xb6e65d2c>) >> Forbidden here in the sense that Folder does not have an 'add' >> attribute. >> >>> I realize IWriteContainer might not be the right interface, it doesn't >>> have any add method. >>> >>> Should I have for="zope.app.container.interfaces.IAdding" instead and >>> somehow add an adapter from IFolder to IAdding or how would I do this? >>> >>> Tim >> As you point out formlib.BaseAddForm calls the add method of the >> context: >> >> _finished_add = False >> >> def add(self, object): >> ob = self.context.add(object) >> self._finished_add = True >> return ob >> >> I (also a novice) always use formlib for adding. But I use my own base >> adding sub-class of BaseAddForm which has this add method: >> >> def add(self, obj): >> try: >> ob = self.container.add(obj) >> except: >> self.container.__setitem__(obj.__name__, obj) >> ob = self.container[obj.__name__] >> self._finished_add = True >> return ob >> >> I almost always use a NameChooser to choose the name for the object. So >> I can trust using __name__ as the dict key. >> >> I use self.container here that usually resolves to self.context but on >> some occassions the context is not the container I want to be adding to. >> >> Hopes this helps. >> >> Darryl > > yes, thanks, it helped me > > but what are we doing wrong here, that the base methods wont work? > > why should my container know about the add method?
Advertising
The context for AddForm normally isn't the container, it's the IAdding namespace adapter. This object implements the add method. The IAdding object interacts with the container (and name chooser). All this presumes you've registered your add form page accordingly: e.g. <addMenuItem view="Addform.html" ... <page name=Addform.html for="zope.app.container.interfaces.IAdding" .. When wiring in a form directly against an IContainer I guess it's reasonable to simply presume the context is the container. In the case above you could make the AddForm work both ways somewhat more explicit, e.g. if IAdding.providedBy(context): self.context.add(ob) # the context IAdding does the name handling. else: #assert IWriteContainer.providedBy(ob) name = .. self.context[name] = ob HTH -Tom _______________________________________________ Zope3-users mailing list Zope3-users@zope.org | https://www.mail-archive.com/zope3-users@zope.org/msg04578.html | CC-MAIN-2017-30 | refinedweb | 436 | 67.76 |
Ole. :-( So it seems you have to use `re-search-forward' with BOUND parameter in a loop and count the number of matches yourself. By the way: "&" as a regexp is too lax. It also matches tho ampersand in "bla \& bla" which is not a column separator. The regexp "[^\\]&" should do the trick. > Here's an updated patch. Using the :set property of defcustom is a good idea, and it also saves the tabular-like environments variable. One nitpick: +(defvar LaTeX-tabularlike--end nil + "A regular expression that matches the ending of environments +that will be aligned with `LaTeX-indent-tabular'. + +Do not set this variable. This variable is auto-set +by customizing `LaTeX-indent-environment-list'.") The first sentence of a docstring should fit into one line. I'd go with "A regexp matching tabular-like environment ends. Those will be aligned with `LaTeX-indent-tabular'. ..." Also, I'd put a hyphen between "tabular" and "like" in the variable name. And why the double-hyphen? To show that it's kind of private and not intended to be modifier by users? In that case, I think the convention is to use the double-hyphen immediately after the "namespace", that is, `LaTeX--tabular-like-end'. We don't follow that convention in AUCTeX currently (because AUCTeX is much older than that convention), but I wouldn't object to start using it. > It uses `cl-reduce', which is probably not what you want. You name it. ;-) > What's the compatible replacement for `cl-reduce'? A while loop pushing into a local variable, or `mapc' where the lambda pushes into a local variable. Bye, Tassilo | https://lists.gnu.org/archive/html/auctex/2013-10/msg00010.html | CC-MAIN-2020-34 | refinedweb | 273 | 59.6 |
Sources Bugzilla – Bug 11403
Failed to set controlling terminal
Last modified: 2010-08-15 20:02:04 UTC
On OpenSolaris b111, gdb 7.0.1 and 7.0
I try to debug a program with different tty:
gdb -tty /dev/pts/6 a.out
when I start the program I get:
warning: GDB: Failed to set controlling terminal: Inappropriate ioctl for device
in the output.
With gdb 6.8 and prior I have not seen this.
This issue started with:
[RFA] Fix GDB's handling of the inferior controlling terminal.
(as reported by Alan Matsuoka)
The changed fixed other problems described there.
Either you should ignore the warning as it has the same functionality as gdb-6.x
before the change above. For example signals do not work in that TTY, though.
If you want to benefit from the fully dedicated TTY to the inferior process you
should run first the helper pasted below.
(One can discuss whether to call TIOCSCTTY with 0 (current) or 1. IMO the
current value is right, 1 would not make it much easier and it would just
require root privileges plus make it whole less clear.)
I would suggest for GDB to make some notice to such a helper in the warning.
Thanks for the bugreport, is it OK this way?
------------------------------------------------------------------------------
/* tty;exec disowntty */
#include <sys/ioctl.h>
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <signal.h>
static void
end (const char *msg)
{
perror (msg);
for (;;)
pause ();
}
int
main (void)
{
void (*orig) (int signo);
setbuf (stdout, NULL);
orig = signal (SIGHUP, SIG_IGN);
if (orig != SIG_DFL)
end ("signal (SIGHUP)");
/* Verify we are the sole owner of the tty. */
if (ioctl (STDIN_FILENO, TIOCSCTTY, 0) != 0)
end ("TIOCSCTTY");
/* Disown the tty. */
if (ioctl (STDIN_FILENO, TIOCNOTTY) != 0)
end ("TIOCNOTTY");
end ("OK, disowned");
return 1;
} | http://sourceware.org/bugzilla/show_bug.cgi?id=11403 | CC-MAIN-2013-20 | refinedweb | 301 | 69.79 |
The list in SelectCollectionStep.java does not specify in which community each collection belongs to. So for collections named "Thesis" that exist in multiple departments (Communities) the user can't choose which is the correct one.
One solution to this problem is to change the way the list is built in SelectCollectionStep.java
(package org.dspace.app.xmlui.aspect.submission.submit) by adding a loop inside the loop that gets the names / handles for each collection in order to get the names of the parent communities
so the original loop:
for (Collection collection : collections) { String name = collection.getMetadata("name"); if (name.length() > 50) name = name.substring(0, 47) + "..."; select.addOption(collection.getHandle(),name); }
can be changed to:
for (Collection collection : collections) { String name = ""; String temp = ""; String temp2 = ""; Community[] community = collection.getCommunities(); //get the names of the communities for this collection for (Community com : community) { temp = com.getMetadata("name"); if (temp.length() > 15) temp = temp.substring(0, 12) + "..."; //Trimming the name of the community name = temp +" / "+ name; //Adding the strings of the community names } temp2 = collection.getMetadata("name"); if (temp2.length() > 18) temp2 = temp2.substring(0, 15) + "..."; //Trimming the name of the collection name = name + temp2; select.addOption(collection.getHandle(),name); }
The variables ("temp","temp2") can be changed, string variable "temp" can be used instead "temp2", and the substring methods can be removed if the names of the communities are not very big. Some steps in the loop can be skipped/merged together.
This change has been tested in 1.5.2
The same can be applied in Profile page (EditProfile.java / package org.dspace.app.xmlui.aspect.eperson) with the addition of
import org.dspace.content.Community
In this way the users can choose the collection they want to subscribe to for mail alerts | https://wiki.duraspace.org/pages/viewpage.action?pageId=19006093 | CC-MAIN-2018-13 | refinedweb | 294 | 52.05 |
Generics in java were introduced as one of features in JDK 5. Personally, I find the angular brackets “<>” used in generics very fascinating and it always forces me to have another thought where I use it OR see it written in somebody else’s code..
Table of content 1) Why Generics? 2) How Generics works in Java 3) Types of Generics? i) Generic Type Class or Interface ii) Generic Type Method or Constructor 4) Generic Type Arrays 5) Generics with Wildcards i) Unbounded Wildcards ii) Bounded Wildcards a) Upper Bounded Wildcards b) Lower Bounded Wildcards 6) What is not allowed to do with Generics?
“Java Generics” is a technical term denoting a set of language features related to the definition and use of generic types and methods . In java, Generic types or methods differ from regular types and methods in that they have type parameters.
“Java Generics are a language feature that allows for definition and use of generic types and methods.”
Generic types are instantiated to form parameterized types by providing actual type arguments that replace the formal type parameters. A class like
LinkedList<E> is a generic type, that has a type parameter E . Instantiations, such as
LinkedList<Integer> or a
LinkedList<String>, are called parameterized types, and String and Integer are the respective actual type arguments.
1) Why Generics?
If you closely look at java collection framework classes then you will observe that most classes take parameter/argument of type
Object and return values from methods as
Object. Now, in this form, they can take any java type as argument and return the same. They are essentially heterogeneous i.e. not of a particular similar type.
Programmers like us often wanted to specify that a collection contains elements only of a certain type e.g.
Integer or
String or
Employee. In the original collection framework, having homogeneous collections was not possible without adding extra checks before adding some checks in code. Generics were introduced to remove this limitation to be very specific. They add this type checking of parameters in your code at compile-time, automatically. This saves us writing a lot of unnecessary code which actually does not add any value in run-time if written correctly.
“In layman,s term, generics force type safety in java language.”
Without this type of safety, your code could have infected by various bugs that get revealed only in runtime. Using generics, makes them highlighted in compile time itself and make you code robust even before you get the bytecode of your java source code files.
“Generics add stability to your code by making more of your bugs detectable at compile time.”
So now we have a fair idea of why generics are present in java in the first place. The next step is to get some knowledge about how they work in java. What actually happens when you use generics in your source code.
2) How Generics works in Java
In the heart of generics is “type safety“. What exactly is type safety? It’s just a guarantee by compiler that if correct Types are used in correct places then there should not be any
ClassCastException in runtime. A usecase can be list of
Integer i.e.
List<Integer>. If you declare a list in java like
List<Integer>, then java guarantees that it will detect and report you any attempt to insert any non-integer type into above list.
Another important term in java generics is “type erasure“. It essentially means that all the extra information added using generics into source code will be removed from bytecode generated from it. Inside bytecode, it will be old java syntax which you will get if you don’t use generics at all. This necessarily helps in generating and executing code written prior to java 5 when generics were not added in language.
Let’s understand with an example.
List<Integer> list = new ArrayList<Integer>(); list.add(1000); //works fine list.add("lokesh"); //compile time error;
When you write above code and compile it, you will get below error: “The method add(Integer) in the type
List<Integer> is not applicable for the arguments (String)“. The compiler warned you. This exactly is generics sole purpose i.e. Type Safety.
The second part is getting the byte code after removing the second line from the above example. If you compare the bytecode of the above example with/without generics, then there will not be any different. Clearly compiler removed all generics information. So, the above code is very much similar to the below code without generics.
List list = new ArrayList(); list.add(1000);
“Precisely, Generics in Java is nothing but a syntactic sugar to your code for Type Safety and all such type information is erased by Type Erasure feature by the compiler.”
3) Types of Generics?
Now we have some understanding of what generics are all about. Now start exploring other important concepts revolving around generics. I will start by identifying the various ways, generics can be applied into sourcecode.
Generic Type Class or Interface
A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. Let’s understand with an example.
DemoClass is a simple java class, which has one property
t (can be more than one also); and type of property is Object.
class DemoClass { private Object t; public void set(Object t) { this.t = t; } public Object get() { return t; } }
Here we want that once initialized the class with a certain type, class should be used with that particular type only. e.g. If we want one instance of class to hold value t of type ‘
String‘, then programmer should set and get the only
String type. Since we have declared property type to
Object, there is no way to enforce this restriction. A programmer can set any object, and can expect any return value type from get method since all java types are subtypes of
Object class.
To enforce this type restriction, we can use generics as below:
class DemoClass<T> { //T stands for "Type" private T t; public void set(T t) { this.t = t; } public T get() { return t; } }
Now we can be assured that class will not be misused with wrong types. A sample usage of
DemoClass will look like this:
DemoClass<String> instance = new DemoClass<String>(); instance.set("lokesh"); //Correct usage instance.set(1); //This will raise compile time error
The above analogy is true for the interfaces as well. Let’s quickly look at an example to understand, how generics type information can be used in interfaces in java.
//Generic interface definition interface DemoInterface<T1, T2> { T2 doSomeOperation(T1 t); T1 doReverseOperation(T2 t); } //A class implementing generic interface class DemoClass implements DemoInterface<String, Integer> { public Integer doSomeOperation(String t) { //some code } public String doReverseOperation(Integer t) { //some code } }
I hope, I was enough clear to put some light on generic classes and interfaces. Now it’s time to look at generic methods and constructors.
Generic Type Method or Constructor
Generic methods are much similar to generic classes. They are different only in one aspect that the scope of type information is only inside the method (or constructor). Generic methods are methods that introduce their own type parameters.
Let’s understand this with an example. Below is a code sample of a generic method that can be used to find all occurrences of a type parameter in a list of variables of that type only.
public static <T> int countAllOccurrences(T[] list, T item) { int count = 0; if (item == null) { for ( T listItem : list ) if (listItem == null) count++; } else { for ( T listItem : list ) if (item.equals(listItem)) count++; } return count; }
If you pass a list of
String and another string to search in this method, it will work fine. But if you will try to find an
Number into list of
String, it will give compile-time error.
The same as above can be an example of a generic constructor. Let’s take a separate example for a generic constructor as well.
class Dimension<T> { private T length; private T width; private T height; //Generic constructor public Dimension(T length, T width, T height) { super(); this.length = length; this.width = width; this.height = height; } }
In this example,
Dimension class’s constructor has the type information also. So you can have an instance of dimension with all attributes of a single type only.
4) Generic Type Arrays
Array in any language have same meaning i.e. an array is a collection of similar type of elements. In java, pushing any incompatible type in an array on runtime will throw
ArrayStoreException. It means array preserve their type information in runtime, and generics use type erasure or remove any type of information in runtime. Due to the above conflict, instantiating a generic array in java is not permitted.
public class GenericArray<T> { // this one is fine public T[] notYetInstantiatedArray; // causes compiler error; Cannot create a generic array of T public T[] array = new T[5]; }
In the same line as above generic type classes and methods, we can have generic arrays in java. As we know that an array is a collection of similar type of elements and pushing any incompatible type will throw
ArrayStoreException in runtime; which is not the case with
Collection classes.
Object[] array = new String[10]; array[0] = "lokesh"; array[1] = 10; //This will throw ArrayStoreException
The above mistake is not very hard to make. It can happen anytime. So it’s better to provide the type information to array also so that error is caught at compile time itself.
Another reason why arrays do not support generics is that arrays are covariant, which means that an array of supertype references is a supertype of an array of subtype references. That is,
Object[] is a supertype of
String[] and a string array can be accessed through a reference variable of type
Object[].
Object[] objArr = new String[10]; // fine objArr[0] = new String();
5) Generics with Wildcards
In generic code, the question mark (?), called the wildcard, represents an unknown type. A wildcard parameterized type is an instantiation of a generic type where at least one type argument is a wildcard. Examples of wildcard parameterized types are
Collection<?<,
List<? extends Number<,
Comparator<? super String> and
Pair<String,?>..
Having wild cards at difference places have different meanings as well. e.g.
- Collection> denotes all instantiations of the Collection interface regardless of the type argument.
- List extends Number> denotes all list types where the element type is a subtype of Number.
Comparator<? super String<denotes all instantiations of the Comparator interface for type argument types that are supertypes of String.
A wildcard parameterized type is not a concrete type that could appear in a new expression. It just hints the rule enforced by java generics that which types are valid in any particular scenario where wild cards have been used.
For example, below are valid declarations involving wild cards:
Collection<?> coll = new ArrayList<String>(); //OR List<? extends Number> list = new ArrayList<Long>(); //OR Pair<String,?> pair = new Pair<String,Integer>();
And below are not valid uses of wildcards, and they will give compile-time error.
List<? extends Number> list = new ArrayList<String>(); //String is not subclass of Number; so error //OR Comparator<? super String> cmp = new RuleBasedCollator(new Integer(100)); //Integer is not superclass of String
Wildcards in generics can be unbounded as well as bounded. Let’s identify the difference in various terms.
Unbounded wildcard parameterized type
A generic type where all type arguments are the unbounded wildcard
"?” without any restriction on type variables. e.g.
ArrayList<?> list = new ArrayList<Long>(); //or ArrayList<?> list = new ArrayList<String>(); //or ArrayList<?> list = new ArrayList<Employee>();
Bounded wildcard parameterized type
Bounded wildcards put some restrictions over possible types, you can use to instantiate a parametrized type. This restriction is enforced using keywords “super” and “extends”. To differentiate more clearly, let’s divide them into upper bounded wildcards and lower bounded wildcards.
Upper bounded wildcards
For example, say you want to write a method that works on List<String>, List<Integer>, and List<double> you can achieve this by using an upper bounded wildcard e.g. you would specify List<? extends Number>. Here Integer, Double are subtypes of Number class. In layman’s terms, if you want the generic expression to accept all subclasses of a particular type, you will use upper bound wildcard using “extends” keyword.
public class GenericsExample<T> { public static void main(String[] args) { //List of Integers List<Integer> ints = Arrays.asList(1,2,3,4,5); System.out.println(sum(ints)); //List of Doubles List<Double> doubles = Arrays.asList(1.5d,2d,3d); System.out.println(sum(doubles)); List<String> strings = Arrays.asList("1","2"); //This will give compilation error as :: The method sum(List<? extends Number>) in the //type GenericsExample<T> is not applicable for the arguments (List<String>) System.out.println(sum(strings)); } //Method will accept private static Number sum (List<? extends Number> numbers){ double s = 0.0; for (Number n : numbers) s += n.doubleValue(); return s; } }
Lower bounded wildcards
If you want a generic expression to accept all types which are “super” type of a particular type OR parent class of a particular class then you will use a lower bound wildcard for this purpose, using ‘super’ keyword.
In below given example, I have created three classes i.e.
SuperClass,
ChildClass and
GrandChildClass. There relationship is shown in code below. Now, we have to create a method which somehow get a
GrandChildClass information (e.g. from DB) and create an instance of it. And we want to store this new
GrandChildClass in an already existing list of
GrandChildClasses.
Here problem is that
GrandChildClass is subtype of
ChildClass and
SuperClass as well. So any generic list of SuperClasses and ChildClasses is capable of holding GrandChildClasses as well. Here we must take help of lower bound wildcard using ‘super‘ keyword.
package test.core; import java.util.ArrayList; import java.util.List; public class GenericsExample<T> { public static void main(String[] args) { //List of grand children List<GrandChildClass> grandChildren = new ArrayList<GrandChildClass>(); grandChildren.add(new GrandChildClass()); addGrandChildren(grandChildren); //List of grand childs List<ChildClass> childs = new ArrayList<ChildClass>(); childs.add(new GrandChildClass()); addGrandChildren(childs); //List of grand supers List<SuperClass> supers = new ArrayList<SuperClass>(); supers.add(new GrandChildClass()); addGrandChildren(supers); } public static void addGrandChildren(List<? super GrandChildClass> grandChildren) { grandChildren.add(new GrandChildClass()); System.out.println(grandChildren); } } class SuperClass{ } class ChildClass extends SuperClass{ } class GrandChildClass extends ChildClass{ }
6) What is not allowed to do with Generics?
So far we have learned about a number of things which you can do with generics in java to avoid many
ClassCastException instances in your application. We also saw the usage of wildcards as well. Now it’s time to identify some tasks which are not allowed to do in java generics.
a) You can’t have static field of type
You can not define a static generic parameterized member in your class. Any attempt to do so will generate compile-time error: Cannot make a static reference to the non-static type T.
public class GenericsExample<T> { private static T member; //This is not allowed }
b) You can not create an instance of T
Any attempt to create an instance of T will fail with error: Cannot instantiate the type T.
public class GenericsExample<T> { public GenericsExample(){ new T(); } }
c) Generics are not compatible with primitives in declarations
Yes, it’s true. You can’t declare generic expression like List or Map<String, double>. Definitely you can use the wrapper classes in place of primitives and then use primitives when passing the actual values. These value primitives are accepted by using auto-boxing to convert primitives to respective wrapper classes.
final List<int> ids = new ArrayList<>(); //Not allowed final List<Integer> ids = new ArrayList<>(); //Allowed
d) You can’t create Generic exception class
Sometimes, the programmer might be in need of passing an instance of generic type along with exception being thrown. This is not possible to do in Java.
// causes compiler error public class GenericException<T> extends Exception {}
When you try to create such an exception, you will end up with message like this: The generic class
GenericException may not subclass
java.lang.Throwable.
That’s all for now closing the discussion on java generics this time. I will come up with more interesting facts and features related to generics in the coming posts.
Drop me a comment if something is unclear /OR you have any other questions.
Happy Learning !!
Feedback, Discussion and Comments
Abhyas
in “Generic Type Method or Constructor” you showed how to create a generic method but you didn’t how to call that method.
I am trying this
But it shows an error. Of course.
Yufei
Hey, Lokesh,
Thank you for your explanation of the generic types, but I have a question, which might be silly.
I want to define a class with a generic type. For that generic type, I want it to be a Vector or ArrayList.
For example, I want to define it as following:
This will not compile. What should I do?
Should I simply replace Vector with T, which becomes
and later when I instantiate this class, replace T with the actual Vector, say, Vector ?
Thanks.
adarsh srivastava
you can say like
public class Test{
…
}
shvia shankar
In original collection framework, having homogeneous collections was not possible without adding extra checks before adding some checks in code. Generics were introduced to remove this limitation to be very specific.
i cannot understand this line will you please explain….?
Lokesh Gupta
In below example,
listOneis heterogeneous collection (allows any type) while
listTwois homogeneous collection (only one type).
dipray2015
Great job Lokesh! The best I could see when tried different ones including Oracles.
I had tiny hard time when tried to understand “super” for lower bound. I think all that you had great, but if you create one more child class such as GrandGrandChildClass and then pass that list to the the add method to prove that sub class below GrandChildClass is not allowed.
Satya
This is not a complete GENERICS tutorial. You missed Generic Inheritance (Subtyping)
Wenbin
Sorry but.. do you mean the other article? PECS
Satya
Thank you for the response. “do you mean the other article ?” – No , I am talking about the inhertance in Generic Classes. – Parent child relation in Generics.
saurabh
Hi Lokesh,
I am unable to understand the difference between these two methods. Can you please help me understand.
void print(List obj) {
Iterator l=obj.iterator();
while(l.hasNext()) {
System.out.println(“inside print1 “+l.next());
}
}
void print2(List obj) {
Iterator l=obj.iterator();
while(l.hasNext()) {
System.out.println(“inside print2 “+l.next());
}
}
pramod Singh
both are same, it seems only function name is different .
Abhijit
Hi Lokesh
Great Explanation on Generics concepts. However I have question. Why Generics Type Arrays do not throw ArrayStoreException when we change your code to the below. If we change the type from String to Object then arrays accept heterogeneous types..
pramod Singh
because Object class is the parent class of every class.
Lokesh
“For example, say you want to write a method that works on List<String>, List<Integer>, and List<double> you can achieve this by using an upper bounded wildcard e.g. you would specify List<? extends Number>.”
Correction Indeed, because List<String> isn’t the same thing as (or subtype of) List<? extends Number>.
In fact, The common parent in List<?>.
ref: wildcards
Lokesh
In section 5, This is confusing:
Collection<?<, List<? extends Number<, Comparator and Pair
Problem with html? Maybe you mean:
Collection, List, Comparator and Pair
JavaDev
I have several questions .
1. What is the difference when writing and T as return type
2. Wildecard vs T .
3. When use S,U etc. What is exactly mean secondary type
4. Is it possible to explain more detailed what is not allowed by generics . I mean why it is not allowed
Thanks
Lakshmi N Galla
public static int countAllOccurrences(T[] list, T item) {
………..
return count;
}
countAllOccurrences(new String[]{“1″,”3″,”3″,”6”}, new Integer(2));
This won’t throw any compile error. It just returns count as ‘0’
sundar
why generic exceptipn are not allowed?can u elaborate deeply with examples
Pati Ram Yadav
Comparator cmp = new RuleBasedCollator(new Integer(100)); //String is not superclass of Integer
This is wrong explanation because means something which is super of String (including String itself). So here it should be like: Integer is not superclass of String 🙂
Lokesh Gupta
You are right. Fixed it.
Garima
I think there is one type mistake in point no 4 : Genereic Arrays which is “generics use type erasure or remove any type information in runtime” where as Erasure remove Type information at compile time. Am I correct?
then this reason is not applicable when u said “Due to above conflict, instantiating a generic array in java is not permitted.” Please explain
john doe
that was because Runtime exception type has no generics information . For more detail , look into JLS 8.1.2
Veer
Hi Lokesh,
Good effort. One thing additional which you might want to mention while talking about generics is Joshua Bloch’s PECS ( Producer Extends Consumer Super ).
This reminds when to use ? extends and when to use ? super.
Lokesh Gupta
Yes Veer.. I am planning to write a separate pot for PECS only, it’s just so much detailed and interesting topic.
Mridul Vimal Singh
Thanks Sir, You include all these things about generic
Sudheer
Thanks for the post on Generics. It would be very helpful if you can write a post on WebServices
Lokesh Gupta
I have written lots of post on RESTful WS. If you need in SOAP, then sorry to disappoint you, i have not worked on SOAP till date, so it will take long time.
HIMANSU NAYAK
Hi Lokesh,
What is not allowed to do with Generics?
ArrayList list = new ArrayList() // allowed
ArrayList list = new ArrayList(); // sub-type not allowed
objects creation using wildcard parameterized type is not allowed
ArrayList list = new ArrayList(); // as told by you a generic class instance creation not allowed | https://howtodoinjava.com/java/generics/complete-java-generics-tutorial/ | CC-MAIN-2021-04 | refinedweb | 3,704 | 56.66 |
A detailed single cell model¶
We can expand on the single segment cell example to create a more complex single cell model, and go through the process in more detail.
Note
Concepts covered in this example:
Building a morphology from a
arbor.segment_tree.
Building a morphology from an SWC file.
Writing and visualizing region and locset expressions.
Building a decor.
Discretising the morphology.
Setting and overriding model and cell parameters.
Running a simulation and visualising the results using a
arbor.single_cell_model.
The cell¶
We start by building the cell. This will be a cable cell with complex geometry and dynamics which is constructed from 3 components:
A morphology defining the geometry of the cell.
A label dictionary storing labelled expressions which define regions and locations of interest on the cell.
A decor defining various properties and dynamics on these regions and locations. The decor also includes hints about how the cell is to be modelled under the hood, by splitting it into discrete control volumes (CV).
The morphology¶
We begin by constructing the following morphology:
This can be done by manually building a segment tree:
import arbor from arbor import mpoint from arbor import mnpos # Define the morphology by manually building a segment tree tree = arbor.segment_tree() # Start with segment 0: a cylindrical soma with tag 1 tree.append(mnpos, mpoint(0.0, 0.0, 0.0, 2.0), mpoint( 40.0, 0.0, 0.0, 2.0), tag=1) # Construct the first section of the dendritic tree with tag 3, # comprised of segments 1 and 2, attached to soma segment 0. tree.append(0, mpoint(40.0, 0.0, 0.0, 0.8), mpoint( 80.0, 0.0, 0.0, 0.8), tag=3) tree.append(1, mpoint(80.0, 0.0, 0.0, 0.8), mpoint(120.0, -5.0, 0.0, 0.8), tag=3) # Construct the rest of the dendritic tree: segments 3, 4 and 5. tree.append(2, mpoint(120.0, -5.0, 0.0, 0.8), mpoint(200.0, 40.0, 0.0, 0.4), tag=3) tree.append(3, mpoint(200.0, 40.0, 0.0, 0.4), mpoint(260.0, 60.0, 0.0, 0.2), tag=3) tree.append(2, mpoint(120.0, -5.0, 0.0, 0.5), mpoint(190.0, -30.0, 0.0, 0.5), tag=3) # Construct a special region of the tree made of segments 6, 7, and 8 # differentiated from the rest of the tree using tag 4. tree.append(5, mpoint(190.0, -30.0, 0.0, 0.5), mpoint(240.0, -70.0, 0.0, 0.2), tag=4) tree.append(5, mpoint(190.0, -30.0, 0.0, 0.5), mpoint(230.0, -10.0, 0.0, 0.2), tag=4) tree.append(7, mpoint(230.0, -10.0, 0.0, 0.2), mpoint(360.0, -20.0, 0.0, 0.2), tag=4) # Construct segments 9 and 10 that make up the axon with tag 2. # Segment 9 is at the root, where its proximal end will be connected to the # proximal end of the soma segment. tree.append(mnpos, mpoint( 0.0, 0.0, 0.0, 2.0), mpoint( -70.0, 0.0, 0.0, 0.4), tag=2) tree.append(9, mpoint(-70.0, 0.0, 0.0, 0.4), mpoint(-100.0, 0.0, 0.0, 0.4), tag=2) morph = arbor.morphology(tree);
The same morphology can be represented using an SWC file (interpreted according
to Arbor’s specifications). We can save the following in
single_cell_detailed.swc.
# id, tag, x, y, z, r, parent 1 1 0.0 0.0 0.0 2.0 -1 # seg0 prox / seg9 prox 2 1 40.0 0.0 0.0 2.0 1 # seg0 dist 3 3 40.0 0.0 0.0 0.8 2 # seg1 prox 4 3 80.0 0.0 0.0 0.8 3 # seg1 dist / seg2 prox 5 3 120.0 -5.0 0.0 0.8 4 # seg2 dist / seg3 prox 6 3 200.0 40.0 0.0 0.4 5 # seg3 dist / seg4 prox 7 3 260.0 60.0 0.0 0.2 6 # seg4 dist 8 3 120.0 -5.0 0.0 0.5 5 # seg5 prox 9 3 190.0 -30.0 0.0 0.5 8 # seg5 dist / seg6 prox / seg7 prox 10 4 240.0 -70.0 0.0 0.2 9 # seg6 dist 11 4 230.0 -10.0 0.0 0.2 9 # seg7 dist / seg8 prox 12 4 360.0 -20.0 0.0 0.2 11 # seg8 dist 13 2 -70.0 0.0 0.0 0.4 1 # seg9 dist / seg10 prox 14 2 -100.0 0.0 0.0 0.4 13 # seg10 dist
Note
SWC samples always form a segment with their parent sample. For example, sample 3 and sample 2 form a segment which has length = 0. We use these zero-length segments to represent an abrupt radius change in the morphology, like we see between segment 0 and segment 1 in the above morphology diagram.
More information on SWC loaders can be found here.
The morphology can then be loaded from
single_cell_detailed.swc in the following way:
# (1) Read the morphology from an SWC file. # Read the SWC filename from input # Example from docs: single_cell_detailed.swc if len(sys.argv) < 2: print("No SWC file passed to the program") sys.exit(0) filename = sys.argv[1] morph = arbor.load_swc_arbor(filename)
The label dictionary¶
Next, we can define region and location expressions and give them labels.
The regions and locations are defined using an Arbor-specific DSL, and the labels
can be stored in a
arbor.label_dict.
Note
The expressions in the label dictionary don’t actually refer to any concrete regions or locations of the morphology at this point. They are merely descriptions that can be applied to any morphology, and depending on its geometry, they will generate different regions and locations. However, we will show some figures illustrating the effect of applying these expressions to the above morphology, in order to better visualize the final cell.
More information on region and location expressions is available here.
The SWC file format allows association of
tags with parts of the morphology
and reserves tag values 1-4 for commonly used sections (see here
for the SWC file format). In Arbor, these tags can be added to a
arbor.label_dict using
the
add_swc_tags() method, which will define
You can alternatively define these regions by hand, using
labels = arbor.label_dict({ "soma": "(tag 1)", "axon": "(tag 2)", "dend": "(tag 3)", "apic": "(tag 4)", })
Both ways will generate the following regions when applied to the previously defined morphology:
From left to right: regions “soma”, “axon”, “dend” and “last”¶
We can also define a region that represents the whole cell; and to make things a bit more interesting, a region that includes the parts of the morphology that have a radius greater than 1.5 μm. This is done in the following way:
# Add a label for the parts of the morphology with radius greater than 1.5 μm. "gt_1.5": '(radius-ge (region "all") 1.5)',
This will generate the following regions when applied to the previously defined morphology:
Left: region “all”; right: region “gt_1.5”¶
By comparing to the original morphology, we can see region “gt_1.5” includes all of segment 0 and part of segment 9.
Finally, let’s define a region that includes two already defined regions: “last” and “gt_1.5”. This can be done as follows:
# Join regions "apic" and "gt_1.5" "custom": '(join (region "apic") (region "gt_1.5"))',
This will generate the following region when applied to the previously defined morphology:
Our label dictionary so far only contains regions. We can also add some locations. Let’s start with a location that is the root of the morphology, and the set of locations that represent all the terminal points of the morphology.
# Add a labels for the root of the morphology and all the terminal points "root": "(root)", "terminal": "(terminal)",
This will generate the following locsets (sets of one or more locations) when applied to the previously defined morphology:
Left: locset “root”; right: locset “terminal”¶
To make things more interesting, let’s select only the terminal points which belong to the previously defined “custom” region; and, separately, the terminal points which belong to the “axon” region:
# Add a label for the terminal locations in the "custom" region: "custom_terminal": '(restrict (locset "terminal") (region "custom"))', # Add a label for the terminal locations in the "axon" region: "axon_terminal": '(restrict (locset "terminal") (region "axon"))',
This will generate the following 2 locsets when applied to the previously defined morphology:
Left: locset “custom_terminal”; right: locset “axon_terminal”¶
The decorations¶
With the key regions and location expressions identified and labelled, we can start to
define certain features, properties and dynamics on the cell. This is done through a
arbor.decor object, which stores a mapping of these “decorations” to certain
region or location expressions.
Note
Similar to the label dictionary, the decor object is merely a description of how an abstract cell should behave, which can then be applied to any morphology, and have a different effect depending on the geometry and region/locset expressions.
More information on decors can be found here.
The decor object can have default values for properties, which can then be overridden on specific regions. It is in general better to explicitly set all the default properties of your cell, to avoid the confusion to having simulator-specific default values. This will therefore be our first step:
decor = arbor.decor() # Set the default properties of the cell (this overrides the model defaults). decor.set_property(Vm=-55) decor.set_ion("na", int_con=10, ext_con=140, rev_pot=50, method="nernst/na") decor.set_ion("k", int_con=54.4, ext_con=2.5, rev_pot=-77)
We have set the default initial membrane voltage to -55 mV; the default initial temperature to 300 K; the default axial resistivity to 35.4 Ω·cm; and the default membrane capacitance to 0.01 F/m².
We also set the initial properties of the na and k ions because they will be utilized by the density mechanisms that we will be adding shortly. For both ions we set the default initial concentration and external concentration measures in mM; and we set the default initial reversal potential in mV. For the na ion, we additionally indicate the the progression on the reversal potential during the simulation will be dictated by the Nernst equation.
It happens, however, that we want the temperature of the “custom” region defined in the label
dictionary earlier to be colder, and the initial voltage of the “soma” region to be higher.
We can override the default properties by painting new values on the relevant regions using
arbor.decor.paint().
# Override the cell defaults. decor.paint('"custom"', tempK=270) decor.paint('"soma"', Vm=-50)
With the default and initial values taken care of, we now add some density mechanisms. Let’s paint a pas density mechanism everywhere on the cell using the previously defined “all” region; an hh density mechanism on the “custom” region; and an Ih density mechanism on the “dend” region. The Ih mechanism has a custom ‘gbar’ parameter.
from arbor import density # Paint density mechanisms. decor.paint('"all"', density("pas")) decor.paint('"custom"', density("hh")) decor.paint('"dend"', density("Ih", {"gbar": 0.001}))
The decor object is also used to place stimuli and threshold detectors on the cell using
arbor.decor.place().
We place 3 current clamps of 2 nA on the “root” locset defined earlier, starting at time = 10, 30, 50 ms and
lasting 1ms each. As well as threshold detectors on the “axon_terminal” locset for voltages above -10 mV.
Every placement gets a label. The labels of detectors and synapses are used to form connection from and to them
in the recipe.
# Place stimuli and detectors. decor.place('"root"', arbor.iclamp(10, 1, current=2), "iclamp0") decor.place('"root"', arbor.iclamp(30, 1, current=2), "iclamp1") decor.place('"root"', arbor.iclamp(50, 1, current=2), "iclamp2") decor.place('"axon_terminal"', arbor.threshold_detector(-10), "detector")
Note
The number of individual locations in the
'axon_terminal' locset depends on the underlying morphology and the
number of axon branches in the morphology. The number of detectors that get added on the cell is equal to the number
of locations in the locset, and the label
'detector' refers to all of them. If we want to refer to a single
detector from the group (to form a network connection for example), we need a
arbor.selection_policy.
Finally, there’s one last property that impacts the behavior of a model: the discretisation. Cells in Arbor are simulated as discrete components called control volumes (CV). The size of a CV has an impact on the accuracy of the results of the simulation. Usually, smaller CVs are more accurate because they simulate the continuous nature of a neuron more closely.
The user controls the discretisation using a
arbor.cv_policy. There are a few different policies to
choose from, and they can be composed with one another. In this example, we would like the “soma” region
to be a single CV, and the rest of the morphology to be comprised of CVs with a maximum length of 1 μm:
# Set discretisation: Soma as one CV, 1um everywhere else decor.discretization('(replace (single (region "soma")) (max-extent 1.0))')
Finally, we create the cell.
# (4) Create the cell. cell = arbor.cable_cell(morph, labels, decor)
The model¶
Having created the cell, we construct an
arbor.single_cell_model.
# (5) Construct the model model = arbor.single_cell_model(cell)
The global properties¶
The global properties of a single cell model include:
The mechanism catalogue: A mechanism catalogue is a collection of density and point mechanisms. Arbor has 3 built-in mechanism catalogues:
default,
allenand
bbp. The mechanism catalogue in the global properties of the model must include the catalogues of all the mechanisms painted on the cell decor. The default is to use the
default_catalogue.
The default parameters: The initial membrane voltage; the initial temperature; the axial resistivity; the membrane capacitance; the ion parameters; and the discretisation policy.
Note
You may notice that the same parameters can be set both at the cell level and at the model level. This is intentional. The model parameters apply to all the cells in a model, whereas the cell parameters apply only to that specific cell.
The idea is that the user is able to define a set of global properties for all cells in a model which can then be overridden for individual cells, and overridden yet again on certain regions of the cells.
You may now be wondering why this is needed for the single cell model where there is only one cell by design. You can use this feature to ease moving from simulating a set of single cell models to simulating a network of these cells. For example, a user may choose to individually test several single cell models before simulating their interactions. By using the same global properties for each model, and customizing the cell global properties, it becomes possible to use the cell descriptions of each cell, unchanged, in a larger network model.
Earlier in the example we mentioned that it is better to explicitly set all the default properties of your cell, while that is true, it is better yet to set the default properties of the entire model:
# (6) Set the model default properties model.properties.set_property(Vm=-65, tempK=300, rL=35.4, cm=0.01) model.properties.set_ion("na", int_con=10, ext_con=140, rev_pot=50, method="nernst/na") model.properties.set_ion("k", int_con=54.4, ext_con=2.5, rev_pot=-77)
We set the same properties as we did earlier when we were creating the decor of the cell, except for the initial membrane voltage, which is -65 mV as opposed to -55 mV.
During the decoration step, we also made use of 3 mechanisms: pas, hh and Ih. As it happens, the pas and hh mechanisms are in the default Arbor catalogue, whereas the Ih mechanism is in the “allen” catalogue. We can extend the default catalogue as follow:
# Extend the default catalogue with the Allen catalogue. # The function takes a second string parameter that can prefix # the name of the mechanisms to avoid collisions between catalogues # in this case we have no collisions so we use an empty prefix string. model.properties.catalogue.extend(arbor.allen_catalogue(), "")
Now all three mechanisms in the decor object have been made available to the model.
The probes¶
The model is almost ready for simulation. Except that the only output we would be able to measure at this point is the spikes from the threshold detectors placed in the decor.
The
arbor.single_cell_model can also measure the voltage on specific locations of the cell.
We can indicate the location we would like to probe using labels from the
label_dict:
# (7) Add probes. # Add voltage probes on the "custom_terminal" locset # which sample the voltage at 50 kHz model.probe("voltage", where='"custom_terminal"', frequency=50)
The simulation¶
The cell and model descriptions are now complete and we can run the simulation:
# (8) Run the simulation for 100 ms, with a dt of 0.025 ms model.run(tfinal=100, dt=0.025) # (9) Print the spikes. print(len(model.spikes), "spikes recorded:") for s in model.spikes: print(s)
The results¶
Finally we move on to the data collection segment of the example. We have added a threshold detector
on the “axon_terminal” locset. The
arbor.single_cell_model automatically registers all
spikes on the cell from all threshold detectors on the cell and saves the times at which they occurred.
# (9) Print the spikes. print(len(model.spikes), "spikes recorded:") for s in model.spikes: print(s)
A more interesting result of the simulation is perhaps the output of the voltage probe previously placed on the “custom_terminal” locset. The model saves the output of the probes as [time, value] pairs which can then be plotted. We use pandas and seaborn for the plotting, but the user can choose the any other library:
import pandas import seaborn # (10) Plot the voltages df_list = [] for t in model.traces: df_list.append( pandas.DataFrame( { "t/ms": t.time, "U/mV": t.value, "Location": str(t.location), "Variable": t.variable, } ) ) df = pandas.concat(df_list, ignore_index=True) seaborn.relplot( data=df, kind="line", x="t/ms", y="U/mV", hue="Location", col="Variable", ci=None ).savefig("single_cell_detailed_result.svg")
The following plot is generated. The orange line is slightly delayed from the blue line, which is what we’d expect because branch 4 is longer than branch 3 of the morphology. We also see 3 spikes, corresponding to each of the current clamps placed on the cell.
The full code¶
You can find the full code of the example at
python/examples/single_cell_detailed.py. | https://docs.arbor-sim.org/en/latest/tutorial/single_cell_detailed.html | CC-MAIN-2022-40 | refinedweb | 3,147 | 55.84 |
When users create a new project in the app generator using release 8.6.6.0 and later, the project type will now be App Factory.
App Factory projects will create an ASP.NET-hosted web site project, deployable to any server running Microsoft Internet Information Services (IIS).
These projects contain both a REST API web server and stream HTML, CSS, and JavaScript to web browsers, to support user interaction through a publicly accessible web site. App Factory projects also function as a REST API server for native Mobile Apps.
Developers can also enable App Factory integration with DotNetNuke and SharePoint.
App Factory project folder directory root contains metadata files required by the app generator, as well as the Visual Studio solution file. An “app” folder contains the generated code required to run the server.
Note that projects created before release 8.7.0.0 will use the “WebSite” folder name instead.
Note that projects created before release 8.7.0.0 will use the “WebSite” folder name instead.
The app folder contains a set of resources required for the application to function. The App_Code folder contains the application framework. Upon running the application, the code in that folder is automatically compiled and executed.
All styling is stored under ~/css folder. All client-side scripts are stored under ~/js folder. Standard styling and script files are read by the framework, joined together, and streamed to the client (native app or web browser). The “_ignore.txt” file located in the two directories enumerates which non-standard files and directories are included in the output.
An additional checkbox is now present on the New Project screen – “Implement application framework as class library (for experienced users only).”
When this option is enabled, the application framework code is placed in a separate class library project, named after the project’s namespace.
The developer must have an instance of Visual Studio 2010, 2012, 2013, 2015, or 2017 installed on the development computer in order for the application to run. At compile-time, the Microsoft Visual Studio compiler must compile and package the application source code stored in the namespace folder into a *.dll file under the app folder. Only then will hosting software (Microsoft IIS) will be able to run the application.
App Factory (Advanced) projects store standard CSS and JS files under the class library. Upon compilation, these files are saved as embedded resources and read from the class manifest.
Custom CSS files can be placed under a “css” folder under the “app” directory. Custom JS files can be placed under the “js” folder under the “app” directory. The framework will read any files in those directories and not excluded by the “_ignore.txt” file, and stream them with every page request.
A number of project types have been deprecated or disabled: | https://codeontime.com/blog/2018/03/app-factory-vs-app-factory-advanced | CC-MAIN-2022-21 | refinedweb | 468 | 57.57 |
When to Use a Vertical Bar Chart
- Jun 10 • 5 min read
- Key Terms: vertical bar chart
Vertical bar charts illustrate sizes of data using different bar heights.
For example, let's say we had a service that rented out scooters in San Francisco, California. Each day, we determine the count of total rides. We can plot the count of rides over the past 21 days, with the count each day being a bar of a certain height, to visualize the trend of rides recently.
I'll showcase a few examples of vertical bar charts below.
Import Modules
import pandas as pd import matplotlib.pyplot as plt %matplotlib inline
Example: Scooter Rides Per Day Over Time
To continue with the example above, below is a sample of the original data collected for each ride.
In order to get the count of rides each day, we'd have to perform a group by operation to group the data above by day, and for each day, get the count of rides.
Generate Daily Scooter Ride Data
list_of_days = pd.date_range(start='5-21-2018', end='6-10-2018', freq='D') count_rides = [1812, 1895, 2080, 1910, 1510, 2200, 1685, 2223, 2080, 2056, 1977, 1738, 2315, 1810, 2880, 2150, 2205, 2020, 1850, 1910, 2301]
Plot Scooter Daily Ride Counts
We choose a bar chart below because the count from each day is a total amount value - so bars help us illustrate the significance of this total value each day.
Alternatively, you could use a line plot. However, I think a bar chart is best here.
plt.figure(figsize=(13, 8)) plt.bar(list_of_days, count_rides, align='center', color='indigo') plt.title("Count of Scooter Rides Per Day Over Time", fontsize=18, y=1.02) plt.xlabel("Day", fontsize=14, labelpad=15) plt.ylabel("Count of Rides", fontsize=14, labelpad=15);
Explanation of Scooter Daily Ride Counts
There's no obvious trend from the visualization above. There looks to be a slight increase in daily ride count over time - but I wouldn't jump to that conclusion from this visualization above.
Based on the visualization above, I'd be interested to explore average daily ride counts per day of week (such as Monday versus Tuesday).
Example: Average Rides Per Day
The visualization above was meant to illustrate a possible trend in ride counts per day over time.
However, now I'm interested to explore the average number of rides per day of week. Perhaps more people ride on Mondays than Sundays because they likely use the scooters to commute.
Different than the visualization below, we'll now want a categorical value, the day of the week, on the x-axis, and the average count of rides on the y-axis.
Generate Data for Average Count of Scooter Rides Per Day
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] avg_count_rides = [2040, 2130, 2080, 1900, 1800, 2190, 1760]
Plot Average Scooter Rides Per Day
I think a vertical bar plot works well here because the day names (ex - Monday) are short and fit well on the x-axis.
Also, we often view the days of a week as a progression from one day to the next, starting from Monday and ending on Sunday. Therefore, I think the chart below works well as a vertical bar chart in order of day of week rather than a horizontal bar chart.
df = pd.DataFrame({'day': days, 'average daily count of rides': avg_count_rides})
df.set_index('day').plot(kind='bar', color='darkslategray', figsize=(14, 9)) plt.xticks(rotation=0) plt.ylabel("Average Count of Rides", fontsize=14, labelpad=15) plt.xlabel("Day", fontsize=14, labelpad=15) plt.title("Average Count of Scooter Rides Per Day of Week (from April 2018 to May 2018)", fontsize=18, y=1.02);
Explanation of Average Scooter Rides Per Day Plot
The visualization illustrates that Saturday, on average, has the highest number of scooter rides by customers.
More rides are taken in the early weekdays from Monday-Wednesday than are taken on average later in the week during Thursday-Friday. | https://dfrieds.com/data-visualizations/when-use-vertical-bar-chart | CC-MAIN-2019-26 | refinedweb | 671 | 61.36 |
while checking recent commits to the kernel core i took a look at the
PID namespaces implementation, and it has a fatal flaw: it breaks
futexes and various libraries (and other stuff) that use PIDs as the
means of identifying tasks, by not providing any means of global
identification that works across PID namespaces. (PIDs _are_ a very
convenient and global way of identifying contexts.)
i asked Ulrich about this and it turns out he has warned about this
early on:
but this problem is still present in the code, and it has been recently
committed into mainline via:
commit 30e49c263e36341b60b735cbef5ca37912549264
Author: Pavel Emelyanov <xemul@openvz.org>
Date: Thu Oct 18 23:40:10 2007 -0700
pid namespaces: allow cloning of new namespace
without these problems having been resolved. A full-scale revert is
probably too intrusive, but at minimum we need to turn off user-space
access to this feature via this simple patch. Until this issue is
resolved properly the new PID namespace code needs to be turned off.
Letting this into 2.6.24 would be a disaster.
Signed-off-by: Ingo Molnar <mingo@elte.hu>
---
kernel/fork.c | 8 ++++++++
1 file changed, 8 insertions(+)
Index: v/kernel/fork.c
===================================================================
--- v.orig/kernel/fork.c
+++ v/kernel/fork.c
@@ -1420,6 +1420,14 @@ long do_fork(unsigned long clone_flags,
int trace = 0;
long nr;
+ /*
+ * PID namespaces are broken at the moment: they do not allow
+ * certain PID based syscalls (such as futexes) to be used
+ * across namespaces. This is broken and must not be allowed,
+ * so we keep this feature turned off until it's properly fixed.
+ */
+ clone_flags &= ~CLONE_NEWPID;
+
if (unlikely(current->ptrace)) {
trace = fork_traceflag (clone_flags);
if (trace)
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at
Please read the FAQ at | http://lkml.org/lkml/2007/11/1/141 | crawl-002 | refinedweb | 311 | 59.84 |
Hello,
RDBMS Version: 10.2.0.1.0
Operating System and Version: Windows 2000 SP 4
Yesterday we have upgraded our database server from Oracle 10g Release 1 to Release 2 and started facing problem. Many of our clients has Oracle 8i installed and when they use import (Export works) utility with Oracle 10g Release database they are facing hanging issues. Oracle 8i client and its tools like Export/Import have worked well with 10g release 1.
Can anyone please guide us to know how to avoid this bug? Is there any workaround to this issue. For reference Export and import command parameters are given below.
EXP UserName/Password@DB File=D:\FileName.DMP Log=D:\FileName.log TABLES=TableName Compress=N
IMP UserName/Password@DB File=D:\FileName.DMP Log=D:\FileName.log TABLES=TableName ignore=y analyze=N
For more info, following details can be seen when import is executed. It halts on importing table...
---------------------------------------------------------------------------------
Import: Release 8.1.6.0.0 - Production on Mon Oct 24 19:11:56 2005
Connected to: Oracle Database 10g Release 10.2.0.1.0 - Production
Export file created by EXPORT:V08.01.06 via conventional path
import done in WE8ISO8859P1 character set and UTF8 NCHAR character set
import server uses WE8MSWIN1252 character set (possible charset conversion)
. importing SYSADM's objects into SYSADM
. . importing table "TEMPMY" 2 rows imported
-------------------------------------------------------------------------------------
and following statement is last executed by import session.
INSERT /*+NESTED_TABLE_SET_REFS+*/INTO "TEMPMY"
("NO", "NAME"
)
VALUES (:1, :2
)
Thanks & Regards,
Shailesh
Hello,
In v$Session_Wait following info was seen for Import session which hangs...
Event: SQL*Net more data from client
Wait_Class: Network
Seconds_IN_Wait: 1900
Please let us know if this gives some clue to solve this issue.
Thanks & Regards,
Shailesh
Import using a lower version client to a higher version server?
Hi Pando,
Test case is as follows...
1) Create Table on database which is 10g Release 2.
2) Use Export of Oracle 8i (Or even 10g Release 1) client
3) Drop Table
4) Use import of Oracle 8i (Or even 10g Release 1) client
On step 4 it hangs.
Regards,
Shailesh
Of course id doesn't work. In step 4) you need to use imp from 10gRel2, you can't use imp utility that is an earlier release as the database.
Jurij Modic
ASCII a stupid question, get a stupid ANSI
24 hours in a day .... 24 beer in a case .... coincidence?
Hello jmodic,
I think there is some confusion. If I create dump of 10g (Use export of 10g) and then try to use 8i import this is not allowed.
But if I create dump using export of 8i client and later tried to use import of same client it is allowed. In this case Server version can be 8i, 9i or 10g release 1.
We have observed problem with only 10g release 2. In short I would like to confirm whether by upgrading to Oracle 10g Release 2 on database server do we have to install same release on few hundreds clients? This is not practical.
Thanks & Regards,
Shailesh
use can't use 8i imp on a higher release version, plain and simple if it has ever worked for you then you have been very lucky you MUST use the version of imp that comes with the database you are importing into
Forum Rules | http://www.dbasupport.com/forums/showthread.php?49296-Import-from-Oracle-8i-client-hangs-when-Server-is-Oracle-10g-Release-2 | CC-MAIN-2017-43 | refinedweb | 556 | 65.12 |
CodePlexProject Hosting for Open Source Software
Wow so I know I've had a lot of questions but I decided to give a jump into Farseer 3 with my project. My biggest question is where did the Mathematics namespace go? I used the Calculator class quite extensively and much raycasting. Now I know that it is
directly implemented somewhere in Farseer 3 (raycasting that is) but I don't even know where Geom went yet lol. I understand that they are now the Shapes but I don't know how they are linked to the bodies? Sorry I just am a little overwhelmed trying to switch
over. Finally, is FixedAngleJoint just gone or is it implemented with the Body now? I still don't understand it all just yet.
You should read the Box2D Manual, it explains the engine really well, and study the TestBed examples.
Geoms have been replaced by Fixtures, and each Fixture has a single shape which describes how it collides.
FixedAngleJoint is gone, but you can use Body.FixedRotation. This doesn't have any give though, and I hope they can get FixedAngleJoint back.
To see how raycasting works you will need to look at the Testbed sample, and read the Box2D Manual. It uses a callback and the value you return tells the raycast operation to continue or cancel. Pretty neat I think! And you can always do manual raycasts
against shapes though.
Ok, I've always used the BodyFactory and GeomFactory in the past. I have switched most of everything in my game to use the new BodyFactory and FixtureFactory but I don't know how to attach the fixture to the body. I've seen the body.CreateFixture() method
but it requires a shape, not a fixture. Would I want to do something like this:
//Create body and geom to associate with
tempFixture = FixtureFactory.CreateRectangle(Farseer.World, size.X, size.Y, mass);
//Load vals to fixture (what collision categories it is part of, friction, etc.
LoadFixture(tempFixture);
//Connect with tempBody
tempBody.CreateFixture(tempFixture.Shape);
I don't see how this would be the best way to do it though because I don't see how tempFixture.Shape would take any of the collision category or friction info along with it. Should I instead not use FixtureFactory and create the shape myself and then once
it is done, change the friction and collision categories based off the body? I only use temporary Fixtures because they are cloned, from what I read, when put to a body. I also saw though that you can access the body through the fixture. I just can't get my
head wrapped around the how these all work together. Sorry again, jumbled mess. Just need some good help with this (or at least a point to something I over read or missed).
UPDATE!!
Looked into the internals of all of the methods I've been using, and saw that FixtureFactory creation creates a body inside the method. I have changed to using Shape objects and the PolygonTools methods now. The only thing left to ask is how to offset different
shapes from the center of a body. Is the position of a shape it's relative position to the body or is there something else I can use?
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://farseerphysics.codeplex.com/discussions/214138 | CC-MAIN-2017-04 | refinedweb | 585 | 73.78 |
Querying and Updating a Database Using Web Services in InfoPath 2003 and ASP.NET
This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.
Summary: Learn how to create a Web service and access that Web service in Microsoft Office InfoPath 2003 Service Pack (SP) 1 and a Web application using Microsoft ASP.NET. (11 printed pages)
Mike Talley, Microsoft Corporation
April 2005
Applies to: Microsoft Office InfoPath 2003
Contents
This proof-of-concept article demonstrates how some functionality of a Microsoft Office InfoPath solution, based on a Web service, can also be offered as a Microsoft ASP.NET Web application. This is useful when InfoPath is not available on the client computer to fill out a form. Commonly referred to as a "reach" experience, this kind of browser-based Web application allows a user to edit the same information in the InfoPath form, but without the features of InfoPath, such as rich-text formatting, the ability to check spelling, and the ability to edit the data if a network connection is not available.
The Web service uses the GetCustomers method to return a Microsoft .NET DataSet, which contains records from the Customers table of the Northwind SQL database. The Web service uses the UpdateCustomers method to accept changes to the records. Both methods are used in the InfoPath form template and the ASP.NET Web application, giving each solution the ability to edit the database records.
This article also includes architectural considerations for Web services and information about design limitations of InfoPath. These sections outline problems that can arise when designing and deploying Web services in the enterprise environment, and examine the limitations of InfoPath forms based on Web services.
This article describes three tasks:
Creating the Web service that returns and accepts a DataSet
Creating the InfoPath form template
Creating the ASP.NET Web application
You build each of these three items separately in either Microsoft Visual Studio .NET 2003 or InfoPath 2003, beginning with the Web service.
This Web service retrieves information from the Customers table of the Northwind SQL database. If you do not have Microsoft SQL Server 2000, you can install the Microsoft SQL Server 2000 Desktop Engine, and install the Northwind database.
To create the Web service
In Visual Studio .NET 2003, create a Microsoft Visual C project with the ASP.NET Web Service template. Name it nwindCustomers.
In the design surface of Service1.asmx.cs, insert a SQLConnection.
Select SQLConnection1. In the Properties Window, click the ConnectionString menu and select New Connection.
Configure the connection to connect to the Northwind database on the SQL Server. Whenever possible, use Microsoft Windows NT Integrated Security to connect to the database.
Insert a SQLDataAdapter on the design surface.
In the Data Adapter Configuration Wizard, click Next and select the connection you just created. Click Next.
Select Use SQL Statements and click Next.
In the box labeled "What data should the data adapter load into the DataSet?", type SELECT * FROM Customers. As an alternative, you can use the Query Builder to create your query.
Click the Advanced Options button, ensure that all three check boxes are selected, and click OK.
In the Properties Window of SQLDataAdapter1, click Generate dataset.
Create a DataSet named "dsCustomers1" and select the Add this dataset to the designer check box. Click OK.
To add code to the Web service
Insert the following code below the automatically inserted Web method section.
[WebMethod] public DataSet GetCustomers() { sqlConnection1.Open(); sqlDataAdapter1.Fill(dsCustomers1); sqlConnection1.Close(); return dsCustomers1; } [WebMethod] public DataSet UpdateCustomers(DataSet dsUpdated) { if (dsUpdated!=null) { sqlConnection1.Open(); int NumRows = sqlDataAdapter1.Update(dsUpdated); if (NumRows > 0) sqlDataAdapter1.Fill(dsUpdated); sqlConnection1.Close(); } return dsUpdated; }
Click File, and then click Save All.
Click Debug, and then click Start Debugging.
When the Web page loads, click GetCustomers.
Click the Invoke button.
Ensure that you see XML tags and all customer information from the Customers database, and then close both Web pages.
Click the Build menu, and then click Build Solution.
Close the project.
To create the InfoPath form template
Open InfoPath and select Design a Form from the Fill Out a Form dialog box.
In the Design a Form task pane, select New from Data Connection.
In the first step of the Data Connection Wizard, select Web service, and then click Next.
Select Receive and submit data, and then click Next.
Type the URL of your Web service. In this example, it would be. Click Next.
In the Select an operation box, select GetCustomers, and then click Next.
Click Next unless you want to change the name of the main query.
The next URL is for the submit process, and the URL should appear automatically. Click Next.
In the Select an operation box, select UpdateCustomers, and then click Next.
Click Modify to the right of the Field or group box, and then select the node under the dataFields group that represents the full DataSet. In this case, it should be ns1:dsCustomers.
Click Next and then click Finish.
Drag the Customers node from the dataFields group to the view, and choose to bind it to a Repeating section with controls.
Preview the form to ensure that the Web service is returning the Customers information.
You can also modify a field (with the exception of the CustomerID field because it is the primary key) and click Submit to test that the form can submit changes back to the database through the Web service.
To create the ASP.NET Web application
In Visual Studio .NET 2003, create a project with the ASP.NET Web Application template. Name it Customers.
On the main Web form (WebForm1.aspx), insert a DataGrid control.
To add the ability to edit data
Select DataGrid1 and press F4 to display the Properties Window, and then click Property Builder at the bottom of the window.
Click the Columns tab.
Under Column list, browse the Available columns list and open the Button Column node.
Select Edit, Update, Cancel and click Add to add the buttons to the Selected columns box.
To add columns from the database
In the Property Builder dialog box, click the Columns tab.
Clear the Create columns automatically at run time box.
Under Column list, select Bound Column and click the Add button to add the column to the Selected columns box.
Type the name of the database field in the Data Field text box. To display text other than the Data Field in the header of the Data Grid column, type that into the Header text field, and then click Apply.
Repeat steps 3 and 4 for each database field you want to show in the Data Grid, such as CompanyName, ContactName, Address, City, Region, PostalCode, Country, Phone, and Fax.
Click OK.
To add a Web reference to the project
Add a Web reference to the Web service you created in Creating the Web Service That Returns and Accepts a DataSet.
Add a using statement for the Web service reference. It begins with the namespace you used when creating the Web service, such as the following.
To insert code to initialize the DataGrid
In the Page_Load event, insert the following code:
In this code and the following code, replace Web_service_namespace with the namespace of your Web service. This is the same as your using statement syntax in the previous section.
To insert code to handle Events
Select DataGrid1 and press F4 to display the Properties Window, and then click Events to display the available event handlers.
In the Properties Window, double-click EditCommand.
Insert the following code for the Edit_Command event handler.
Select the WebService1.aspx [Design] tab, and double-click CancelCommand in the Properties Window.
Add the following code to the Cancel_Command event handler.
Select the WebForm1.aspx [Design] tab, and double-click UpdateCommand in the Properties Window.
Add the following code to the Update_Command event handler.
// Connect to Web service, get DataSet to be updated. Web_service_namespace.Service1 wsCustomers = new Web_service_namespace.Service1(); DataSet myCustomers2 = wsCustomers.GetCustomers(); DataRow drEditedRow = myCustomers2.Tables[0].Rows.Find(e.Item.Cells[1].Text); // Loop through each column in DataGrid and update DataRow. int intCount; for (intCount=0;intCount<e.Item.Cells.Count;intCount++) { if (e.Item.Cells[intCount].Controls.Count > 0) { if (e.Item.Cells[intCount].Controls[0] is TextBox) { TextBox txtTemp = (TextBox) e.Item.Cells[intCount].Controls[0]; string strValue = txtTemp.Text; if (strValue.Length == 0) { drEditedRow[DataGrid1.Columns [intCount].HeaderText] = System.DBNull.Value; } else { drEditedRow[DataGrid1.Columns [intCount].HeaderText] = strValue; } } } } // Call Web service method UpdateCustomers // with updated DataSet. DataSet myCustomersUpdated = wsCustomers.UpdateCustomers(myCustomers2); // Bind the updated DataSet to the DataGrid // and take edited row out of edit mode. DataGrid1.DataSource = myCustomersUpdated; DataGrid1.SelectedIndex = -1; DataGrid1.EditItemIndex = -1; DataGrid1.DataBind();
Save the project and build the solution by clicking the Build menu and then clicking Build Solution.
Browse to the page by opening your browser and typing the following in the address bar:. This confirms that the results of the Web service call are shown in the Web form.
When you want to deploy Web services in the enterprise environment for client computers with InfoPath, and also offer a solution for those computers that do not have InfoPath installed, you can develop an ASP.NET application that mimics some of the functionality of InfoPath. You will not, however, enjoy the full capabilities of the InfoPath editing environment, which offers declarative design features, standard Microsoft Office features such as rich-text formatting, the ability to check spelling, or the offline capability of editing a form without a network connection.
For more information about working with .NET DataSets in InfoPath 2003, see Lab 9: ADO.NET DataSets in InfoPath 2003.
Watch MSDN Webcast: Database Connectivity in InfoPath Through ADO.NET DataSet Support - Level 400.
More detailed steps for creating an ASP.NET Web application similar to the application outlined in this article can be found in Walkthrough: Using a DataGrid Web Control to Read and Write Data. This walkthrough also contains code for writing the application in Microsoft Visual Basic .NET.
For more information about creating Web services, see Web Services Developer Center.
For more information about ASP.NET authentication, including Web application authentication options and the Kerberos extensions included in Microsoft Windows Server 2003, see Kerberos Protocol Transition and Constrained Delegation.
For in-depth information about ASP.NET security, including different authentication options, see Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication, and specifically the ASP.NET Security chapter and the section of the Internet Security chapter titled "ASP.NET to Remote Enterprise Services to SQL Server."
For more information about Microsoft SharePoint Portal Server 2003 Single Sign-On (SSO) options, see Single Sign-On in SharePoint Portal Server 2003.
See the article Sharing InfoPath Forms with Users Who Do Not Have InfoPath for an overview of options available for sharing InfoPath forms. | https://msdn.microsoft.com/en-us/library/bb608314(v=office.11).aspx | CC-MAIN-2016-50 | refinedweb | 1,825 | 58.89 |
Let's continue exploring Electron alternatives. This time, NodeGui. NodeGui uses Qt5 instead of Chromium, so we'll be leaving the familiar web development behind, but it tries to not be too far from it, as web development is what everyone knows.
Interestingly it comes with preconfigured Svelte, React, and Vue setups, but since Svelte starter doesn't work at all, we'll try out the React one.
Installation
We need to install a bunch of dependencies, not just
npm packages. For OSX this one extra line of
brew is required. For other OSes, check documentation.
$ brew install make cmake $ npx degit episode-75-nodegui-react $ cd episode-75-react-nodegui $ npm i
Unfortunately instead of having happy React started, what we get at this point is some T***Script abomination, so next few steps were me ripping out T***Script and putting back plain JavaScript in its place.
Start the app
To start the app we'll need to run these in separate terminals:
$ npm run dev $ npm run start
package.json
Stripped out of unnecessary dependencies, here's what's left:
{ "name": "react-nodegui-starter", "main": "index.js", "scripts": { "build": "webpack -p", "dev": "webpack --mode=development", "start": "qode ./dist/index.js", "debug": "qode --inspect ./dist/index.js" }, "dependencies": { "@nodegui/react-nodegui": "^0.10.2", "react": "^16.13.1" }, "devDependencies": { "@babel/core": "^7.11.6", "@babel/preset-env": "^7.11.5", "@babel/preset-react": "^7.10.4", "@nodegui/packer": "^1.4.1", "babel-loader": "^8.1.0", "clean-webpack-plugin": "^3.0.0", "file-loader": "^6.1.0", "native-addon-loader": "^2.0.1", "webpack": "^4.44.2", "webpack-cli": "^3.3.12" } }
.babelrc
There's small
.babelrc after removing unnecessary stuff:
{ "presets": [ ["@babel/preset-env", { "targets": { "node": "12" } }], "@babel/preset-react" ], "plugins": [] }
webpack.config.js
And here's similarly cleaned up
webpack.config.js:
const path = require("path") const webpack = require("webpack") const { CleanWebpackPlugin } = require("clean-webpack-plugin") module.exports = (env, argv) => { const config = { mode: "production", entry: ["./src/index.jsx"], target: "node", output: { path: path.resolve(__dirname, "dist"), filename: "index.js" }, module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { cacheDirectory: true, cacheCompression: false } } }, { test: /\.(png|jpe?g|gif|svg|bmp|otf)$/i, use: [ { loader: "file-loader", options: { publicPath: "dist" } } ] }, { test: /\.node/i, use: [ { loader: "native-addon-loader", options: { name: "[name]-[hash].[ext]" } } ] } ] }, plugins: [new CleanWebpackPlugin()], resolve: { extensions: [".js", ".jsx", ".json"] } } if (argv.mode === "development") { config.mode = "development"; config.plugins.push(new webpack.HotModuleReplacementPlugin()); config.devtool = "source-map"; config.watch = true; config.entry.unshift("webpack/hot/poll?100"); } return config }
src/index.jsx
This is reasonably close to what we would use in plain React.
import { Renderer } from "@nodegui/react-nodegui" import React from "react" import App from "./app" process.title = "My NodeGui App" Renderer.render(<App />) // This is for hot reloading (this will be stripped off in production by webpack) if (module.hot) { module.hot.accept(["./app"], function() { Renderer.forceUpdate() }) }
Hot module reloading
Important thing to note is hot module reloading we enabled.
You can use hot module reloading in Electron as well, but you can also use Cmd-R to reload manually, so it's nice but unnecessary.
NodeGUI has no such functionality, so you're very dependent on hot module reloading for development to be smooth. Unfortunately if you ever make a syntax error in your code, you get this:
[HMR] You need to restart the application!
And you'll need to quit the application, and start it again.
So in practice, the dev experience is a lot worse than default Electron experience.
src/app.jsx
And finally we can get to the app.
Similar to how React Native works, instead of using html elements, you need to import components from
@nodegui/react-nodegui.
The nice thing is that we can declare window properties same as any other widgets, instead of windows being their own separate thing. Some APIs differ like event handling with
on={{...}} instead of individual
onEvent attributes.
A bigger issue is the Qt pseudo-CSS. It supports different properties from HTML (so there's now "How to center in Qt" question, which you can see below), and unfortunately it doesn't seem to support any element type or class based selectors, just attaching to an element with
style or using ID-based selectors. There's probably some way to deal with this.
import { Text, Window, hot, View, Button } from "@nodegui/react-nodegui" import React, { useState } from "react" function App() { let [counter, setCounter] = useState(0) return ( <Window windowTitle="Welcome to NodeGui" minSize={{ width: 800, height: 600 }} styleSheet={styleSheet} > <View style={containerStyle}> <Text id="header">Welcome to NodeGui</Text> <Text id="text">The button has been pressed {counter} times.</Text> <Button id="button" on={{ clicked: () => setCounter(c => c+1) }}>CLICK ME!</Button> <Text id="html"> {` <p>For more complicated things</p> <ul> <li>Use HTML</li> <li>Like this</li> </ul> `}</Text> </View> </Window> ) } let containerStyle = ` flex: 1; ` let styleSheet = ` #header { font-size: 24px; padding-top: 20px; qproperty-alignment: 'AlignHCenter'; font-family: 'sans-serif'; } #text, #html { font-size: 18px; padding-top: 10px; padding-horizontal: 20px; } #button { margin-horizontal: 20px; height: 40px; } ` export default hot(App)
Overall this wasn't too bad a change from plain React. We can still structure the components the same way, use either hooks or classes for state, and also import any frontend JavaScript libraries we want.
Results
Here's the results:
After all the work setting up Nodegui with React and plain JavaScript it would be a shame not to write a small app with it, so in the next episode we'll do just that.
As usual, all the code for the episode is here.
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/taw/electron-adventures-episode-75-nodegui-react-3hp6 | CC-MAIN-2021-49 | refinedweb | 941 | 51.44 |
I am trying to used two ssd1306 with two different address. I have one working but having trouble with the second. The first one has an address of 60 and the second one address is 61.
Start your code here
i2c = I2C(-1, scl=Pin(22), sda=Pin(21))
address = 60
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
def oled1():
i2c = I2C(-1, scl=Pin(22), sda=Pin(21))
address = 61
oled1_width = 128
oled1_height = 64
oled1 = ssd1306.SSD1306_I2C(oled1_width, oled1_height, i2c)
Maybe can get a little help
RAy
Micro-python is not user friendly to Hobbyist that just want to learn how to write some codes. The lessons you need to teach is how to write libraries for sensors and different displays. The core of the user of Micro-python must be season code writers to write library for there devices so they will work on the esp8266 and the esp32. It does look the support for the Raspberry pi is a lot better than the esp devices.
Now I do know my expertise is not in micro-controllers. I am just retired mechanical engineer trying to learn how to program these little devices. When you do a project in Arduino and try to take that to Micro-Python you do run into a lot of road blocks
I do think you guys courses are very good. But I must say since the support for Micro Python is limited maybe you should offer a course on taking a datasheet and making a workable library for Micro Python. Now that course I would pay for.
Good luck to you guys and keep the courses coming.
Ray
Hello Ray, thank you for the suggestion and I’m sorry to hear that.
Unfortunately that goes beyond our control (creating the MicroPython documentation). We also create projects on more basic topics and building specific projects, but we’re considering creating more advanced courses.
I really appreciate your feedback. (Sorry for taking so long to get back to you, but I was without internet for the last couple of days during a trip. I’m finally back!) | https://rntlab.com/question/oled-ssd1306-esp32/ | CC-MAIN-2019-39 | refinedweb | 355 | 72.26 |
Hi all With sending this mail, I'm going to commit a rather large bunch of changes. After trying to compile with quite every remotely usefull warning option enable, I found warnings about classes having pointer data members but neither copy constructor nor operator= ! I was also quite shocked to see such warnings stemming from ClanLib. Shallow pointer copies in objects are very dangerous and most often lead to strange, hard to catch bugs. I'd guess that quite a few segfaults were caused by this. Therefore, I went through each and every class, declaring a private copy constructor and operator= without defining them. Where required I wrote them manually even in those cases where the compiler would create correct ones to lower the chance that someone will add a pointer member to those classes without making a deep copy of it. I fear that I'll probably have overlooked some things, especially in classes where already a copy constructor was defined. BTW defining only a copy constructor and no operator= is even worse then not defining both - a small change in the using code, copy constructor is used where operator= was and a bug vanishes mysteriously... Therefore, I want to add the following design rules: ------------------------------------------------------------------------------------. Every class containing pointer members shall define a destructor releasing the memory. This implies that every pointer must be initialized in every constructor (be it 0 or a value). ------------------------------------------------------------------------------------- I'm going to apply the second rule where necessary soon, since I've found a few cases where this wasn't done already - without searching. The next thing I'm going to do right now is to apply the rule that every class should reside in it's own .hxx[/.cxx] . After doing this I'll go on and apply another design rule: -------------------------------------------------------------------------------------- Every subdirectory in the source tree shall be reflected by a name space in the source code. -------------------------------------------------------------------------------------- This will require to add a few more subdirectories and getting rid of namespace pingus. I also plan to add some more namespaces whereever I find large groups of related classes or where I consider it usefull to improve the automatic documentation from doxygen (e.g. I plan to create input/buttons, input/pointers ...). Since I'm not yet familar with autoconf/automake/libtool I don't know how to add new subdirs - a small HOWTO would be welcome, else I'll look how the existing subdirs are bound in. Beside those changes which I plan to do in any case (I can't see any sane counter argument), I've got a few questions: - Why is there a init() in every action? Initializing in constructor is much safer. - May I make float delta a global constant of some sort? -) ... */. As with the other changes, a simple approve is enough. I'll do the work myself to learn more about Pingus and to walk another step on the long way of transforming the code into something I've fun to work with. Right now I found huge piles of (probably old) code that simply terrible and screaming to be rewritten. Bye David PS: While adding copy methods I also rewrote some code to distract myself from the boring task at hand. I remember that I rewrote SoundHolder to use a map instead of a vector of some self defined pair class and removed some useless code from to_string. sstream::freeze has nothing to do with releasing the memory, a frozen stream may not be assigned to, that's all. | http://lists.gnu.org/archive/html/pingus-devel/2002-08/msg00058.html | CC-MAIN-2018-30 | refinedweb | 585 | 68.1 |
Despite wrting a couple of articles on how to install a Python algorithmic trading research environment on Ubuntu, I still receive a lot of email regarding how to translate the instructions into Windows and Mac. It turns out that a substantial number of you emailed and commented on the site about an alternative, known as a Python distribution.
A Python distribution is a much easier way to install all of the corresponding Python libraries that are used for algorithmic trading. In essence you download a single installation package, which comes provided with all of the major scientific Python libraries such as IPython, NumPy, SciPy, scikit-learn, pandas and matplotlib as well as an Integrated Development Environment (IDE) that lets you code using a Graphical User Interface (GUI). This is a different approach when compared to my previous suggestion of installing the libraries manually and working directly with IPython and Python scripts.
Two of the major Python distributions are Enthought's Canopy and Continuum Analytics' Anaconda. Unfortunately, I hadn't heard of the latter when I first wrote the previous two guides on installing Python in Ubuntu. I've now tried the installation of Anaconda (which is free!) and have found it to be an easy multi-platform method for getting started in Python.
This article will discuss how to install Anaconda on Mac OSX. However, it is pretty straightforward to change it for Windows or Ubuntu, since Continuum Analytics provide easy installers for each. Once installed, I'll also describe how to run basic Python code using the accompanying Spyder IDE.
The first task is to visit the Continuum Analytics site. You will see the following page:
Continuum Analytics home page
Click the Download Anaconda button and you'll be presented with a box asking for an email address (and confirmation):
Continuum Analytics email address entry
You will be presented with the downloads page. On my MacBook Air it has automatically selected the Mac downloads. For simplicity I am going to download Python 2.7, rather than the newer Python 3.4, as there are still some minor incompatibility issues with certain packages that I make use of:
Continuum Analytics Anaconda downloads page
Once you select the "Graphical Installer" button, you'll be presented with the usual Mac OSX file save option. Save the file in the normal way. Note that the file (as of the writing of this article) is approximately 250Mb:
Anaconda package download
When the file has downloaded, make sure to open it and you'll see the following installation window:
Anaconda initial installation
Accept all of the Terms & Conditions and then proceed with the installation. You'll notice that Anaconda takes up a reasonable amount of hard disk space (0.75Gb), but this is because it comes with a lot of Python libraries pre-installed. Once the installation is finished, you'll see the following screen:
Anaconda installation finalised
The installation procedure places a shortcut icon on your Mac OSX desktop:
Anaconda desktop shortcut
If you click this icon Anaconda will load and present you with the following screen:
Anaconda launcher window
However, I had trouble attempting to load Spyder at this stage! Hence, I dug out a workaround that allows you to use Spyder directly. Use the Spotlight option in Mac OSX (the magnifying glass in the top right corner) and type "Terminal" in the dialog box. The first hit should be a black Terminal icon. Click this and you'll be presented with a prompt window. I've changed the colours on mine to be black with white text, but yours may be white with black text:
Terminal window in Mac OSX
First we need to check that Anaconda has become the default Python installation. To check this, type the following:
which python
This is the output I received, which shows that Anaconda is the current default Python installation:
/Users/mhallsmoore/anaconda/bin/python
Now you can simply type the following to launch the Spyder IDE:
spyder
You will now see the following screen, which is the Spyder IDE:
Spyder IDE
On the left hand pane you have a file editor, while the right hand pane contains an Object Inspector, a Variable Explorer and a File Explorer, which all allow you to see different aspects of your Python code. On the bottom right hand side is an IPython console, which allows you to carry out interactive Python programming.
To check that NumPy is installed correctly (a basic sanity check), we can type the following:
import numpy as np np.mean([1,2,3])
If all goes to plan, you should see the following output:
Sypder IPython conole output
And that's it for installing Anaconda and Spyder on Mac OSX! This is a simpler procedure (on Mac!) than the previous Ubuntu installation I mentioned before in this article. In the future I'll be discussing how to do the same for Windows and Linux, which will make your quantitative finance programs truly cross-platform. | https://www.quantstart.com/articles/Easy-Multi-Platform-Installation-of-a-Scientific-Python-Stack-Using-Anaconda | CC-MAIN-2018-05 | refinedweb | 830 | 56.69 |
Larry Wall, the Guru of Perl
I “talked” to Larry Wall, the creator of the Perl scripting language, by e-mail on March 1. Larry proved to be quite voluble, and I think you'll find this interview fun as well as informative. I certainly did.
Marjorie: Back in the beginning, what inspired you to write Perl?
Larry: That depends on what you mean by “beginning”. Like Moses said: “In the beginning, God created the heavens and the earth.” I'm not being entirely facetious about that. Whichever way you care (or don't care) to interpret scripture, I think the universe is a pretty hefty inspiration for anyone who aspires to be a creator. I've certainly tried to put a universe of ideas into Perl, with some amount of success.
In terms of biographical beginnings, my father was a pastor, as were both my grandfathers, and many of my ancestors before that. My wife likes to say that preachers are bred for intelligence (though I suppose she might be saying that just to flatter me). Be that as it may, I did receive a fairly decent set of brain construction genes. Beyond that, I also received a rich heritage of ideas and skills, some of which found their way into Perl culture. For instance, the notion that you can change the world. The idea that other people are important. The love of communication and an understanding of rhetoric, not to mention linguistics. The appreciation of the importance of text. The desire to relate everything to everything else. The passion to build up rather than tear down. And, of course, the dead certainty that true wealth is measured not by what you accumulate, but by what you pass on to others.
The beginnings of Perl were directly inspired by running into a problem I couldn't solve with the tools I had. Or rather, that I couldn't easily solve. As the Apostle Paul so succinctly put it, “All things are possible, but not all things are expedient.”.
Of course, actually writing something like Perl takes a great deal of hard work, patience and even humility. Had I just been doing it for myself, I probably wouldn't have made the effort. However, I was aware from the beginning that other people were going to be using Perl, so I've always integrated the “laziness curve” over the whole community, not just over myself. I was being vicariously lazy. So here we are talking about vicars again.
Marjorie: Well, that certainly answered the question fully. I must admit I didn't expect you to go back as far as the beginning of the Universe. :-) How'd you come up with that name?
Larry: I wanted a short name with positive connotations. (I would never name a language “Scheme” or “Python”, for instance.) I actually looked at every three- and four-letter word in the dictionary and rejected them all. I briefly toyed with the idea of naming it after my wife, Gloria, but that promised to be confusing on the domestic front. Eventually I came up with the name “pearl”, with the gloss Practical Extraction and Report Language. The “a” was still in the name when I made that one up. But I heard rumors of some obscure graphics language named “pearl”, so I shortened it to “perl”. (The “a” had already disappeared by the time I gave Perl its alternate gloss, Pathologically Eclectic Rubbish Lister.)
Another interesting tidbit is that the name “perl” wasn't capitalized at first. UNIX was still very much a lower-case-only OS at the time. In fact, I think you could call it an anti-upper-case OS. It's a bit like the folks who start posting on the Net and affect not to capitalize anything. Eventually, most of them come back to the point where they realize occasional capitalization is useful for efficient communication. In Perl's case, we realized about the time of Perl 4 that it was useful to distinguish between “perl” the program and “Perl” the language. If you find a first edition of the Camel Book, you'll see that the title was Programming perl, with a small “p”. Nowadays, the title is Programming Perl.
Marjorie: Okay, is Perl perfect now or do you continue to do further development?
Larry: Hmm, the two are not mutually exclusive. Look at Linux. :-)
Actually, Perl was never designed to be perfect. It was designed to evolve, to become more adaptive, as they say. There is no such thing as a perfect organism, biologically speaking. About the most you can say is an organism is more or less suited for the environment in which it finds itself. In fact, biologists are just now realizing that any organism which seems to be “perfect” for one environment is likely to be in danger of extinction as soon as the environment changes. Over-specialization is only as good as your ecological niche. We're not just talking about dinosaurs here, but also snail darters and cheetahs and a bazillion beetles in Brazil—not to mention Visual Basic.
We've already seen the deaths of many over-specialized organisms in computing: Lisp machines, Ada chips and many so-called fourth generation languages. Any program ever written in assembly language for an obsolete architecture is now obsolete. Likewise, any program that ties its fortunes to a single operating system is likely to go down with the ship. I don't know how many more torpedoes Windows can take before it sinks, but if and when it does, a whole batch of specialized programs are going down with it. Obviously, for reasons relating to the open source movement, Linux doesn't have this particular problem.
Anyway, back to Perl. Right from the start, Perl was designed for change. This involves certain tradeoffs, some of which appear to be suboptimal to people who don't think the way I think. For instance, I wanted to be able to add new keywords to Perl without breaking old programs, so I put them into a separate namespace from variable names. This meant either variable names or keywords had to be marked somehow as special. I chose to mark variables, since it also made it easy to interpolate variables into strings, and since there's a history of marking variables in computer languages such as BASIC. Note this was actually non-adaptive in certain environments, namely in the minds of certain purists who think the added punctuation makes Perl ugly, and too much like BASIC. Well, maybe it does. So what? That was a conscious tradeoff so that Perl would be more useful in the long run. In that respect, Perl is less adaptive in the specific ecological niche comprising the minds of computer scientists, but more adaptive in the world as a whole. I've never regretted that particular tradeoff.
Of course, once you get past first impressions, there are many things in Perl that computer scientists do like, such as lexically scoped variables and closures. So by and large, those computer scientists who can hold their nose long enough to get the cheese into their mouths find the taste bearable.
More importantly, Perl 5 introduced an extension system that, much like Linux's module system, allows continued development of the language without actually changing the core language. That is, you can pull in a Perl module that warps the language to your purposes in a controlled fashion. If a module becomes popular enough, we can consider making it part of the core of Perl—maybe.
That's not to say we never change the core anymore. We recently added support for multi-threading and for Unicode. Interestingly, even when we do make changes to the core these days, we make it look as though the programmer is pulling in an extension module. Essentially, if you use a fancy new core feature that warps the semantics in some way, you have to declare it. This is how we maintain almost complete compatibility with older Perl scripts. Most Perl 1 scripts still run unchanged under Perl 5. As a side benefit, feature declarations are right up front where the dependency is visible at compile time, so we rarely die in the middle of execution for lack of a feature. Compare this with shell programming, where you don't even know whether all the programs you're intending to invoke actually exist until you try to run them, and then, kablooey!
Marjorie: What are your future development plans for Perl?
Larry: If I could predict that, I'd be a smarter person than I am. I'm just smart enough to know I'm no smarter than that, which is why I designed Perl to evolve in the first place.
That being said, I can tell you some of the characteristics I look for in a project.
First, if it has anything to do with text processing, Perl is a natural. Perl has never stopped being a text-processing language, though it long ago escaped the straitjacket of being just a text processing language. That's one reason Perl was a natural for CGI programming, because Perl excels at ripping text apart and putting it back together.
Second, I look for projects that involve gluing things together. We don't use glue on Legos—we glue together things that weren't designed to go together. As a glue language, Perl has thin characteristics so that it can flow into tiny gaps, and thick characteristics so that it can fill in larger voids. Perl is always at home in the interstices. The typical CGI script or mod_perl servlet glues a database together with the Web. When that particular interstice disappears, there will be other interstices.
Third, I look for projects that franchise the disenfranchised. We joke about sending our leftovers to the starving people in Africa, but there are, in fact, billions of potential programmers outside of America who can't afford to lay out hundreds of bucks for an operating system or an application. China recently put in a single order for 200,000 Internet books from a publisher I know (and work for). That's just the beginning. This is why I hacked Unicode support into Perl last year. Of course, text processing has something to do with Unicode too.
Having said all that, it almost doesn't matter what I look for in my next development project, because I don't do most of the Perl development these days. The Perl community outweighs me by many orders of magnitude, and they're really the ones who are making Perl the be-all and end-all of scripting languages. I just sit on the sidelines and cheer occasionally. I'm cheering now. Rah, rah, rah! :-)
Marjorie: In what way is Perl better than other scripting languages such as Python and Eiffel?
Larry: Perl is unique, not just among scripting languages, but among computer languages in general. It's the only computer language consciously and explicitly designed to be postmodern. All other computer languages are still stuck in the modern era to some degree. Now, as it happens, I don't normally use the term “postmodern” to describe Perl, because most people don't really understand postmodernism, even as they embrace it. But the fact is that American culture has become thoroughly postmodern, not just in music and literature, but also in fashion, architecture and in overall multicultural awareness.
Modernism was based on a kind of arrogance, a set of monocultural blinders that elevated originality above all else, and led designers to believe that if they thought of something cool, it must be considered universally cool. That is, if something's worth doing, it's worth driving into the ground to the exclusion of all other approaches.. We escaped from the fashion police in the 1970s, but many programmers are still slaves of the cyber police.
In contrast, postmodernism allows for cultural and personal context in the interpretation of any work of art. How you dress is your business. It's the origin of the Perl slogan: “There's More Than One Way To Do It!” The reason Perl gives you more than one way to do anything is this: I truly believe computer programmers want to be creative, and they may have many different reasons for wanting to write code a particular way. What you choose to optimize for is your concern, not mine. I just supply the paint—you paint the picture.
Marjorie: Who is using Perl and how are they using it?
Larry: A couple of years ago, I ran into someone at a trade show who was representing the NSA (National Security Agency). He mentioned to someone else in passing that he'd written a filter program in Perl, so without telling him who I was, I asked him if I could tell people that the NSA uses Perl. His response was, “Doesn't everyone?” So now I don't tell people the NSA uses Perl. I merely tell people the NSA thinks everyone uses Perl. They should know, after all.
As an interesting side note, it turned out this fellow was the very administrator who shut down the NSA project Perl was (indirectly) written to support. He was vaguely amused when I pointed out Perl might well be the most enduring legacy of the project.
As to what everyone uses Perl for, it's really all over the map. I was astounded several years ago to be told how heavily Perl is used on Wall Street. “A Perl book on every other desk” is how I heard it. But it makes sense when you realize that market analysts need to revise their models continually, and they need to scan news services for information that might be related to their positions in the market. Rapid prototyping and text processing are what they need.
Many people associate Perl with CGI scripts, though of course most of the heavy lifting is done with mod_perl servlets under Apache. Perl is used just as much on the client side in the robots and spiders that navigate the Web and build much of the linkage implicit in various on-line databases. And that's not all. If you've ever been spammed (and who hasn't?), your e-mail address was almost certainly gleaned from the Net using a Perl script. The spam itself was likely sent via a Perl script. One could say that Perl is the language of choice for Net abuse. And one could almost be proud of it.
That's only scratching the surface of what Perl is used for. Without getting Mr. Gallup or the U.S. Census Bureau involved, the best way to figure out what Perl is used for is to look at the 800 or so reusable extension modules in the Comprehensive Perl Archive Network (the CPAN, for short). If you glance through those modules, you'll get the impression that Perl has interfaces to almost everything in the world. With a little thought, you may figure out the reason Perl has interfaces to everything is not so much so Perl itself can talk to everything, but so Perl can get everything in the world talking to everything else in the world. The combinatorics are staggering. The very first issue of The Perl Journal (not to be confused with Linux Journal) contained an article entitled “How Perl Saved the Human Genome Project”. It explains how all the different genome sequencing laboratories used different databases with different formats, and how Perl was used to massage the data into a cohesive whole.
Marjorie: We received a product announcement for PerlDirect from ActiveState Tool Corporation that says:
“PerlDirect provides reliability, stability, support and accountability for Perl through the following features: validated, quality-assured releases of Perl and its popular extensions; advice and support; Y2K test suite; and a Perl Alert weekly bulletin. PerlDirect offers an opportunity to provide direct input to a leading organization involved in open-source development. Basic annual subscription rates start at $12,000 US.”
Are you affiliated with this company? I think it's interesting they are offering to let a subscriber have direct input to open-source development for $12,000 a year. Does this make sense?
Larry: Sounds like a pretty ordinary support contract to me. I don't think even Richard Stallman would disagree with the notion that support is a valid way to make money off free software.
I'm not directly affiliated with ActiveState, but I've worked with them, and I think the problems they've solved far outweigh any problems they've created. You've got to understand their market has always been the Windows space, where you're actually doing people a favor by charging them money for things, because that's the only way to keep from confusing them. Linux users are smarter than this, of course, but some Linux users aren't quite smart enough to realize Windows is a different culture, and Perl, being a postmodern language that is sensitive to context, will look different in a different culture.
Marjorie: Oops, didn't mean to sound as if I thought they weren't on the up-and-up—just curious if you knew them. What are your views of the Open Source movement? Do you think it will become a true phenomenon, or is it just a passing fancy?
Larry: I must have a conjunctive rather than a disjunctive brain, because I think both of those notions are true. And I also think they're both false. :-)
How can we claim open source is becoming a true phenomenon when it has already been a true phenomenon for a couple of decades now? We're merely pointing out to everyone a practice that has a proven track record of producing excellent code. On the other hand, we're certainly trying to make it a truer phenomenon, in the sense that we hope more people will feel it's a valid development model for many kinds of software that were formerly developed under a closed model.
And, of course, it's a passing fancy—just as we've had other passing fancies for free-form syntax, structured programming, and more recently, object orientation.
What you have to understand is that, from the viewpoint of the passing fancy, people represent a kind of fork in the road. It's like separating the sheep from the goats in the book of Revelation. Some of these fancies pass on the one side and go into oblivion, while others pass on the other side and go into common practice, usually after a period of excessive enthusiasm. Free-form syntax, structured programming and object orientation are all good (in moderation). But note that all of these passing fancies had a history of being useful before they became popular. The passing fancies that go into oblivion are the ones rooted not in history, but rather in someone's wishful thinking (usually someone from marketing). By this criterion, open source will probably go into common practice because it's already in common practice.
The way I see it, the open source movement is just another manifestation of the growing postmodernism of our culture. By contrast, the notion of trade secrecy is just a rehash of the modernistic idea of originality at any cost. We've had a lot of lip service given to code reuse over the years, but it really only works with open source. A postmodern computer programmer truly believes in reusing good code whether it's original or not. It's not a point of pride anymore. A good postmodern is supposed to plagiarize the things he or she thinks are cool.
Marjorie: If everything becomes open source, how will programmers make a living?
Larry: Contrary to many open source advocates, I don't see everything becoming open source. What I do see is a growing recognition that anything resembling large-scale infrastructure ought to be open source, much as the United States has recognized that interstate highways should not be toll roads. On the other hand, we don't expect city parking lots to be free except in certain enlightened municipalities. So I'd expect to see Windows become open source before Word does.
That being said, there are many ways to make a living off open source, just as there are many ways to make a living off open science. But here's precisely where I think the open source movement has some growing to do. Open science basically started out as a hobby of the rich, but it didn't truly blossom into the form we recognize today until its patronage was taken over by educational institutions. This has not quite happened yet with open source. Or rather, it started to happen, but then many educational institutions got caught up in the drive for the almighty dollar. I wish more places would follow the example of UC Berkeley.
Marjorie: On that note, how do you make a living?
Larry: To start off, I worked programming and sys admin jobs like anyone else and did my free software on the side. Later, I wrote a book and started collecting royalties. The book became a best-seller, so it made my publisher, O'Reilly & Associates, even more money than it made me. Of course, they have to pay more people with that money, so it evens out.
Anyway, three years ago it occurred to Tim O'Reilly and me that anything good for Perl was also good for O'Reilly & Associates, so now they pay me to do whatever I like, as long as it helps Perl. It's been a good symbiosis.
Marjorie: Any interesting projects you'd like to tell us about?
Larry: I'm supposed to be working on the third edition of the Camel Book, so I don't officially have any other interesting projects at the moment. Of course, I have been playing around with that Palm Pilot Tim O'Reilly gave me for Christmas, but I won't tell if you won't.
Marjorie: Agreed. Give us some personal info—where you went to school, interests, etc.
Larry: I spent the first half my childhood in south Los Angeles about two miles from where the Watts riots broke out, and the second half of my childhood in Bremerton, Washington, where no riots broke out, but I did graduate from high school. For the third half of my childhood, I went to Seattle Pacific University, where I started off majoring in chemistry and music, later switched to premed, and eventually (after taking several years off to work in the SPU computer center) ended up majoring in Natural and Artificial Languages (a self-designed major). After that, my wife and I attended grad school in linguistics at Berkeley and UCLA. At the time, we were actually planning to be missionaries (more specifically, Bible translators), but we had to drop that idea for health reasons. Funny thing is, now the missionaries probably get more good out of Perl than they'd have gotten out of me as a missionary. Go figure.
As for my interests, that's hard, because I tend to be interested in anything that's interesting. Which comes out to pretty much anything except opera and soap opera—space opera's okay, though.
Marjorie: What do you do for fun?
Larry: Read and listen to my wife read to me (especially space opera). Discuss anything and everything with anyone and everyone in my family. Work NY Times crossword puzzles. Play mah jong. Practice aikido. Watch anime. (Maybe Japanese soap opera is okay.) Play with my fish. Rescue my fish from the equipment I bought to keep them alive.
Marjorie: Looks like you stay busy and have fun—a good combination. What do you eat for breakfast?
Larry: I eat all kinds of things for breakfast—but then, I generally eat breakfast at lunchtime.
Marjorie: Seems as good a time as any. Thanks for giving us so much of your time. It's been interesting. | https://www.linuxjournal.com/article/3394?page=0,0&quicktabs_1=2 | CC-MAIN-2018-17 | refinedweb | 4,033 | 62.88 |
XML Interview Questions and Answers – Introduction.I am sure you want to know the most common XML Interview Questions and Answers that will help you crack the interview with ease.
Below are the most common feature of XML Interview Questions, that can give you a great foundation into the language.:
•XML is a software and hardware independent tool used to transport and store data while HTML is used to display data and focuses on how data looks
•XML is for data representation while HTML is for displaying purpose
•XML supports user-defined tags while HTML provides pre-defined tags
•XML is a case-sensitive language while HTML language is not case-sensitive
•In XML, you make up your own tags while HTML uses a fixed, unchangeable set of tags
•In XML, all tags must be closed while in HTML, it is not necessary to close each tag
•XML provides a framework to define markup languages while HTML is a markup language itself
•XML is content driven while HTML is format driven
4.5 (2,882 ratings)
View Course
4.What are the features of XML?
Answer:
The features of XML are:
•Very easy to learn and implement
•Does not require an editor because XML files are a text file
•Both human-readable and machine-readable
•Minimal and a limited number of syntax rules in XML
•It is extensible, and it specifies that structural rules of tags
•Has a free open standard
5.What are the benefits of XML?
Answer: These are the main benefits of using XML are:
•Simplicity: Very easy to read and understand the information coded in XML.
•Openness: It is a W3C standard, endorsed by software industry market leaders.
•Extensibility: It is extensible because it has no fixed set of tags. You can define them as you need.
•Self-descriptive: XML documents do not need special schema set-up like traditional databases to store data. XML documents can be stored without such definitions because they contain metadata in the form of tags and attributes.
•Scalable: XML is not in binary format so you can create and edit files with anything and it is also easy to debug.
•Fast access: XML documents are arranged in hierarchical form so it is comparatively faster.
6.What are the basic rules while writing XML?
Answer: The basic rules while writing XML:
•XML should have a root element
•XML tags should be closed
•XML tags are case sensitive
•XML tags should be nested properly
•Tag names cannot contain spaces
•Attribute value should appear within quotes
•White space is preserved in XML
7.What is an XML Schema?
Answer:
An XML schema gives the definition of an XML document and it has following:
•Elements and attributes
•Elements that are child elements
•Order of child elements
•Data types of elements and attributes
8.Where is XML used?
Answer:
It is used to exchange the information between two applications. Information can also be exchanged between two different applications which are running on a different server which will check for well-formedness and validate the document. It also allows us to read, create and modify existing XML document.
11.What is an XML namespace?
Answer:
An XML namespace is a collection of element type and attributes names.
12.What is XQuery?
Answer:
XQuery is a query language that is used to retrieve data from XML documents. You can add, update, delete and list the XML with use of XQuery.
13.What I XMLA?
Answer:
It is a protocol of Microsoft for XML-messaging used for exchanging data between client- | https://www.educba.com/xml-interview-questions/ | CC-MAIN-2020-10 | refinedweb | 593 | 61.16 |
Docker is an open platform, that gives customers the ability to deploy, multiple o/s containers on any give host. This allows for the deployment of multiple environments without having to incur the overhead of having a virtual machine per environment. Docker uses linux o/s facilities like namespaces, cgroups and union capable file systems to deploy lightweight containers.
A good explanation of Docker Architecture and concepts can be found here .
At the time of writing of this post, oracle does not support running oracle databases in docker containers. However it is conceivable that, in the future customers might want to deploy the oracle database in a docker container’s on the cloud. It could be an effective mechanism to create and maintain a large number of database copies in order to support development environments that follow agile development methadologies.
Oracle has published docker images for Oracle Linux 6 and Oracle Linux 7 . Recently Oracle has also published a DockerFile and a build script that builds a docker image that uses Oracle Linux 7, installs and creates a oracle database (11gr2 or 12cr1) on it, and creates a new image that includes the oracle database. This is an easy way to get an oracle 12.1.0.2 database up and running for development purposes.
In this blog post, I will detail the steps i followed to build an Oracle 12c database, Docker image, that runs inside of a VirtualBox virtual machine.
The high level steps are as follows.
- Download the oracle 12cr1 installation Files.
- Download and setup a VirtualBox Ubuntu 16.04 image from osboxes.
- Install docker on Ubuntu 16.04
- Download the Oracle Docker files from github
- Stage the 12cr1 binaries Execute the build script to build the Oracle database docker image.
Download the oracle 12cr1 installation files.
- Login to edelivery.oracle.com
- Choose Oracle Database Enterprise Edition, and Linux x86-64
- Choose the 2 files, and download them.
- Rename (Because the Docker build script expects files to be with these names) the files as shown below
- V46095-01_1of2.zip to linuxamd64_12102_database_1of2.zip
- V46095-01_1of2.zip to linuxamd64_12102_database_2of2.zip
Download and setup a VirtualBox Ubuntu 16.04 image from osboxes
From, download the .vdi file, for “VirtualBox (VDI) 64Bit”.
The downloaded file name will be Ubuntu-16.04-Xenial-VB-64bit.7z. Unzip the contents of this file, to any directory. This will give you a file named “Ubuntu 16.04 64bit.vdi”
From your VirtualBox console create a new VirtualMachine.
- Use the expert mode
- Name “Ubuntu1604”
- Type “Linux”
- Version – “Ubuntu (64-bit)”
- Choose 3Gb of memory for the virtualmachine.
- Choose “Do not add a virtualdisk”
- Click Create
- Copy the file you downloaded from, “Ubuntu 16.04 64bit.vdi” into the newly created directory, named “Ubuntu1604”
- This brings you back to the home page.
- Choose the newly created image “Ubuntu1604”, click on Storage, and Click on “Controller SATA”.
- Here choose to add a new disk, and choose the file “Ubuntu 16.04 64bit.vdi”.
- Click OK.
- This brings you back to the home page.
- Click on Network.
- The Network Adapter 1, is configured to use NAT, change this to use “Bridged Adapter”, Click Ok.
Now you have a virtualmachine, which runs the latest version of Ubuntu. The / directory has 99GB of space allocated to it, and hence is sufficient to create the oracle docker image.
Start the virtualmachine and login. (The default user it creates is osboxes, and the password is osboxes.org)
Install docker on Ubuntu 16.04
Follow the instructions at, to install docker.
- login as the user osboxes into Ubuntu
- Invoke a linux terminal.
- sudo
- vi /etc/apt/sources.list.d/docker.list
- Add the following line
- deb ubuntu-xenial main
- save and quit
- apt-get update
- apt-cache policy docker-engine
- apt-get install linux-image-extra-$(uname -r)
- apt-get install docker-engine
- sudo service docker start
- sudo groupadd docker
Create a new o/s user for running docker images.I will be performing all the docker operations going forward, from this OS User.
- I created a new o/s user named rramdas (Regular user, not admin) (Feel free to create a user with any name you want to use)
- I added this user to the sudoers file, so I can sudo to root from this user.
- Add the new user rramdas to the docker group
- sudo usermod -aG docker rramdas
Login as rramdas and ping yahoo.com to ensure that you are able to communicate with machines on the internet.
Next I installed opensshd-server so that I can ssh to this virtual host from my laptop. (Not required)
Download the oracle Docker files from github
- Login as rramdas
- Create a directory /u01 in which we will place all the docker files
- sudo su –
- mkdir /u01
- chown rramdas:rramdas /u01
- exit
- cd /u01
- git clone
- cd /u01/docker-images
- remove all the directories other than OracleDatabase.
Stage the 12cr1 binaries
From the directory where the oracle installation binaries were downloaded in step 1.
- Copy the oracle installation binaries to the virtual host. (10.1.1.156 is the Ip address of my virtual host)
- scp linuxamd64_12102_database_* rramdas@10.1.1.156:/u01/docker-images/OracleDatabase/dockerfiles/12.1.0.2/.
We are staging the oracle installation files in this directory because the Docker build script expects the files in this directory.
Build the Docker Image with Oracle 12c
- login as rramdas to the ubuntu virtualhost.
- cd /u01/docker-images/OracleDatabase/dockerfiles
- ./buildDockerImage.sh -v 12.1.0.2 -e -p manager -i
It Took 43 minutes to build the image.
If we take a deeper look into the DockerFile.ee , we can see that the following actions have been executed.
- Download the latest docker image for Oracle Linux
- Create the necessary O/S users and groups.
- Install the oracle-rdbms-server-12cR1-preinstall rpm, which checks and installs all the pre-requesite rpm’s for an oracle install and sets up the required kernel parameters.
- Runs the Universal Installer (Using a response file) to install the oracle binaries and create an oracle database.
- Creates the oracle listener and tnsnames entries.
After the script completes execution, we have a new docker image database:12.1.0.2-ee
Start the Docker database container.
Now we have a 12c CDB, with 1 PDB running, in the Docker Container.
You can list the running docker containers using the “docker ps” command
This database can be accessed from any oracle database client (like sqlcl or sqlplus, or any application via jdbc , odbc etc).
This should get you started with using an Oracle 12c database in a Docker container. | http://126kr.com/article/jzsv4u4j6 | CC-MAIN-2017-17 | refinedweb | 1,102 | 57.27 |
Opened 5 years ago
Closed 5 years ago
#18459 closed Bug (invalid)
makemessages - problem with Unicode
Description
Commit 4a10308 from 2012-06-07 broke makemessages:
git checkout 4a10308
$ django-admin.py makemessages --all Traceback (most recent call last): File "/usr/bin/django-admin.py", line 7, in <module> execfile(__file__) File "/django/django/bin/django-admin.py", line 5, in <module> management.execute_from_command_line() File "/django/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/django/django/core/management/__init__.py", line 348, in execute version=get_version(), File "/django/django/__init__.py", line 7, in get_version return get_version(*args, **kwargs) File "/django/django/utils/version.py", line 25, in get_version git_changeset = get_git_changeset() File "/django/django/utils/version.py", line 46, in get_git_changeset timestamp = git_show.communicate()[0].partition('\n')[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 14535: ordinal not in range(128)
git checkout master (1a10a06)
$ django-admin.py makemessages --all processing language pt_BR UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 715460: invalid start byte
I've tried
from __future__ import unicode_literals but it didn't work.
I'm running Python 2.7.3 on Arch Linux x86_64
Change History (3)
comment:1 follow-up: 2 Changed 5 years ago by
comment:2 Changed 5 years ago by
The first error you mention has been fixed in 90985048fc1882483794e6734eb91401aefbe768
For the second one, we'd need some more details. Try to increase verbosity (--verbosity=2).
Makemessages had some problems with 2 files in my static folder. One of them (list.txt) had the character "\u0096":
Text <96> Text Text Text
And the other was encoded using ISO-8859 (had latin words like "inglês" and "alemão").
The error with increased verbosity:
$ ../manage.py makemessages --all --verbosity 2 processing file list.txt in ./arquivos/static UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 5: invalid start byte
Converting those files to UTF-8 using native2ascii solved the problem.
comment:3 Changed 5 years ago by
Thanks for looking closer at the error. So I will consider that the problem was on your side and close the ticket.
The first error you mention has been fixed in 90985048fc1882483794e6734eb91401aefbe768
For the second one, we'd need some more details. Try to increase verbosity (--verbosity=2). | https://code.djangoproject.com/ticket/18459 | CC-MAIN-2017-13 | refinedweb | 380 | 50.84 |
Pages: 1
im googlin now since hours but didnt find anything useable...
what i want..
typedef struct vertex {
GLfloat x;
GLfloat y;
GLfloat z;
}
class SimpleClass {
public:
SimpleClass();
~SimpleClass();
private:
vector<vertex> v;
string n;
};
SimpleClass::SimpleClass() {
n="something";
voxel x;
x.x=0.0f; x.y=0.0f; x.z=0.0f;
v.push_back(x);
} test;
-snip-
test >> file
-snip-
test << file
-snip-
or something like that..
so i dont have to care about what i write or how to read it back... and all those other nasty shit a file is causing ;-)
i found some lib's implementing stuff like that... like boost .. but i'd like to know more about...
and also i don't want to use something else than the realy base-libs
(I also bet that there MUST be something i didn't find yet)
Offline
this no innate way to do that without writing your own methods. I'd suggest using the archive stuff from boost
Offline
bad news :cry:
Offline
personally, I hate boost
but you can always do this the C way, if you want...
the C way is as follows:
SomeClass c(); char buffer[sizeof(SomeClass)]; memcpy( (void*)buffer, (void*)&c, sizeof(SomeClass)); ... file << buffer; ... file >> buffer; memcpy( (void*)&c, (void*)buffer, sizeof(SomeClass)); c.SomeMethod();
keep in mind this isn't really the best way to do it, but it works
Offline
hmmm ic :?
i'll really have to spend more time on this than i actually thougt i would have to ...
well im already using SDL... but .. it got just some very very basic stuff (writing bitmaps to files) as far as i know at the moment (but supports zip and bz2 if i got it right - in a way you dont have to care about that it is compressed)
anyway not really what i wanted to have...
i guess my next step will be to have a look at some applications for 3D-model-creation (GPL/LGPL'ed ones of course
)
so i implement support for there model-file-format and build the rest so it fits
this way i dont run in the need of writing my own tools for import/export/filearchitecture or even a tool to create 3D-model's
Offline
Hmm.. we've built own functions in our company, to store our data. We're more or less serializing the objects by our own methods, deserializing it again as well.
But .. a typedef with a type definition and without a type name interesting.
We've overloaded our operators to filestreams, and wrote the serialize / deserialize ourselves, exactly what you don't want. But - you've been googling for hours? In an hour you'd have written this.
// STi
Ability is nothing without opportunity.
Offline
#include <iostream>
#include "SDL.h"
#include "SDL_opengl.h"
using namespace std;
typedef struct vertex {
GLfloat x;
GLfloat y;
GLfloat z;
};
// Main
int main(int argc, char **argv) {
vertex test;
test.x=1.0f;
test.y=2.0f;
test.z=3.0f;
cout << test.x << " " << test.y << " " << test.z << " " << endl;
exit (0);
})
eg.:
vector<vertex> vertexvector;
----------------------------------------
about serialization...
well... im working on a "hobby-project" ... not on a business one
im a system-admin / network-operator .. no programmer - i just have some very basic knowladge of programming techniques and languages (cobol, pl/1,borland-c (ansii-c), borland-c++(ansii-c++), Visual C++ with mfc (just to mention that i did something with it - but just cuz we had to at school - bless god and beer that i forgot everything about it ), java)
i just started programming again cuz of interest .. basically i wanted to know what im able to do with OpenGL
therefore my intend isnt to finish everything as fast as possible but fiddeling arround and learning
Offline)
no, the proper typedef usage is:
typedef [original type] [new type];
and a proper struct definition is:
struct [name] { [data members] };
so, combining the two, you get:
typedef [struct definition] [new name];
or
typedef [name] { [data members] } [new name];
it's a C trick to do this:
typedef struct _vertex { int x,y,z; } vertex;
because under C, to declare a struct variable you must use "struct _vertex"... the typedef just makes it simpler...
under C++ you can do: struct vertex {int x,y,z; }
and use "vertex v;" just fine....
Offline
ah
thx
Offline
i guess my next step will be to have a look at some applications for 3D-model-creation (GPL/LGPL'ed ones of course
))
Wings3D, ArtOfIllusion, Blender, Equinox3D I find Wings3D to be the most useable, but texturing in it is a pain, I do my models in Wings3D and texturing in AoI.
Blender is the gimp of 3D, it does everything. Equinox3D looks interesting, I haven't tried it yet.
I don't know what your application is, but you might be interested in using Python instead of C++; it has pickling for easy serialization, and the Soya3D API is about as easy to use a 3D API as you can get. Another option I might slip in is Java, which also has serialization and Java3D, a SceneGraphAPI and JOGL, a direct OpenGL layer. Python programs seem to have a lower framerate, but is easier to use. Java with JOGL is said to be about equivalent in speed to OpenGL. Java with Java3D is somewhere in between.
Dusty
Offline
Thx a lot for those hints! ... i'll google em asap!
I already had a look at blender... it seems to be a REALY powerfull app but its *mainly* a renderer ... i saw that there are scripts to export .blender files to something else.. like OBJ or 3DS, MD3,4,5...
but couldnt figure out yet *how* or even if those scripts come with the arch pgk ... just read in posts that they exist .. (but i found a API-Docu for *Blender-scripting*...)
what id like to have would be a GPL'ed/OS/FREE 3D-Model-creator able to export to common 3D-Model-file formats
till now all i googeled about where win32 apps ... some free.. most commercial (starting at 1.000 Euro)
as you maybe already guessed ... "common file format" according to games
my intend with this *Project* is to code a game ...
maybe you know Master of Orion 2, Birth of Federation, (guess) civilization,...
Offline
about Phyton/Java ...
uhm.. well... i can't say anything about Phyton... never *saw* it.. just heard the name often...
and java.. well.. from the very first moment up to now i simply [personal opinion]DON'T LIKE IT[/personal opinion] ... not even one piece of it... i can't really point at something why i don't like it
but my main-reason why i don't wanna switch is: i started to "use/learn" SDL and OpenGL some time ago... i had a look at the tutorials(mostly NeHe)... but after some while it got boring to simply draw rotating/blitted thingies flying arround on the screen... also i liked to play Master of Orion 2... so why not combine those to and code a OpenGL/SDL game following the principle of MoO
(no i dont think that i will ever finish it... i have too much ideas/too less knowledge and time
)
and as i already said ... i do it as a hobby and for further education
Offline
Blender isn't really just for rendering. It can do everything... hard beast to tame though.
I'm pretty sure Blender has scripts to export to more formats than anything. I even found one that exported directly to Java3D. If that's supported, anything is. Soya3D uses Cal3D files, which include animations and such all in the same file and you can call them, might be a useful format for a game because you don't have to write animations either (Soya was designed for gaming -- slune for example).
Wings3D exports to a handful of modeling formats. You'll want to choose only one format in the end because you don't want to have to write a file-format loader for every single format out there.
Dusty
Offline
Pages: 1 | https://bbs.archlinux.org/viewtopic.php?pid=73002 | CC-MAIN-2016-36 | refinedweb | 1,356 | 72.66 |
rewind (3p)
PROLOGThis manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
NAMErewind — reset the file position indicator in a stream
SYNOPSIS
#include <stdio.h>
void rewind(FILE * stream);
DESCRIPTIONThe functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2008 defers to the ISO C standard. The call:
rewind(stream)
(void) fseek(stream, 0L, SEEK_SET) | https://readtheman.io/pages/3p/rewind | CC-MAIN-2019-18 | refinedweb | 107 | 50.33 |
Centrica Chaim AWS Accounts - Python Module
Project description
Chaim
This module gives chaim functionality to your python scripts.
usage
Chaim acts as a context manager for python scripts. It obtains temporary credentials for an AWS account under the alias 'tempname'. These credentials are removed when the context goes out of scope.
from chaim.chaimmodule import Chaim with Chaim("sredev", "mpu", 1) as success: # if success is True we successfully obtained credentials if success: # we are 'in context' so the credentials are valid ses = boto3.session.Session(profile_name="tempname") client = ses.client("s3") buckets = client.list_buckets() # script continues but we are now 'out of context' so the credentials are no longer # valid and have been deleted. print("all done")
Chaim can also act as an ordinary python class facilitating access to chaim accounts. Each object
only works with one AWS account. You should set the
tempname class constructor variable to a
unique value if you use more than one instance at once.
You will need to call
Chaim.requestKeys() to actually get keys for the account.
It should be thread safe as there is thread locking code in the ini file write routine.
from chaim.chaimmodule import Chaim ch = Chaim("sredev", "rro", 1, tempname="uniquename12") success = ch.requestKeys() ... # when program ends or object is destroyed Chaim.deleteAccount() is automatically called # which will delete the account information from the ini file del(ch)
Chaim can be quite 'chatty' and defaults to logging output to stderr. There are 3 levels of verboseness:
0: only show errors
1: show progress
>1: debug messages
verbose defaults to
0
API
Parameters
Parameters to set up the Chaim Object
account - the full account name to obtain credentials for.
role - the chaim role to access the account as.
duration - integer between 1 and 12 for number of hours to hold the credentials for.
defaults to 1 hour.
region - defaults to 'eu-west-1'.
tempname - the alias for the account - defaults to 'tempname'.
terrible - set to True for Ansible/Terraform support - defaults to False.
verbose - set loglevel, defaults to WARN, 1 = INFO, >1 = DEBUG
logfile - log output to a seperate file, defaults to NONE.
Exceptions
Chaim has 2 unique exceptions
UmanagedAccount
NoUrl
Neither of these should be thrown when using as a context manager.
Callable Methods
None of these are intended for basic, context manager, usage, this list is provided for completeness. To use these the Chaim object must be setup first.
These Functions have been written to ease future expansion of this module.
getDefaultSection()
returns the default section from the credentials file
getDefaultAccount()
returns the default account name as set in the credentials file
getEndpoint()
returns the url to access the chaim api gateway
renewSection(section)
requests updated credentails for the account named in
section
requestKeys()
Obtains credentials from chaim. Takes no parameters
storeKeys(text)
Stores the keys contained in
text into the credential file format.
text should be the returned text from a requests object. It should be convertable
into json and then into a python dictionary.
myAccountList()
Returns a list of tuples describing your current chaim accounts
[(account, expire timestamp, expire string, default account),(...)]
displayMyList()
Logs the current chaim credentials you hold, along with their expiration times.
requestList()
Returns a list of tuples of all account ids and account names that chaim knows about
[(account number, account name),(...)]
deleteAccount(account)
Deletes the account credentials
account from the credentials file
parkAccount(account)
Removes the
account definition from the credentials file and stores it for later use
in the chaim-parked accounts file
unparkAccount(account)
Removes the
account definition from the chaim-parked accounts file, adds it to the
credentials file and renews the credentials for it.
listParkAccounts()
Returns a list of parked account aliases.
["cdev","hprod",...]
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/chaim/ | CC-MAIN-2019-51 | refinedweb | 646 | 55.84 |
05 August 2011 11:55 [Source: ICIS news]
By Felicia Loo
SINGAPORE (ICIS)--Naphtha prices in ?xml:namespace>
Battered by a slump in global crude futures, the second-half September naphtha contract closed at $905.50-907.50/tonne (€642.91-644.33/tonne) CFR (cost and freight) Japan – the lowest since 29 June 2011, according to ICIS data.
Prices had fallen from $1,012-1,014/tonne CFR Japan on 1 August, the highest this week. The contract soared after
“The market is spooked by a potential double-dip recession,” said a trader.
September Brent crude on
In open market trading on Friday, a second-half October naphtha cargo changed hands at $905.00/tonne. A second-half October cargo was done at $968.00/tonne on Thursday, ICIS data showed.
( | http://www.icis.com/Articles/2011/08/05/9482784/asia-naphtha-prices-nosedive-on-crude-equity-sell-off.html | CC-MAIN-2015-22 | refinedweb | 132 | 66.13 |
> But in the meantime, as a workaround, fall back on __main__.pymol_argv if
> sys.argv is not defined.
Thanks! For what it's worth, I ended up with something like
try:
args = sys.argv
except AttributeError:
sys.argv = pymol_argv
args = sys.argv
because I'm using optparse to handle command line options. When
optparse generates its automatic help messages, it calls through to
sys.argv no matter what you tell it to do.
Here's a related question: when I call sys.exit from my script (or,
actually, when optparse calls it), it ends up causing a traceback. Is
there any way to turn that behavior off? At the moment, I'm using this
as a workaround:
from pymol import cmd
import sys
def exit(*args,**kwargs):
cmd.quit()
sys.exit = exit
but I thought that I remembered hearing about a better way once.
Thanks,
-michael
>
> Michael Lerner
> > Sent: Tuesday, August 14, 2007 2:35 PM
> > To: pymol-users@...
> > Subject: [PyMOL] Why can't I get to sys.argv on Linux?
> >
> > Hi,
> >
> > I'm using PyMOL as a front end to a few scripts. So, I need
> > to get my hands on sys.argv to process the command-line
> > arguments. On OS X, everything works just like I'd expect.
> > However, on Linux, I can't get sys.argv. Here's a very simple
> > Python script:
> >
> > #!/usr/bin/env python
> > import sys
> > print dir(sys)
> > print sys.argv
> >
> > When I run pymol -cr ./my_script.py on Linux, I get this:
> >
> > PyMOL>run ./x.py,main
> > ['__displayhook__', '__doc__', '__excepthook__', '__name__',
> > '__stderr__', '__stdin__', '__stdout__', '_getframe',
> > 'api_version', 'builtin_module_names', 'byteorder',
> > 'call_tracing', 'callstats', 'copyright', 'displayhook',
> > 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
> > 'exec_prefix', 'executable', 'exit', 'exitfunc',
> > 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
> > 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount',
> > 'hexversion', 'maxint', 'maxunicode', 'meta_path', 'modules',
> > 'path', 'path_hooks', 'path_importer_cache', 'platform',
> > 'prefix', 'setcheckinterval', 'setdlopenflags', 'setprofile',
> > 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
> > 'version', 'version_info', 'warnoptions'] Traceback (most
> > recent call last):
> > File "/users/mlerner/src/pymol/modules/pymol/parser.py",
> > line 287, in parse
> >
> > parsing.run_file(exp_path(args[nest][0]),__main__.__dict__,__m
> > ain__.__dict__)
> > File "/users/mlerner/src/pymol/modules/pymol/parsing.py",
> > line 407, in run_file
> > execfile(file,global_ns,local_ns)
> > File "./x.py", line 4, in ?
> > print sys.argv
> > AttributeError: 'module' object has no attribute 'argv'
> > PyMOL: normal program termination.
> >
> > While pawing around in the PyMOL sources, I found that
> > pymol_argv shows up. It seems to be what I want, but I don't
> > know how stable it is. Am I supposed to use it instead of sys.argv?
> >
> > Thanks,
> >
> > -michael
> >
> > --
> > Biophysics Graduate Student
> > Carlson Lab, University of Michigan
> >
> >
> > --------------------------------------------------------------
> > -----------
> >@...
> >
>
>
You can do this with the isodot command.
Are you using the PyMOL-APBS plugin to generate or view electron
density maps? If so, would you like me to add dot representations to
the plugin in the next release?
Thanks,
-michael
--
Biophysics Graduate Student
Carlson Lab, University of Michigan
On 8/15/07, shivesh kumar <shivesh_sls@...> wrote:
> Dear all
> How can the dot representation of electron density map is made as in the
> figure in attachment,I know the mess representation through isomesh
> command.Please suggest.Thanx in advance.
> Shivesh kumar
>
> shivesh
>
> ________________________________
> Be a better Heartthrob. Get better relationship answers from someone who
> knows.
> Yahoo! Answers - Check it out.
> -------------------------------------------------------------------------
>@...
>
>
>
>
Hi,
I'm trying to compile pymol with mingw. Has somebody successfully did
this?
Could somebody give me some hints on how to get glut library work on my
windows box ?
Thanks.
You.
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/pymol/mailman/pymol-users/?viewmonth=200708&viewday=15&style=flat | CC-MAIN-2017-34 | refinedweb | 606 | 61.02 |
With the Azure SDK 2.5.1 Release we took the opportunity to combine existing Web Publishing techniques with the new Azure Resource Management APIs to support Azure’s newest feature for Web, Mobile, and API developers – Azure App Service. We’ve added Azure API Apps as a publishing target for the ASP.NET developer, so you can make use of concepts like Resource Groups and App Hosting Plans in the new Azure portal, right within Visual Studio.
Enable Developers with One-click Strongly-typed REST API Clients
For developers who consistently need to consume REST APIs from various vendors or services, a component of the Azure App Service – Azure API Apps – exposes metadata formats like Swagger and WADL to describe REST API endpoints. Included is a new Azure API App template that provides dynamic Swagger generation from ASP.NET Web API controllers. Additionally, there is a new consumption system in Visual Studio that provides one-click C# code generation features to make it easier than ever to consume REST APIs without needing to write repetitive HTTP calls or JSON or XML parsing. The generated client code is also supported in Portable Class Library projects, so you can use them from any platform supporting PCL, like Windows Phone 8.1 and Universal apps, as well as apps written targeting Android and iOS with Xamarin. Read more about the Azure App Service on the Microsoft blog announcing the availability of Azure App Services and Azure blog announcing Azure App Service. You can also watch recording of the webcast announcement to learn more.
Access to a Rich Marketplace of Third-party APIs
The Azure Marketplace now contains dozens of APIs for existing Microsoft services and products, and includes other APIs from partners such as Twilio, Salesforce, and Dropbox. The REST API consumption features available for custom APIs are also available for APIs installed via the Azure Management Portal’s interface, so you’ll be able to access strongly-typed clients for any of the APIs in the rapidly-growing Azure marketplace.
End-to-end Experience of Developing, Deploying, and Consuming an Azure API App
Now let’s walk-through the new Azure API Apps tools. To start, we’ll create a new Azure API App using the new project templates available in the 2.5.1 release. Then, we’ll deploy that Azure API App to the cloud. Once it’s deployed we’ll create a simple client application that will consume the deployed API App using the strongly-typed auto-generated client code.
Getting Started: the Azure API App Template
Create a new Web Application project using Visual Studio 2013 named TodoListApi.
When the One ASP.NET dialog opens, select the Azure API Apps template. The Azure API Apps template is a bare-bones Web API project, including the Azure API Apps SDK NuGet and the Swashbuckle NuGet package, which provides support for dynamic Swagger generation for Web API controllers.
Note the project readme for the API Apps template. It includes helpful links to documentation articles which will describe in greater detail how to write, deploy, debug, and consume Azure API Apps.
Add a custom model and controller that makes use of that model. The screenshot below demonstrates the project’s structure after adding a TodoItem model and TodoController class.
Next, create a new Azure API App in your Azure subscription by using the right-click > Publish feature for Web Projects.
Select the new Microsoft Azure API Apps (Preview) publish target.
The Azure API Apps publishing dialog will open. Click the New button to create a new Azure API App in your Azure subscription.
The Azure API App creation dialog will open. Now, select an existing App Service Plan and Resource Group into which your API App will be deployed. For the purpose of this demonstration, create a new App Service Plan and Resource Group using the convenient options in the dialog.
Once you click OK, the Azure API App provisioning begins. This process can take 1-2 minutes, so you will receive a warning that the provisioning process will complete. Once it completes, execute the publish action once more to publish your code to the API App instance.
The Azure App Service Activity window will reflect the process of creating the new Azure API App in your subscription. You’ll be notified when the creation process has completed.
Once the creation process completes, execute the right-click > Publish gesture on the API App project, and see that the publish settings file is resident and that the code is ready to be published to Azure.
Note: You must execute the publish process twice to ensure your code was published to the newly-provisioned site. The first publish process creates the Azure API App resources in your subscription but does not publish the code once the creation has completed, so you need to execute Publish a second time to deploy your code.
Once you click the Publish button, the API App code will be deployed to your running Azure API App instance.
Viewing the Azure API App Definition in the Azure Management Portal
Following deployment, you can open up the Azure Management Portal in your web browser and navigate to the API App you just deployed. By clicking on the API Definition button in the portal blade for the API App you’ll see the REST API endpoints for your Web API TodoController and for the default ValuesController (unless you deleted the ValuesController.cs file from the project).
Now that the Azure API App has been deployed, we’ll consume it from a Windows Desktop Console application.
One-click API App Client Code Generation in Visual Studio
API App consumption is available for most C# project types, and more will be added in future releases. For the purpose of this demo, we’ll just roll a simple Console application to call the Azure API App to verify it can be consumed. To get started consuming the API add a new project to your solution in Visual Studio.
Next, select the Console Application project template from the dialog and name the project TodoListApiClient.
Once the project is loaded in Visual Studio, right-click the project node and select the Add > Azure API App Client context menu item to open up the Azure API Apps Client generation dialog. Once it opens, select the radio button labeled Download from Microsoft Azure API App and select the TodoListApi API App you just published to Azure. Then, click the OK button. Note, you can also provide a custom namespace for the API App client code if you’d like, but the default namespace is equivalent to the base namespace of your Console Application project.
Once you click the OK button, Visual Studio will pull down the Swagger metadata exposed by your Azure API App and generate client code to make it easier for your Console Application to call your Azure API App endpoints. Once the Azure API App client code is generated, you will see it added to the Console Application project.
Now, open up the Program.cs file in the Console Application project. The generated code makes it easier than ever to use strongly-typed classes and methods to call your Azure API endpoints. The code below will reach out to the API and call its Get method, which returns the list of TodoItems from the API.
Once you hit F5 to launch the Console Application in the Visual Studio debugger, it will call the Azure API running live in the cloud, pull down the list of TodoItems, and display them in the Console window.
It’s never been easier to develop, deploy, and consume data presented via REST APIs. Download the Azure SDK for Visual Studio to try the new tooling for Azure API Apps.
Get in Touch!
Community feedback is imperative to the success of the Visual Studio Web Tools Extensions, and we value your feedback. Feedback is welcome via Send-a-Smile and Send-a-Frown UI within Visual Studio, or you can file a bug through the Visual Studio Connect site. If you have ideas on how to enhance the functionality of the Azure API Apps tools we’ve introduced, please share them on the Visual Studio UserVoice or ASP.NET UserVoice sites. The Azure API Apps resource and tools are in preview as of the 2.5.1 release. We have more to come and welcome your feedback during the preview period. Also, please check the Azure SDK for .NET Release Notes for a full list of features and known issues.
Very exciting to be able to define an API that can easily be consumed by a WebApp or mobile service – very exciting to get hands-on with this…
Question: Does API App usurp API Management? When would one choose API App over Management, or vice versa? Would they both be used together? I am a bit confused as API App seems to have a lot of the same plus much more in many ways than management, but not all.
What are the deciding factors while choosing either to go for Azure App service API or traditional hosting of REST APIs on azure (using either web site or cloud services)? does the generated C# code is supported in silverlight?
Question: Does API App usurp API Management? When would one choose API App over Management, or vice versa?
Quick attempt to address the all of the comments –
Chris – Thanks for being excited about this. We think this is going to make consuming API Apps really easy, and we'd like to extend this functionality to include other REST API endpoints as well..
BB/Shane – No, it doesn't usurp APIM. We have plans to enable API Apps with more APIM functionality. The two will complement one another quite nicely, we think.
Bhushan – That's sort of large question that can be answered via some of the deeper links on the Azure.com site, such as this one: azure.microsoft.com/…/app-service-api-apps-why-best-platform
Ultimately, you can host an ASP.NET Web API in Web Apps, or you can host it in API Apps and harness the power of the API Apps gateway and runtime. The runtime makes it easy to get things like the URIs of services within your Azure resource group and to use the Isolated Storage functionality on the API Apps service side. Not to mention the one large separating factor is that Azure has an API marketplace. You could publish your API into the marketplace so that other developers could make use of it, use your API as a dependency in their own applications or their own APIs.
is there any way to generate the c# client code from the swagger metadata (hosted locally or elsewhere) without deploying it in azure?
Sorry didn't read the answer to chris ." Ignore my question. Thanks.
Suresh2 – no problem whatsoever. Just click that second radio button, input a file, and party on it. If you are interested in how it works, take a look at this GitHub repository, where we've open-sourced the underpinnings of the swagger-to-C# generation: github.com/…/autorest
@Brady Gaster Thanks for more details. Starred the github repository. Looks like the dialog box internally calls "AutoRest.exe -Input swagger.json -Namespace MyNamespace" to produce the c# code. When I played with the Autoreset nuget package, looks like its missing Newtonsoft dependency. Reported in the github isssues. Hope it will get fixed soon. Cheers.
Whencan we have the new Azure app templates on VS 2015 ?
Ali – we plan on having the API Apps tooling in by RTM at the latest.
Hi, in the Channel 9 related video by Scot Hanselman, it was mentioned that there is a convert option so that to easily convert an existing WEB API project into Web API App project.
Do you know where we can find more info for this issue?
Thanks in advance
Stavros – you can learn about the conversion process in the official API Apps documentation on the Azure.com site. Check it out here: azure.microsoft.com/…/app-service-dotnet-create-api-app-visual-studio
wow App Service is amazing stuff, well done MS.
one item I dont quite understand how to implement:
"…Additionally, there is a new consumption system in Visual Studio that provides one-click C# code generation features to make it easier than ever to consume REST APIs without needing to write repetitive HTTP calls or JSON or XML parsing…"
So how for example, could we bring our companies RESTAPI in, and use it / make available, as a (strongly typed) "API App" ?
Who cares about azure man?
Hi,
I am trying the same typical project and I have successfully done all of the aforementioned steps. However, when trying to use the published API App from within a Logic App (within the same resource group, subscription, etc.) I observed the following:
1. You can't add an action that calls the GET method with no params (trying clicking the OK green button, with no effect). Discard changes or choose another controller's method with params.
2. Suppose we have chosen an API method with at least one param. Then the body of the action is empty meaning that you cannot feed the output of this action to any other action (i.e. Twilio or Send Mail, etc.)
However should you run the logic app that contains just this one action, it runs and it produces the correct results.
Second, I tried to publish an already existing API APP (I did the same steps but I just selected the typical WEB API template(instead of the Azure API App template). Then I published the project as an API APP by selecting the Automatic metadata option and everything was ok EXCEPT that this API App could not deliver the definition (click this option on the azure portal) and thus I could not add it as an action inside a Logic App.
I'm seeing the same thing as Stavros Menegos.
I have a custom-made API App, and added it to a logic app. The body is empty, so I can't pass the response to another API app inside the logic app.
This is extremely frustrating… Is anyone seeing this same behavior?
After much googling, I came to this blog post that solved my problem:
blogs.msdn.com/…/logic-app-with-simple-api-app-with-inputs-and-outputs.aspx
Specifically, the part about AddDefaultResponse. I put this in my SwaggerConfig class, published, and restarted the API app in Azure… I now see response output properties.
Why this little detail isn't in the "getting started" guide is beyond me.
That's totally amazing !!!
Woow Amazing !!!
Is there currently a way to use continuous deployment with api apps? I've been playing around with the old and new portals but can't see any way to hook up an api app to vs online.
Angus – You could totally bring in an existing API and add the metadata to it required by the App Service API apps. Then you could deploy it to API Apps and the Swagger metadata emitted would give you the generation functionality in VS. You don't HAVE to get started using the new API Apps template – you can convert an existing Web API and use it in API Apps.
Stavros – i'd like to try to help you offline. Mind emailing me? bradyg AT MSFT. I'd be able to direct you to some folks who understand the logic apps a little more deeply and could provide more information on the integration options.
Yes, you can totally use API Apps and CI. Go into your API App, then click on the API App site (not the gateway) in the resources view. In that blade of the portal you can set up things like GitHub integration, much like you've always been able to do using Azure Websites and GitHub.
I am not able to install Azure SDK 2.5.1. Three is no project template for API preview.
Hi, I've tried this API app, and got some errors. I created an API app with two HTTP GET methods, and publish it to the Azure. Then I followed your tutorial to create a console application and call the two GET method. When I call one of them ,correct response can be received. However, when I call both of them in sequence, an exception of Unauthorized is reported. But I have already set the API app to be public accessible. Do you have any idea about this problem?
Hi. It would be great if we could have the ability to consume the swagger definition within a TypeScript project, something similar to how you referenced it in the above console app.
Hi Brady ,
Facing strange issue with API Apps, here is what I did .
1.created a default azure api app .
2. give it a build
3. created another project
4. on project right click to add the api app client
5. choose the option to select existing swagger file.(browse the file with the project(default file ))
6. got error
.
[Info]Generating client model from swagger model.
[Info]Initializing code generator.
[Info]Successfully initialized CSharp Code Generator 1.0.5584.22489
[Fatal]Invalid swagger 2.0 specification. Missing version property.
Here is the metadata of my json file
{
"$schema": "json-schema.org/…/apiapp.json,
"id": "AzureAD.WebapiApp",
"namespace": "microsoft.com",
"gateway": "2015-01-14",
"version": "1.0.0",
"title": "AzureAD.WebapiApp",
"summary": "This is the set of apis used for the Admin App of AZURE AD",
"author": "GSY",
"endpoints": {
"apiDefinition": "/swagger/docs/v1",
"status": null
}
}
Isn't it possible to add swagger files of existing apps from local project(without getting deployed on azure logic apps) Or is something I am doing wrong .
Hello,
I have installed the latest Azure SDK and tools. But I don't see an option for "Azure API App Client" in my context menu. I tried in Web, Class Library and Console app. I am using Visual Studio 2015 Enterprise RC.
Is there anything I need to do other than just installing SDK and Tools?
bala and a few other folks – The API Apps preview template will be available in the upcoming Visual Studio 2015 RTM release. We weren't able to get it into 2015 previously but it'll be there very, very soon. We're testing the bits pretty regularly now.
Govind – i think we've already covered the issues you had over email but if not, please shoot me an email so we can discuss the issues you're seeing. You can indeed use an existing Swagger file. If you're in a solution with a Web API project (or an API Apps Preview project), you can generate the Swagger, save it to disk, and then use the local file. We're working on making this a LOT easier in the future.
ZeroOne – We are discussing TypeScript. We're also open-sourcing components of the generation framework Visual Studio uses to output code. TypeScript has come up once or twice, as has simplifying the process by which the community can add languages. Would you be interested in contributing to a project like this if it were open? (not a request, just gauging interest in this area)
Does Azure still support publishing web apps to virtual directories of an azure web app? for example
demo.azurewebsites.net/webappA
demo.azurewebsites.net/webappB
Does Azure still support publishing to virtual directories of an azure web app? for example
demo.azurewebsites.net/webappA
demo.azurewebsites.net/webappB
Does Azure still support publishing to virtual directories of an azure web app? something like:
demo.azurewebsites.net/webappA
demo.azurewebsites.net/webappB
Any word on when this tooling will be updated for DNX project templates?
I know this is fairly old, but it is none the less cool. Just starting to figure this Azure stuff out. I will say that code snippets rather than screen shots would have made this easier to play with – copy and paste, you know. | https://blogs.msdn.microsoft.com/visualstudio/2015/03/24/introducing-the-azure-api-apps-tools-for-visual-studio-2013/ | CC-MAIN-2018-05 | refinedweb | 3,360 | 72.36 |
PingSweeper
- Category: CodeReview
- 450 points
- Solved by JCTF Team
Description
Solution
Didn't solve this challenge in the intentend way (SQL injection), but the challenge's category is "code review" so any vulnerability we find is fair game, right? :-)
We guessed that we need to somehow send an OTP to the webapp which will be accepted in order to get back the flag, and indeed and the code for the endpoint "/api/confimOtm" reads:
const express = require('express'); const router = express.Router(); const orm = require('../models/index'); const config = require("../config/config"); const crypto = require('crypto'); const endpointsModel = orm.import('../models/endpoints'); const aes256 = require('aes256'); const fetch = require('node-fetch'); const key = config.AES.key; const adminPhone = config.adminPhone; const flag = config.flag; ... ... router.post('/confirmOtp', function (req, res) { try { // Global, use per-user cookie instead //orm.query('SELECT @OTP;').then(otp => console.log(otp)); const currentStamp = Date.now(); const otp = req.body.otp; const encrypted = req.cookies.otpStamp; const decrypted = aes256.decrypt(key, encrypted); const decryptedOtp = decrypted.slice(0, 8); const decryptedStamp = parseInt(decrypted.slice(8), 10); if (currentStamp >= decryptedStamp) { res.status(500).json({ error: 'Session expired' }); } else if (otp !== decryptedOtp) { res.status(500).json({ error: 'Incorrect OTP' }); } else { res.json({ flag }); } } catch (e) { res.status(500).json({ error: 'Bad data' }); } });
Lets walk the confirmation method logic:
- Gets the current millisecond epoch time, stores in
currentStamp.
- Gets the otp we posted in the request body, storse in
otp.
- Gets the otpStamp cookie:
- Decrypt it through
aes256module using a secret key getting a plaintext.
- The first 8 bytes of the plaintext is considered the
decryptedOtp.
- All the rest bytes in the plaintext from the 9th byte onward is parsed as int of base 10 and called
decryptedStamp.
- If the currentStamp is greater than decryptedStamp return 'Session expired' error.
- If the otp is not equal to the decryptedOtp return 'Incorrect OTP' error.
- Return the flag.
- If any error occur in any pervious step return 'Bad data' error.
We need to pass only 2 if statements - timestamp compare and otp compare, and also we cannot raise any exception, let's find out a way to break this and get the flag.
Looking at
aes256 code we find out that:
- Ciphertext is base64 encoded.
- CTR mode is used - the ciphertext can be of any length of bytes and not only a multiple of a blocksize of AES.
- The decrypt function throws if it gets less then 17 bytes and since 16 bytes is the iv it means that at least one byte of "actual" ciphertext is needed to be provided.
We found the first mistake: the
otpStamp cookie is not integrity protected! This allow us to craft this cookie at will. Side note: CTR is also malleable but we will not use this useful property here.
Keeping our new power in mind we can now look at the first if statement, we look at parseInt at MDN which tells us that we might get a
NaN.
If we can get
decryptedStamp to be a NaN we will pass the first if statement as whatever number
currentStamp will be it will NOT be greater or equal to
NaN.
We check in browser console:
> parseInt('', 10) NaN
We conclude that the second mistake that this code is missing a check that
decryptedStamp is an actual number and not
NaN.
The last if statement is just comparing the otp from the posted form against the
decryptedOtp as a byte string. There is NO check that the otp length is 8 bytes!!!
This is the last mistake we needed!
We can just send 1 byte of ciphertext and send an otp of one byte of '0'. We will need to do this maximum of 256 requests as we don't know the relevant keysteam byte which is xor'ed with the provided byte through our cookie.
The expliot code is:
import requests import sys from base64 import b64encode from urllib.parse import quote url = "" headers = { "Accept": "*/*", "Host": "pingsweeper.appsecil.ctf.today", "Origin": "" } s = requests.Session() s.headers = headers def confirm(otp): r = s.post(url_confirm, data={"otp": otp}) if r.status_code == 200: print(r.json()['flag']) print() sys.exit(0) def setOTP(iv, code, ts): otpCookie = iv + code + ts s.cookies.set('otpStamp', quote(b64encode(otpCookie)), domain='pingsweeper.appsecil.ctf.today') def setUuid(uuid): s.cookies.set('uuid', uuid, domain='pingsweeper.appsecil.ctf.today') try: setUuid('b3f463bf-9675-498e-befd-10213a55931a') iv, code, ks = b'\x00' * 16, b'', b'' otp = '' for c in range(255): setOTP(iv, bytes([c]), ks) confirm('0') print('Failed to get the flag') except KeyboardInterrupt: pass
Running this code we get:
AppSec-IL{SH0u1d_H4v3_US3d_4_pR3p4R3d_ST4Tm3Nt}
Which indeed confirm, no pan intended, that we solved this challenge not in the intended way.
Might have been
Validated your inputs! and
Protect your cookies integrity!. Ta ta. | https://jctf.team/AppSec-IL-2020/PingSweeper/ | CC-MAIN-2022-33 | refinedweb | 802 | 58.99 |
Premier IT Outsourcing and Support Services within the UK
Problem, Formatting or Query - Send Feedback
Internet Engineering Task Force (IETF) S. Bosch Request for Comments: 8579 Open Xchange Oy Category: Standards Track May 2019 ISSN: 2070-1721
Sieve Email Filtering: Delivering to Special-Use Mailboxes
Abstract a mailbox identified solely by a special-use 8579 Sieve: Special-Use Mailboxes May 2019
Table of Contents
1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 2 2. Conventions Used in This Document . . . . . . . . . . . . . . 3 3. . . . . . . . . . . . . . . . . . . . . . 10 9. References . . . . . . . . . . . . . . . . . . . . . . . . . 10 9.1. Normative References . . . . . . . . . . . . . . . . . . 10 9.2. Informative References . . . . . . . . . . . . . . . . . 11 Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . 11 Author's Address . . . . . . . . . . . . . . . . . . . . . . . . 12
1. Introduction
Commonly, several mailboxes in an IMAP message store [IMAP] have a special use. For example, there can be a special-use mailbox for storing the user's draft messages, for keeping copies of sent messages, and for collecting spam messages that were classified as such has no means to identify a mailbox with a particular special-use Standards Track [Page 2] RFC 8579 Sieve: Special-Use Mailboxes May 2019
This document defines an extension to the Sieve mail filtering language that adds the ability to freely access mailbox special-use attributes. It adds a test called "specialuse_exists" that checks 1) whether a special-use attribute is assigned for a particular mailbox or 2) whether any of the user's personal mailboxes have a special-use attribute assigned. It also adds the ability to file messages into a personal mailbox identified by a particular special-use attribute rather than the mailbox's name. This is achieved using the new ":specialuse" argument for the "fileinto" command [SIEVE].
2. Conventions Used in This Document
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 [KEYWORDS] [KEYWORDS-UPD] when, and only when, they appear in all capitals, as shown here.
Conventions for notations are as described in Section 1.1 of [SIEVE], including use of the "Usage:" label for the definition of the action and the syntax of tagged arguments.-attrs: string-list>
If the "mailbox" string argument is omitted, the "specialuse_exists" test yields "true" if all of the following statements are true for each of the special-use attributes listed in the special-use-attrs argument:
a. At least one mailbox exists in the user's personal namespace [NAMESPACE] that has that particular special-use attribute assigned.
b. That mailbox allows the user in whose context the Sieve script runs to "deliver" messages into it.
Bosch Standards Track [Page 3] RFC 8579 Sieve: Special-Use Mailboxes May 2019
If the mailbox argument is specified, the "specialuse_exists" test yields "true" if all of the following statements are true:
a. The indicated mailbox exists.
b. That mailbox allows the user in whose context the Sieve script runs to "deliver" messages into it.
c. That mailbox has all of the special-use attributes listed in the, the following IMAP protocol examples show a sequence of [IMAP] commands that a client could send to perform an assessment without Sieve that is equivalent to the "specialuse_exists" test. attributes in the two returned personal namespaces (this extended LIST command requires the LIST- attributes assigned. This way, it can determine whether messages can be saved to any of those. In this example, an "\Archive" special-use mailbox is sought:
Bosch Standards Track [Page 4] RFC 8579 Sieve: Special-Use Mailboxes May 2019
C: A03 MYRIGHTS Archive/Default S: * MYRIGHTS Archive/Default lrwsip S: A03 OK Myrights completed
The MYRIGHTS response indicates-attr: string>] <mailbox: string>
Normally, the "fileinto" command delivers the message in the mailbox specified using its positional mailbox argument, which is the name of the mailbox. However, if the optional ":specialuse" argument is also specified, the "fileinto" command first checks whether a mailbox exists in the user's personal namespace [NAMESPACE] with the specified special-use attribute assigned to it. If that is the case, that special-use mailbox is used for delivery instead. If there is no such mailbox or if the specified special-use attribute is unknown to the implementation in general, the "fileinto" action proceeds as it would without the ":specialuse" argument.
Summarizing, if the ":specialuse" argument is specified, the "fileinto" command deals with two mailboxes that may or may not exist and may, in fact, be equal:
o A special-use mailbox in the user's personal namespace, which has at least the special-use attribute attribute specified with the ":specialuse" argument conforms to the "use-attr" syntax described in Section 6 of RFC 6154 [SPECIAL-USE]. Implementations SHOULD handle an invalid special-use attribute in the same way as an invalid mailbox name is handled. The string parameter of the ":specialuse" argument is not a constant string, which means that variable substitutions are allowed when the "variables" extension [VARIABLES] is active. In that case, the syntax of the special-use attribute is only verified at runtime.
Bosch Standards Track [Page 5] RFC 8579 Sieve: Special-Use Mailboxes May 2019
If neither the special-use mailbox nor the default mailbox exists, the "fileinto" action MUST proceed exactly as it does in case the ":specialuse" argument is absent and the mailbox named by its positional argument does not exist. The various options for handling this situation are described in Section 4.1 of RFC 5228 [SIEVE].
More than one mailbox in the user's personal namespace can have a particular special-use attribute attribute are assigned remains unchanged, implementations SHOULD ensure that the mailbox choice is made consistently, so that the same mailbox is used every time. Conversely, the chosen mailbox MAY change once the assignments of the special-use attribute that are relevant for the mailbox choice are changed (usually by user interaction).
If delivery to the special-use mailbox fails for reasons not relating to its existence, the Sieve interpreter MUST NOT subsequently attempt delivery in the indicated default mailbox as a fallback. 5.
Bosch Standards Track [Page 6] RFC 8579 Sieve: Special-Use Mailboxes May 2019
If the server implementation supports the CREATE-SPECIAL-USE capability [SPECIAL-USE] for IMAP (i.e., it allows assigning special- use attributes to new mailboxes), it SHOULD assign the special-use attribute specified with the ":specialuse" argument to the newly created mailbox.
4.2. Equivalent IMAP Operations
To clarify, the following IMAP protocol examples show a sequence of [IMAP] commands that a client could send to perform an action without Sieve that is equivalent to the "fileinto" action with the ":specialuse" argument. The following Sieve script is assumed:
require "fileinto"; require "special-use";
fileinto :specialuse "\\Archive" "INBOX/Archive";
First, the client proceeds as in Section 3.1 to find out whether the indicated special-use attribute: INBOX/Archive
In this example, the default mailbox does not exist either. In that case, the client MAY create the default mailbox and assign the indicated special-use attribute to it:
C: A05 CREATE INBOX/Archive (USE (\Archive)) S: A05 OK Create completed
Bosch Standards Track [Page 7] RFC 8579 Sieve: Special-Use Mailboxes May 2019
Finally, the client completes the delivery:
C: A06 APPEND INBOX/Archive {309} S: + OK C: Date: Wed, 18 Jul 2018 22:00:09 +0200 C: From: mooch@owatagu.siam.example C: To: Fred Foobar <foobar@Blurdybloop.example> C: Subject: afternoon meeting C: Message-Id: exists. In that case, a mailbox called "Spam" is created, and the message is stored there. Additionally, the "\Junk" special-use attribute may be assigned to it.
require "fileinto"; require "special-use"; require "mailbox";
fileinto :specialuse "\\Junk" :create "Spam";
Bosch Standards Track [Page 8] RFC 8579 Sieve: Special-Use Mailboxes May 2019 special-use mailbox to the user's personal namespace. First, this avoids the need to search the entire mail storage for mailboxes that have a particular special-use attribute assigned. This could put undue load on the system, while shared special-use mailboxes are deemed of limited use with the currently defined special-use attributes. Secondly, it prevents security concerns with shared mailboxes that have special-use attributes assigned that apply to all users. Searching the entire mail storage for special-use mailboxes could lead to messages unexpectedly or even maliciously being filed to shared mailboxes.
This restriction could be lifted for particular future special-use attributes, but such new attributes should have a clear application for shared mailboxes, and the security concerns should be considered carefully.
Bosch Standards Track [Page 9] RFC 8579 Sieve: Special-Use Mailboxes May 2019
8. IANA Considerations
IANA has registered the Sieve extension specified in this document in the "Sieve Extensions" registry at < sieve-extensions>:
Capability name: special-use Description: adds a test for checking whether an IMAP special-use attribute is assigned for a particular mailbox or any mailbox; also adds the ability to file messages into a mailbox identified solely by a special-use attribute. RFC number: RFC 8579 Contact address: Sieve discussion list <sieve@ietf.org>
9. References
9.1. Normative References
[IMAP-METADATA] Daboo, C., "The IMAP METADATA Extension", RFC 5464, DOI 10.17487/RFC5464, February 2009, <>.
, <>.
[NAMESPACE] Gahrns, M. and C. Newman, "IMAP4 Namespace", RFC 2342, DOI 10.17487/RFC2342, May 1998, <>.
[SIEVE] Guenther, P., Ed. and T. Showalter, Ed., "Sieve: An Email Filtering Language", RFC 5228, DOI 10.17487/RFC5228, January 2008, <>.
[SIEVE-MAILBOX] Melnikov, A., "The Sieve Mail-Filtering Language -- Extensions for Checking Mailbox Status and Accessing Mailbox Metadata", RFC 5490, DOI 10.17487/RFC5490, March 2009, <>.
Bosch Standards Track [Page 10] RFC 8579 Sieve: Special-Use Mailboxes May 2019
[SPECIAL-USE] Leiba, B. and J. Nicolson, "IMAP LIST Extension for Special-Use Mailboxes", RFC 6154, DOI 10.17487/RFC6154, March 2011, <>.
[VARIABLES] Homme, K., "Sieve Email Filtering: Variables Extension", RFC 5229, DOI 10.17487/RFC5229, January 2008, <>., <>.
Acknowledgements
Thanks to Stan Kalisch, Barry Leiba, Alexey Melnikov, Ken Murchison, and Ned Freed for reviews and suggestions.
Thanks to the authors of RFC 5490 [SIEVE-MAILBOX], from which some descriptive text in this document is borrowed.
Bosch Standards Track [Page 11] RFC 8579 Sieve: Special-Use Mailboxes May 2019
Author's Address
Stephan Bosch Open Xchange Oy Lars Sonckin kaari 12 Espoo 02600 Finland
Bosch Standards Track [Page 12] | https://wiki.gen.net.uk/doku.php/rfc:rfc8579?s%5B%5D=implementation | CC-MAIN-2019-47 | refinedweb | 1,691 | 50.16 |
node-fast-ratelimitnode-fast-ratelimit
Fast and efficient in-memory rate-limit, used to alleviate most common DOS attacks.
This rate-limiter was designed to be as generic as possible, usable in any NodeJS project environment, regardless of wheter you're using a framework or just vanilla code.
Rate-limit lists are stored in a native hashtable to avoid V8 GC to hip on collecting lost references. The
hashtable native module is used for that purpose.
Who uses it?Who uses it?
👋 You use fast-ratelimit and you want to be listed there? Contact me.
How to install?How to install?
Include
fast-ratelimit in your
package.json dependencies.
Alternatively, you can run
npm install fast-ratelimit --save.
Note: ensure you have a C++11 compiler available. This allows for node-gyp to build the
hashtable dependency that
fast-ratelimit depends on.
How to use?How to use?
The
fast-ratelimit API is pretty simple, here are some keywords used in the docs:
ratelimiter: ratelimiter instance, which plays the role of limits storage
namespace: the master ratelimit storage namespace (eg: set
namespaceto the user client IP, or user username)
You can create as many
ratelimiter instances as you need in your application. This is great if you need to rate-limit IPs on specific zones (eg: for a chat application, you don't want the message send rate limit to affect the message composing notification rate limit).
Here's how to proceed (we take the example of rate-limiting messages sending in a chat app):
1. Create the rate-limiter1. Create the rate-limiter
The rate-limiter can be instanciated as such:
var FastRateLimit = FastRateLimit;var messageLimiter =threshold : 20 // available tokens over timespanttl : 60 // time-to-live value of token bucket (in seconds);
This limiter will allow 20 messages to be sent every minute per namespace. An user can send a maximum number of 20 messages in a 1 minute timespan, with a token counter reset every minute for a given namespace.
The reset scheduling is done per-namespace; eg: if namespace
user_1 sends 1 message at 11:00:32am, he will have 19 messages remaining from 11:00:32am to 11:01:32am. Hence, his limiter will reset at 11:01:32am, and won't scheduler any more reset until he consumes another token.
2. Allow/disallow request based on rate-limit2. Allow/disallow request based on rate-limit
On the message send portion of our application code, we would add a call to the ratelimiter instance.
2.2. Use asynchronous API (Promise catch/reject)2.2. Use asynchronous API (Promise catch/reject)
// This would be dynamic in your application, based on user session data, or user IPnamespace = "user_1";// Check if user is allowed to send messagemessageLimiter;
2.1. Use synchronous API (boolean test)2.1. Use synchronous API (boolean test)
// This would be dynamic in your application, based on user session data, or user IPnamespace = "user_1";// Check if user is allowed to send messageif messageLimiter === true// Consumed a token// Send messagemessage;else// consumeSync returned false since there is no more tokens available// Silently discard message
Notes on performanceNotes on performance
This module is used extensively on edge WebSocket servers, handling thousands of connections every second with multiple rate limit lists on the top of each other. Everything works smoothly, I/O doesn't block and RAM didn't move that much with the rate-limiting module enabled.
On one core / thread of 2.5 GHz Intel Core i7, the parallel asynchronous processing of 40,000 namespaces in the same limiter take an average of 300 ms, which is fine (7.5 microseconds per operation).
Why not using existing similar modules?Why not using existing similar modules?
I was looking for an efficient, yet simple, DOS-prevention technique that wouldn't hurt performance and consume tons of memory. All proper modules I found were relying on Redis as the keystore for limits, which is definitely not great if you want to keep away from DOS attacks: using such a module under DOS conditions would subsequently DOS Redis since 1 (or more) Redis queries are made per limit check (1 attacker request = 1 limit check). Attacks should definitely not be allieviated this way, although a Redis-based solution would be perfect to limit abusing users.
This module keeps all limits in-memory, which is much better for our attack-prevention concern. The only downside: since the limits database isn't shared, limits are per-process. This means that you should only use this module to prevent hard-attacks at any level of your infrastructure. This works pretty well for micro-service infrastructures, which is what we're using it in. | https://www.npmjs.com/package/@anchorchat/fast-ratelimit | CC-MAIN-2020-05 | refinedweb | 780 | 54.32 |
Hi there,
I have a file with unicode characters I used url decoder code below on a large file, but what is funny is that it doesn't decode some lines,but when I use the code on a file with just that line it decodes it correctly.
import urllib.parse for lines in open('mytxt1.txt'): s = urllib.parse.unquote(lines,encoding='latin-1') with open ('outtxt1.txt','a') as f1: f1.write(s) f1.close()
for example login=bob%40%3CSCRipt%3Ealert%28Paros%29%3C%2FscrIPT%3E.parosproxy.org is not decoded,
but when using just one line i get login=bob@<SCRipt>alert(Paros)</scrIPT>.parosproxy.org | https://www.daniweb.com/programming/software-development/threads/498185/url-decoder | CC-MAIN-2018-13 | refinedweb | 110 | 51.95 |
Python Programming, news on the Voidspace Python Projects and all things techie.
Stuff I Agree With: Debuggers and Testing
An interesting post on debuggers and testing: Debugger Support Considered Harmful. It says exactly what I mean about testing:
One deleted comment stated that tests were for finding out when things went wrong, and debuggers were for fixing them...
Tests are absolutely not for checking to see if things went wrong. They are for articulating what code should do, and proving that code does it.
This is why test first is so radically different from test afterwards (unless you usually write your specification after the code...).
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2007-11-29 21:03:53 | |
Categories: General Programming
Consolidating Digital Identity, Web apps & onaswarm
Jon Udell has written a blog entry on digital identity: Your Winnings Sir.
The basic problem is that 'content we create' (our identity online) is distributed all across the internet, on various sites and possibly multiple blogs, with no way of connecting them all together. One solution of course is to give all your data to one company, google aren't doing badly on this score..
This is one of the reasons I like OpenID. I try to keep most of my content on Voidspace. OpenID allows me to use this domain as my identity. It isn't the whole answer though, I also use services like del.icio.us and facebook.
Of course it is perfectly possible to mash all these together - but thankfully someone has done it so that I don't have to.
Onaswarm is a new (beta of course - and built with Python which is even better) service that mashes up blogs (or anything with RSS), del.icio.us, facebook, Pownce (or twitter if you prefer) plus lots more. It's given me a renewed enthusiasm for Pownce as well:
Onaswarm has an RPC API, so it should be possible to build some nice things on top of it. I have a couple of invites for it, plus stacks of invites for Pownce.
The desktop client for Pownce is really nice. It has got some flack but I really like it. It is written with Adobe AIR. I've long said that the line between desktop and web apps needs to be blurred, and Pownce does it very well. Another web/desktop app is the one used by Emusic: EMusic Remote. It is a wrapper around Firefox with a custom sidebar. You login to your account through the 'website' and the app is integrated with the download manager from which you can launch songs, create playlists and configure your media library sync settings. It's very well done, is created with Mozilla's XULRunner and has Mac, Windows and Linux versions.
Other random guff:
- Just added another gig of memory to my Macbook Pro (up to the max of 3gig now) - the upgrade was monumentally easy
- The delivery date for my eeePC got pushed back so I cancelled. They are available on ebay but I don't think I really need it.
- Just watched the new futurama movie - it was ok. Nice cheesy ending.
- The Resolver public beta will be coming out really soon now. We've done a lot of work since I last updated you on it, expect more details when it finally happens. Robert Scoble is coming to London next weekend. I've arranged to meetup and it looks like we might be doing a ScobleShow on Resolver which will coincide nicely with the beta.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2007-11-28 23:38:32 | |
Categories: Computers, General Programming, Work
Functional Programming on .NET
The part of my presentation at DDD that I enjoyed the most, was talking briefly about functional programming (demonstrating multiple programming paradigms with IronPython).
First class functions and closures:
def adder(y):
return x + y
return adder
>>> addThree = makeAdder(3)
>>> addTwo = makeAdder(2)
>>> addThree(2)
5
>>> addTwo(2)
4
A similar example but generalising for partial functional application:
return x + y
def partial(func, x):
def inner(y):
return func(x, y)
return inner
>>> addThree = partial(add, 3)
>>> addThree(2)
5
partial binds a function that takes two arguments to the first argument that you pass. The function returned only takes one argument. This is basically the mechanism by which methods fetched from an instance have self bound as the first argument.
This reminds me of one of the things that happened at TechEd that I haven't blogged about yet. I met Robert Pickering (who is a really nice guy - I doubt I can persuade him to work at Resolver though!). He works for Lexifi, who are a French company doing commercial development with OCaml (and their program - although very different - is working in the same problem domain as Resolver).
He is also the author of a book on F#. F# is a functional programming language for .NET (heavily influenced by OCaml) that started as a research project, but was recently promoted to 'supported product':
Robert gave me a copy of the book. I'd love to learn a functional programming language and F# looks like a good choice, unfortunately I won't have time until I finish the book.
There is a nice summary of some of the features in F# on Frank Sommers' Blog. It includes (which I didn't know):
#light: The #light directive in F# allows code to omit begin...end keywords and some other tokens, and instead relies on indentation to indicate nesting. This is similar to languages like Python, and enables the same kind of syntactic lightness that programs in these languages enjoy.
Cool.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2007-11-28 23:03:58 | |
Categories: General Programming, Python, Writing
Developer Day 6
On Saturday I was at Developer Day 6, a .NET community event in Reading (the Microsoft corporate bunkers in the UK).
I'm now starting to get to know some of the folk who come to these events (the 450 places at DDD were all filled with 24hours of registration opening!). Coming from the free-love hippy environs of the open source community, it is nice to find that there are some good people even amongst the ravening capitalist confines of Microsoft land.
I did a presentation on 'Dynamic Languages on .NET', unsurprisingly with a focus on IronPython:
You can find most of the resources mentioned in the talk from the IronPython section of my website: IronPython Stuff.
At Mix I was asked to talk on IronPython and Silverlight, and the (personal) feedback from there was that people wanted to know more about IronPython itself and why they should even care about dynamic languages. An hour is a useful amount of time to be able to deliver a real message [1], and although some parts of the talk could have been better I think it went well.
As well as talking about dynamic languages I demoed Resolver, which seemed to go down pretty well. I certainly made some useful contacts through the talk. I'll be interested to see if any 'feedback' makes it way back to me (which it didn't directly from Mix).
By the way, a special thanks to Zi Makki for all his efforts, not just for his part in organising the event - but particularly for the geek dinner he arranged afterwards.
I particularly enjoyed the talk by Dave Verwer on IronRuby. He basically uses these talks as a propaganda opportunity for Ruby, and everytime I go to one (this was my second) I learn a bit more about Ruby. He copes very well with my interruptions and questions.
There are some photos from the day and more blog entries: Mike Hadlow, Paul Lockwood, Ben Hall and Richard Fennell.
I have no more talks planned for this year (well - except possibly a lightning talk on rest2web at the next Python London meetup), which is a great relief and means I can finally concentrate on the book (Manning will be very pleased!).
Coming up next year are PyCon and RuPy. If you have a login for the PyCon site you can see the summary of all 140 (-ish) talk proposals. As usual there are some very interesting ones. There is one that looks like it has been submitted by Jim Hugunin and it even mentions Resolver's C-Extensions for IronPython project.
There is also a talk proposed on Python.NET. I hope this talk gets accepted as it is a project that deserves to be more widely known than it is.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2007-11-26 14:11:35 | |
Categories: Writing, IronPython, General Programming
We're Going to Try Agile Programming
snigger
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2007-11-26 14:08:51 | |
Categories: Fun, General Programming
Ebay Geek Clearout
I've had a clearout of some of my unneeded geek toys.
- Dirk Gently's Holistic Detective Agency: 6 Audio CDs
- The Long Dark Tea-Time of the Soul: Audiobook 6 CDs
- Smartphone: Nokia N70 Mobile Phone. Boxed & Unlocked
- HTC Touch Mobile: New PDA Camera Phone Boxed Unlocked
- LG U8360 Mobile Phone: Boxed & Unlocked
- Apple Black Video iPod 30Gig mp3 Player with Case
- Microsoft Windows Vista Ultimate
- PNY NVIDIA Quadro NVS 280, (64 MB) PCI Graphics Card
- Dell Axim X5 PocketPC PDA with TOMTOM GPS + Extras
Putting those online wasn't the most fun way to spend Sunday evening, but I've been putting it off for a while. Ho hum.
I'm selling my books via Amazon Marketplace as an experiment
It's not all good news on the gadget clearing front though. I couldn't resist the Asus eeePC [1]. For some pictures and a review, Smurf on Spreadsheets convinced me. The best is the picture of the eee on top of a Sony Vaio.
And yes, I know that someone installed Mac OS on one, and about the GPL Violation scandal [2]. I don't know when mine will arrive, but it will be nice to finally have a Linux box.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2007-11-26 00:34:03 | |
Categories: Computers, Life
Archives
This work is licensed under a Creative Commons Attribution-Share Alike 2.0 License.
Counter... | http://www.voidspace.org.uk/python/weblog/arch_d7_2007_11_24.shtml | CC-MAIN-2014-42 | refinedweb | 1,752 | 70.73 |
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Introducing Inheritance4:28 with Ben Deitch
In this video we'll learn what inheritance is and use it for the first time!
Dog dog = new Dog(); dog.makeSound();
[MUSIC] 0:00
At this point, we've seen how to create objects with 0:09
fields representing their properties and methods representing their actions. 0:11
In this course, we'll see how to do a lot more with objects by using inheritance. 0:16
Inheritance is actually a pretty simple concept. 0:22
Let's say we have a class called A, and 0:25
this class has a couple fields and a method. 0:28
Now let's say we have another class, B, 0:31
which is exactly like A except it has an extra field and an extra method. 0:33
It's a lot of extra code, and we're definitely repeating ourselves. 0:39
But with inheritance, we can clean things up by just saying that B inherits from A, 0:43
which we do with the extends key word. 0:49
So this code is exactly the same as before, just much shorter. 0:52
Now, in most cases, the class names will make a lot more sense than just A and B. 0:57
But using these simple names, let's us focus on what inheritance actually is. 1:02
A class using another class as its foundation. 1:08
All right, that's enough theory. 1:11
Let's do some practice in a new project. 1:14
Let's pick Create New Project, then click Next, 1:17
select our Command Line App template, hit Next again. 1:22
And for the project name, let's just name it, inheritance, and click Finish. 1:27
Awesome. 1:35
Now, just to make things a little easier for you to see, 1:36
I'm going to put my IntelliJ into full screen mode, okay. 1:40
Now, right below the main class let's create a new class named animal. 1:44
Typically we'd put each class in its own file. 1:51
But since we're learning, it'll be nice to have everything on one page. 1:54
Let's type class Animal, and add the brackets. 1:59
And I'll go ahead and hide the project pane as well. 2:04
Also, note that if we try to make our animal class public, we'll get an error. 2:06
While you can have more than one class in a file, 2:13
all public classes need their own files. 2:17
Al lright, inside this class lets add a string 2:21
field named sound and set it equal to an empty string. 2:26
Then lets add a void method called makeSound and 2:34
use the S-O-U-T shortcut, 2:38
or sout to have it print out the sound variable. 2:41
Nice. 2:47
Next let's make a dog class that will bark when we call the makeSound method. 2:48
But first, let's head up to the main method and delete the comment. 2:54
Then let's copy and paste in the code from the teacher's notes. 2:59
Once we're done with the Dog class, we should be able to run this program, and 3:03
see that our dog has said bark. 3:07
So right below our Animal class, let's create our Dog class by using inheritance. 3:09
So actually, why don't you take a stab at it first? 3:14
Remember, the key word is extends. 3:18
Okay, pause me, and when you come back, I'll show you how I solved it. 3:22
Did you get it? 3:26
Here's how I did it. 3:28
First, create the Dog class, and make it extend from animal. 3:30
Then, inside the Dog class, we'll add a constructor, 3:42
Dog( ) and then the brackets, and inside the constructor, 3:48
we'll set sound = "bark" and add the semicolon. 3:54
Finally, if we run the program, 4:00
We'll see that our dog says bark. 4:06
Awesome job learning about Inheritance. 4:09
Being able to use another class as a foundation for 4:12
new one is a real time saver. 4:16
And it's not hard to imagine how you could start with something simple and 4:18
build your way up to something really complicated. 4:22
More on that in the next video. 4:25 | https://teamtreehouse.com/library/introducing-inheritance | CC-MAIN-2022-33 | refinedweb | 798 | 81.12 |
inet_ntop (3p)
PROLOGThis manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
NAMEinet_ntop, inet_pton — convert IPv4 and IPv6 addresses between binary and text form
SYNOPSIS
#include <arpa/inet.h>
const char *inet_ntop(int af, const void *restrict src, char *restrict dst, socklen_t size); int inet_pton(int af, const char *restrict src, void *restrict dst);
DESCRIPTIONThe). If the af argument of inet_pton() is AF_INET, the src string shall be in the standard IPv4 dotted-decimal form:
ddd.ddd.ddd.ddd
- 1.
- The preferred form is "x:x:x:x:x:x:x:x", where the 'x's are the hexadecimal values of the eight 16-bit pieces of the address. Leading zeros in individual fields can be omitted, but there shall be at least one numeral in every field.
- 2.
- A string of contiguous zero fields in the preferred form can be shown as "::". The "::" can only appear once in an address. Unspecified addresses ("0:0:0:0:0:0:0:0") may be represented simply as "::".
- 3.
-).
- Note:
- A more extensive description of the standard representations of IPv6 addresses can be found in RFC 2373.
RETURN VALUEThe inet_ntop() function shall return a pointer to the buffer containing the text string if the conversion succeeds, and NULL otherwise, and set errno to indicate the error. The inet_pton() function shall return 1 if the conversion succeeds, with the address pointed to by dst in network byte order. It shall return 0 if the input is not a valid IPv4 dotted-decimal string or a valid IPv6 address string, or −1 with errno set to [EAFNOSUPPORT] if the af argument is unknown.
ERRORSThe inet_ntop() and inet_pton() functions shall fail if:
- EAFNOSUPPORT
- ENOSPC
- The size of the inet_ntop() result buffer is inadequate. | https://readtheman.io/pages/3p/inet_ntop | CC-MAIN-2019-09 | refinedweb | 317 | 51.78 |
Polymorphism is the ability to perform an action on an object regardless of its type. This is generally implemented by creating a base class and having two or more subclasses that all implement methods with the same signature. Any other function or method that manipulates these objects can call the same methods regardless of which type of object it is operating on, without needing to do a type check first. In object-oriented terminology when class X extend class Y , then Y is called super class or base class and X is called subclass or derived class.
class Shape: """ This is a parent class that is intended to be inherited by other classes """ def calculate_area(self): """ This method is intended to be overridden in subclasses. If a subclass doesn't implement it but it is called, NotImplemented will be raised. """ raise NotImplemented class Square(Shape): """ This is a subclass of the Shape class, and represents a square """ side_length = 2 # in this example, the sides are 2 units long def calculate_area(self): """ This method overrides Shape.calculate_area(). When an object of type Square has its calculate_area() method called, this is the method that will be called, rather than the parent class' version. It performs the calculation necessary for this shape, a square, and returns the result. """ return self.side_length * 2 class Triangle(Shape): """ This is also a subclass of the Shape class, and it represents a triangle """ base_length = 4 height = 3 def calculate_area(self): """ This method also overrides Shape.calculate_area() and performs the area calculation for a triangle, returning the result. """ return 0.5 * self.base_length * self.height def get_area(input_obj): """ This function accepts an input object, and will call that object's calculate_area() method. Note that the object type is not specified. It could be a Square, Triangle, or Shape object. """ print(input_obj.calculate_area()) # Create one object of each class shape_obj = Shape() square_obj = Square() triangle_obj = Triangle() # Now pass each object, one at a time, to the get_area() function and see the # result. get_area(shape_obj) get_area(square_obj) get_area(triangle_obj)
We should see this output:
None
4
6.0
What happens without polymorphism?
Without polymorphism, a type check may be required before performing an action on an object to determine the correct method to call. The following counter example performs the same task as the previous code, but without the use of polymorphism, the
get_area() function has to do more work.
class Square: side_length = 2 def calculate_square_area(self): return self.side_length ** 2 class Triangle: base_length = 4 height = 3 def calculate_triangle_area(self): return (0.5 * self.base_length) * self.height def get_area(input_obj): # Notice the type checks that are now necessary here. These type checks # could get very complicated for a more complex example, resulting in # duplicate and difficult to maintain code. if type(input_obj).__name__ == "Square": area = input_obj.calculate_square_area() elif type(input_obj).__name__ == "Triangle": area = input_obj.calculate_triangle_area() print(area) # Create one object of each class square_obj = Square() triangle_obj = Triangle() # Now pass each object, one at a time, to the get_area() function and see the # result. get_area(square_obj) get_area(triangle_obj)
We should see this output:
4
6.0
Important Note
Note that the classes used in the counter example are "new style" classes and implicitly inherit from the object class if Python 3 is being used. Polymorphism will work in both Python 2.x and 3.x, but the polymorphism counterexample code will raise an exception if run in a Python 2.x interpreter because type(input_obj).name will return "instance" instead of the class name if they do not explicitly inherit from object, resulting in area never being assigned to. | https://riptutorial.com/python/example/17997/polymorphism | CC-MAIN-2019-30 | refinedweb | 597 | 54.93 |
This notebook is inspired by Nate Silver's recent article on How to Tell Someone's Age When All you Know is Her Name. It allows one to (almost) replicate the analysis done in the article, and provides more extensive features. I have done similar work using R, and you can find it here.
We will uses four primary datasets.
We will download each of these datasets and process them to get them analysis ready.
%matplotlib inline import re import urllib from zipfile import ZipFile from path import path import numpy as np import pandas as pd from scipy.interpolate import interp1d import matplotlib.pyplot as plt import seaborn as sns from ggplot import *
/Users/ramnathv/anaconda/lib/python2.7/site-packages/pytz/__init__.py:29: UserWarning: Module argparse was already imported from /Users/ramnathv/anaconda/lib/python2.7/argparse.pyc, but /Users/ramnathv/anaconda/lib/python2.7/site-packages is being added to sys.path from pkg_resources import resource_stream
urllib.urlretrieve("", "names.zip") zf = ZipFile("names.zip") def read_names(f): data = pd.read_csv(zf.open(f), header = None, names = ['name', 'sex', 'n']) data['year'] = int(re.findall(r'\d+', f)[0]) return data bnames = pd.concat([read_names(f) for f in zf.namelist() if f.endswith('.txt')]) bnames.head()
5 rows × 4 columns
The second dataset we will be downloading is the bnames_by_state dataset, also provided by SSA
urllib.urlretrieve("", "namesbystate.zip") zf = ZipFile("namesbystate.zip") def read_names2(f): return pd.read_csv(zf.open(f), header = None, names = ['state', 'sex', 'year', 'name', 'n']) bnames_by_state = pd.concat([read_names2(f) for f in zf.namelist() if f.endswith('.TXT')]) bnames_by_state.head()
5 rows × 5 columns
The next dataset is actuarial cohort life tables provided by SSA. I was unable to figure out how to scrape this data using
BeautifulSoup. So I used the R package
XML to scrape these lifetables and saved it to lifetables.csv. If you are interested in the R code, you can find it here.
lifetables = pd.read_csv('lifetables.csv') lifetables.head()
5 rows × 9 columns
You can read the documentation for the lifetables to understand the various parameters. The key column of interest to us is
lx, which provides the number of people born in the year
year who live upto the age
x. Since we are in the year 2014, we are only interested in a subset of the data.
lifetables_2014 = lifetables[lifetables['year'] + lifetables['x'] == 2014] lifetables_2014.head()
5 rows × 9 columns
The cohort life tables are provided only for every decade. Since we need the data by year, we will use spline interpolation to fill out the gaps.
def process(d, kind = 'slinear'): f = interp1d(d.year, d.lx, kind) year = np.arange(1900, 2011) lx = f(year) return pd.DataFrame({"year": year, "lx": lx, "sex": d.sex.iloc[1]}) lifetable_2014 = lifetables_2014.\ groupby('sex', as_index = False).\ apply(process) lifetable_2014.head()
5 rows × 3 columns
Finally, we need live births data from the census to extrapolate the birth data to account for the correct that not all births were recorded by SSA till around 1930, since it wasn't mandatory.
urllib.urlretrieve("", "02HS0013.xls") dat = pd.read_excel('02HS0013.xls', sheetname = 'HS-13', skiprows = range(14)) tot_births = dat.ix[9:101,:2].reset_index(drop = True) tot_births.columns = ['year', 'births'] tot_births = tot_births.convert_objects(convert_numeric = True) tot_births.head()
5 rows × 2 columns
We will now merge this data with the
bnames aggregated by
year to compute a set of correction factors, which will be used to scale the number of births. I have taken a very naive approach to do this, and there might be better ways to accomplish the same.
cor_factors = bnames.\ groupby('year', as_index = False).\ sum().\ merge(tot_births) cor_factors['cor'] = cor_factors['births']*1000/cor_factors['n'] cor_factors = cor_factors[['year', 'cor']] cor_factors.head()
5 rows × 2 columns
We expand the correction factors data for the years 2002 to 2014 using the correction factor for the year 2001.
cor_new = pd.DataFrame({ 'year': range(2002, 2014), 'cor': cor_factors.cor.iloc[-1] }) cor_factors = pd.concat([cor_factors, cor_new])[['year', 'cor']] cor_factors.head()
5 rows × 2 columns
def get_data(name, sex, state = None): if state is None: dat = bnames else: dat = bnames_by_state[(bnames_by_state["state"] == state)] data = dat[(dat['name'] == name) & (dat['sex'] == sex)].\ merge(cor_factors).\ merge(lifetable_2014) data['n_cor'] = data['n']*data['cor'] data['n_alive'] = data['lx']/(10**5)*data['n_cor'] return data get_data('Violet', 'F').head()
5 rows × 8 columns
Our next helper function is
plot_name which accepts the same arguments as
get_data, but returns a plot of the distribution of number of births and number alive by year.
def plot_name(name, sex, state = None): data = get_data(name, sex, state) return ggplot(data, aes('year', 'n_cor')) +\ geom_line() +\ geom_area(aes(ymin = 0, ymax = 'n_alive'), alpha = 0.5) plot_name("Joseph", "F")
<ggplot: (279099421)>
plot_name("Violet", "F", "MA")
<ggplot: (279096937)>
We will now write a function that will help us figure out the probability that a person with a certain name is alive, as well as the quantiles of their age distribution. Since we are dealing with weighted data, I will use some code copied from the wquantiles module. The
quantile function accepts a data array and a weights array to return a specific quantile
# from the module wquantiles import numpy as np def quantile_1D(data, weights, quantile): """ Compute the weighted quantile of a 1D numpy array. Parameters ---------- data : ndarray Input array (one dimension). weights : ndarray Array with the weights of the same size of `data`. quantile : float Quantile to compute. It must have a value between 0 and 1. Returns ------- quantile_1D : float The output value. """ # Check the data if not isinstance(data, np.matrix) : data = np.asarray(data) if not isinstance(weights, np.matrix) : weights = np.asarray(weights) nd = data.ndim if nd != 1: raise TypeError("data must be a one dimensional array") ndw = weights.ndim if ndw != 1: raise TypeError("weights must be a one dimensional array") if data.shape != weights.shape: raise TypeError("the length of data and weights must be the same") if ((quantile > 1.) or (quantile < 0.)): raise ValueError("quantile must have a value between 0. and 1.") # Sort the data ind_sorted = np.argsort(data) sorted_data = data[ind_sorted] sorted_weights = weights[ind_sorted] # Compute the auxiliary arrays Sn = np.cumsum(sorted_weights) # TODO: Check that the weights do not sum zero Pn = (Sn-0.5*sorted_weights)/np.sum(sorted_weights) # Get the value of the weighted median return np.interp(quantile, Pn, sorted_data) def quantile(data, weights, quantile): """ Weighted quantile of an array with respect to the last axis. Parameters ---------- data : ndarray Input array. weights : ndarray Array with the weights. It must have the same size of the last axis of `data`. quantile : float Quantile to compute. It must have a value between 0 and 1. Returns ------- quantile : float The output value. """ # TODO: Allow to specify the axis nd = data.ndim if nd == 0: TypeError("data must have at least one dimension") elif nd == 1: return quantile_1D(data, weights, quantile) elif nd > 1: n = data.shape imr = data.reshape((np.prod(n[:-1]), n[-1])) result = np.apply_along_axis(quantile_1D, -1, imr, weights, quantile) return result.reshape(n[:-1])
We will use the
quantile function to write an
estimate_age function that will return the living probabilities and quantiles for a given
name,
sex and
state.
def estimate_age(name, sex, state = None): data = get_data(name, sex, state) qs = [1, 0.75, 0.5, 0.25, 0] quantiles = [2014 - int(quantile(data.year, data.n_alive, q)) for q in qs] result = dict(zip(['q0', 'q25', 'q50', 'q75', 'q100'], quantiles)) result['p_alive'] = round(data.n_alive.sum()/data.n_cor.sum()*100, 2) result['sex'] = sex result['name'] = name return pd.Series(result) estimate_age('Gertrude', 'F')
name Gertrude p_alive 18.17 q0 4 q100 105 q25 71 q50 82 q75 90 sex F dtype: object
estimate_age('Ava', 'F')
name Ava p_alive 95.24 q0 4 q100 105 q25 6 q50 8 q75 10 sex F dtype: object
We can now use the
estimate_age function to compute the quantiles for the most common names and replicate the plots in the Nate Silver article.
top_100_names = bnames.\ groupby(['name', 'sex'], as_index = False).\ sum().\ sort('n', ascending = False) top_25_females = top_100_names[(top_100_names["sex"] == "F")] estimates = pd.concat([estimate_age(name, 'F') for name in top_25_females["name"].iloc[:25].tolist()], axis = 1) estimates.T.sort('q50').reset_index()
25 rows × 9 columns
We can go a step beyond the article and also use the
state parameter to get more specific quantiles, if we know the place of birth of a person.
The final step for me is to convert all of this into an interactive webapp. I have done it with R using the shiny package. I am still getting the hang of web frameworks in python, so it will be a while before I get to doing this. | https://nbviewer.jupyter.org/github/ramnathv/agebyname_py/blob/master/index.ipynb | CC-MAIN-2019-09 | refinedweb | 1,452 | 60.31 |
For many developers, SQLite has become the preferred client-side technology for data storage. It is a server-less, embedded, open-source database engine that satisfies most local data access scenarios. There are numerous advantages that come with its use, many of which are explained in the SQLite about page.
Since the Windows 10 Anniversary Update (Build 14393), SQLite has also shipped as part of the Windows SDK. This means that when you are building your Universal Windows Platform (UWP) app that runs across the different Windows device form factors, you can take advantage of the SDK version of SQLite for local data storage. This comes with some advantages:
- Your application size reduces since you don’t download your own SQLite binary and package it as part of your application
- Note: Microsoft.Data.SQLite (used in the example below) currently has an issue where both SQLite3.dll and WinSQLite.dll are loaded in memory whenever a .NET Native version of your application is run. This is a tracked issue that will be addressed in subsequent updates of the library.
- You can depend on the Windows team to update the version of SQLite running on the operating system with every release of Windows.
- Application load time has the potential to be faster since the SDK version of SQLite will likely already be loaded in memory.
Below, we provided a quick coding example on how to consume the SDK version of SQLite in your C# application.
Note: Since the Windows SDK version of SQLite has only been available since the Windows 10 Anniversary Update, it can only be used for UWP apps targeting Build 14393 or higher.
C# Example
In this example, we will build a UWP application that will allow users to input text into an app local database. The goal is to provide developers with concise guidance on how to use the SQLite binary that’s shipped as part of the Windows SDK. Therefore this code sample is meant to be as simple as possible, so as to provide a foundation that can be further built upon.
An example of the end product is shown below:
SQLite C# API Wrappers
As mentioned in the SQLite documentation, the API provided by SQLite is fairly low-level and can add an additional level of complexity for the developer. Because of this, many open-source libraries have been produced to act as wrappers around the core SQLite API. These libraries abstract away a lot of the core details behind SQLite, allowing developers to more directly deal with executing SQL statements and parsing the results.
For SQLite consumption across Windows, we recommend the open-source Microsoft.Data.Sqlite library built by the ASP.NET team. It is actively being maintained and provides an intuitive wrapper around the SQLite API. The rest of the example assumes use of the Microsoft.Data.Sqlite library.
Alternative SQLite wrappers are also linked in the “Additional Resources” section below.
Visual Studio set-up
The packages used in this sample have a dependency on NuGet version 3.5 or greater. You can check your version of NuGet by going to Help ‣ About Microsoft Visual Studio and looking through the Installed Products for NuGet Package Manager. You can go to the NuGet download page and grab the version 3.5 VSIX update if you have a lower version.
Note: Visual Studio 2015 Update 3 is pre-installed with NuGet version 3.4, and will likely require an upgrade. Visual Studio 2017 RC is installed with NuGet version 4.0, which works fine for this sample.
Adding Microsoft.Data.Sqlite and upgrading the .NET Core template
The Microsoft.Data.Sqlite package relies on at least the 5.2.2 version of .NET Core for UWP, so we’ll begin by upgrading this:
- Right click on References ‣ Manage NuGet Packages
- Under the Installed tab, look for the Microsoft.NETCore.UniversalWindowsPlatform package and check the version number on the right-hand side. If it’s not up to date, you’ll be able to update to version 5.2.2 or higher.
Note: Version 5.2.2 is the default for VS 2017 RC. Therefore, this step is not required if you are using this newest version of Visual Studio.
To add the Microsoft.Data.Sqlite NuGet package to your application, follow a similar pattern:
- Right-click on References ‣ Manage NuGet Packages
- Under the Browse tab, search for the Microsoft.Data.Sqlite package and install it.
Code
Application User Interface
We’ll start off by making a simple UI for our application so we can see how to add and retrieve entries from our SQLite database.
[code lang=”xml”]
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<TextBox Name="Input_Box"></TextBox>
<Button Click="Add_Text">Add</Button>
<ListView Name="Output">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</Grid>
[/code]
There are three important parts to our application’s interface:
- A text box that allows us to take text from the user.
- A button linked to an event for pulling the text and placing it in the SQLite database.
- An ItemTemplate to show previous entries in the database.
Code Behind for Application
In the App.xaml.cs and MainPage.xaml.cs files generated by Visual Studio, we’ll start by importing the Microsoft.Data.Sqlite namespaces that we’ll be using.
[code]
using Microsoft.Data.Sqlite;
using Microsoft.Data.Sqlite.Internal;
[/code]
Then as part of the app constructor, we’ll run a “CREATE TABLE IF NOT EXISTS” command to guarantee that the SQLite .db file and table are created the first time the application is launched.
[code lang=”csharp”]
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
SqliteEngine.UseWinSqlite3(); //Configuring library to use SDK version of SQLite
using (SqliteConnection db = new SqliteConnection("Filename=sqliteSample.db"))
{
db.Open();
String tableCommand = "CREATE TABLE IF NOT EXISTS MyTable (Primary_Key INTEGER PRIMARY KEY AUTOINCREMENT, Text_Entry NVARCHAR(2048) NULL)";
SqliteCommand createTable = new SqliteCommand(tableCommand, db);
try
{
createTable.ExecuteReader();
}
catch (SqliteException e)
{
//Do nothing
}
}
}
[/code]
There are couple of points worth noting with this code:
- We make a call to SqliteEngine.UseWinSqlite3() before making any other SQL calls, which guarantees that the Microsoft.Data.Sqlite framework will use the SDK version of SQLite as opposed to a local version.
- We then open a connection to a SQLite .db file. The name of the file passed as a String is your choice, but should be consistent across all SqliteConnection objects. This file is created on the fly the first time it’s called, and is stored in the application’s local data store.
- After establishing the connection to the database, we instantiate a SqliteCommand object passing in a String representing the specific command and the SqliteConnection instance, and call execute.
- We place the ExecuteReader() call inside a try-catch block. This is because SQLite will always throw a SqliteException whenever it can’t execute the SQL command. Not getting the error confirms that the command went through correctly.
Next, we’ll add code in the View’s code-behind file to handle the button-clicked event. This will take text from the text box and put it into our SQLite database.
[code lang=”csharp”]
private void Add_Text(object sender, RoutedEventArgs e)
{
using (SqliteConnection db = new SqliteConnection("Filename=sqliteSample.db"))
{
db.Open();
SqliteCommand insertCommand = new SqliteCommand();
insertCommand.Connection = db;
//Use parameterized query to prevent SQL injection attacks
insertCommand.CommandText = "INSERT INTO MyTable VALUES (NULL, @Entry);";
insertCommand.Parameters.AddWithValue("@Entry", Input_Box.Text);
try
{
insertCommand.ExecuteReader();
}
catch (SqliteException error)
{
//Handle error
return;
}
db.Close();
}
Output.ItemsSource = Grab_Entries();
}
[/code]
As you can see, this isn’t drastically different than the SQLite code explained in the app’s constructor above. The only major deviation is the use of parameters in the query so as to prevent SQL injection attacks. You will find that commands that make changes to the database (i.e. creating tables, or inserting entries) will mostly follow the same logic.
Finally, we go to the implementation of the Grab_Entries() method, where we grab all the entries from the Text_Entry column and fill in the XAML template with this information.
[code lang=”csharp”]
private List<String> Grab_Entries()
{
List<String> entries = new List<string>();
using (SqliteConnection db = new SqliteConnection("Filename=sqliteSample.db"))
{
db.Open();
SqliteCommand selectCommand = new SqliteCommand("SELECT Text_Entry from MyTable", db);
SqliteDataReader query;
try
{
query = selectCommand.ExecuteReader();
}
catch(SqliteException error)
{
//Handle error
return entries;
}
while(query.Read())
{
entries.Add(query.GetString(0));
}
db.Close();
}
return entries;
}
[/code]
Here, we take advantage of the SqliteDataReader object returned from the ExecuteReader() method to run through the results and add them to the List we eventually return. There are two methods worth pointing out:
- The Read() method advances through the rows returned back from the executed SQLite command, and returns a boolean based on whether you’ve reached the end of the query or not (True if there are more rows left, and False if you’ve reached the end).
- The GetString() method returns the value of the specified column as a String. It takes in one parameter, an int that represents the zero-based column ordinal. There are similar methods like GetDataTime() and GetBoolean() that you can use based on the data type of the column that you are dealing with.
- The ordinal parameter isn’t as relevant in this example since we are selecting all the entries in a single column. However, in the case where multiple columns are part of the query, the ordinal represents the column you are pulling from. So if we selected both Primary_Key and Text_Entry, then GetString(0) would return the value of Primary_Key String and GetString(1) would return the value of Text_Entry as a String.
And that’s it! You can now build your application and add any text you like into your SQLite database. You can even close and open your application to see that the data persists.
A link to the full code can be found at:
Moving Forward
There are plenty of additions that you can make to tailor this sample to your needs:
- Adding more tables and more complicated queries.
- Providing more sanitation over the text entries to prevent faulty user input.
- Communicating with your database in the cloud to propagate information across devices.
- And so much more!
What about Entity Framework?
For those developers looking to abstract away particular database details, Microsoft’s Entity Framework provides a great model that lets you work at the “Object” layer as opposed to the database access layer. You can create models for your database using code, or visually define your model in the EF designer. Then Entity Framework makes it super-easy to generate a database from your defined object model. It’s also possible to map your models to existing databases you may have already created.
SQLite is one of many database back-ends that Entity Framework is configured to work with. This documentation provides an example to work from.
Conclusion
From embedded applications for Windows 10 IoT Core to a cache for enterprise relations database server (RDBS) data, SQLite is the premier choice for any application that needs local storage support. SQLite’s server-less and self-contained architecture makes it compact and easy to manage, while its tried and tested API surface coupled with its massive community support provides additional ease of use. And since it ships as part of Windows 10, you can have peace of mind, knowing that you’re always using an up-to-date version of the binary.
As always, please leave any questions in the comments section, and we’ll try our best to answer them. Additional resources are also linked below.
Additional Resources
- SQLite Documentation from SQLite page
- Additional open source SQLite wrappers available via NuGet:
- Entity Framework Documentation | https://blogs.windows.com/windowsdeveloper/2017/02/06/using-sqlite-databases-uwp-apps/ | CC-MAIN-2022-40 | refinedweb | 1,952 | 56.35 |
Transient keyword in java is comparatively less common than any other keyword like volatile.since transient is less common it becomes even more important to understand correct usage of it. In One word transient keyword is used in serialization process to prevent any variable from being serialized, so if you have any field which is not making sense to serialize, you can simply declare that as transient and it won't be serialized.In this article we will revise some basics like
What is transient variable in java, why do we need transient variable and most importantly where should we use transient variable or which fields need to be declared as transient with example.
What is transient variable in Java?
Why do we need transient variable in java?
Transient keyword provides you some control over serialization process and gives you flexibility to exclude some of object properties from serialization process. Some time it does make sense not to serialize certain attributes of an object, we will see which variables should not be serialized and should be made transient in next section.
Which variable you should mark transient?
This is a good question; since we know the purpose of transient keyword or having transient variable its make sense to think about which variable should be marked as transient. My rule is that any variable whose value can be calculated from other variables doesn't require to be saved. For example if you have a field called "interest" whose value can be derived from other fields e.g. principle, rate, time etc then there is no need to serialize it.
Another example is of word count, if you are saving article then no need to save word count, because it can be created when article gets deserialized. Another good example of transient keyword is "Logger" since most of the time you have logger instance for logging in Java but you certainly don't want it to serialize correct?
Example of transient variable in java
To understand the concept of transient variables let see a live example in java.
public class Stock {
private transient Logger logger = Logger.getLogger(Stock.class); //will not serialized
private String symbol; //will be serialized
private BigInteger price; //serialized
private long quantity; //serialized
}
Important points about transient keyword in java
Here are few important points about transient variables in java which I found, let me know if you have some more which I missed out here and I will include here.
1) Transient keyword can only be applied to fields or member variable. Applying it to method or local variable is compilation error.
2) Another important point is that you can declare an variable static and transient at same time and java compiler doesn't complain but doing that doesn't make any sense because transient is to instruct "do not save this field" and static variables are not saved anyway during serialization.
3) In similar way you can apply transient and final keyword together to a variable compiler will not complain but you will face another problem of reinitializing a final variable during deserialization.
4) Transient variable in java is not persisted or saved when an object gets serialized.
That's all from me on transient keyword, let me know how do you use it and if you know any pecularity about transient keyword or something which we need to be aware while using it and missed out here. You can also refer’s Sun Glossary for meaning of different keywords in Java.
Related tutorials in Java
6 comments :
transient keyword also saves you with NotSerializable exception. If you have a field in your Class which does not implement Serializable interface than there is no way out other than marking it transient.
Does it make sense to have a trasient variable if your class is not serializable?
@Anonymous, Yes if you have an non serializable class which is part of Serializable than you can not include that into default Serialization, you have two option either declare them static or transient. further if they are class level resource than making static more sense than transient.
can you please explain in simple terms what is transient variable in Java and where to use transient variable ? the definition looks very technical, a simple example or real life use case would be appreciated.
Hi all,
I have a question,
I declared an object (which has 3 properties String, int, double) itself as transient.
I call oos.writeObject(object1);
and then when I call
object2 = (MyClass) ois.readObject();
It is successfully deserialized even though it is declared as transient.
Can anybody explain please!!
I see contradictions in your statements..
see point 2 here.. 2) Another important point is that you can declare an variable static and transient at same time.....
and another point on page --
which says...
2) transient keyword can not be used along with static keyword but volatile can be used along with static. | http://javarevisited.blogspot.com/2011/09/transient-keyword-variable-in-java.html?showComment=1352959960362 | CC-MAIN-2014-52 | refinedweb | 823 | 60.45 |
import db data into openoffice
Discussion in 'Python' started by Ghido, Sep 26, 2006.
- Similar Threads
Import excel data into SQL server -- ASP.net, C#, DTS -- how??Rathtap, Jun 30, 2003, in forum: ASP .Net
- Replies:
- 0
- Views:
- 2,366
- Rathtap
- Jun 30, 2003
Tools to extract data from SQL database and convert it into XML & insert XML data into SQL databasesHarry Zoroc, Jul 12, 2004, in forum: XML
- Replies:
- 1
- Views:
- 1,189
- Gregory Vaughan
- Jul 12, 2004
Import data from Excel file or text file into database in ASP.NET programbienwell, Jun 16, 2006, in forum: ASP .Net
- Replies:
- 2
- Views:
- 4,454
- bienwell
- Jun 17, 2006
import ascii data into a HTML file?, Jul 14, 2006, in forum: HTML
- Replies:
- 3
- Views:
- 511
- Andy Dingley
- Jul 15, 2006
RE: Pywin32: How to import data into Excel?Tim Golden, Nov 8, 2005, in forum: Python
- Replies:
- 1
- Views:
- 848
- Duncan Booth
- Nov 8, 2005
Re: Pywin32: How to import data into Excel?Simon Brunning, Nov 8, 2005, in forum: Python
- Replies:
- 1
- Views:
- 499
- Norbert
- Nov 13, 2005
FYI: getting data from an OpenOffice.org spreadsheetalf, Sep 3, 2006, in forum: Python
- Replies:
- 7
- Views:
- 598
- Sybren Stuvel
- Sep 4, 2006
The best file format to import/export data into sql database through asp.net applicationMax2006, Oct 9, 2007, in forum: ASP .Net
- Replies:
- 4
- Views:
- 707
- =?Utf-8?B?UGV0ZXIgQnJvbWJlcmcgW0MjIE1WUF0=?=
- Oct 9, 2007 | http://www.thecodingforums.com/threads/import-db-data-into-openoffice.373546/ | CC-MAIN-2016-40 | refinedweb | 236 | 63.8 |
All that work we just did is important, but sadly looks identical to end users – frustrating, huh? But that's OK, because it was important groundwork for what's coming now: we're going to add a new page for our homepage, then move what we have now to be /react.
So, create a new file inside src/pages called List.js and give it this basic content for now:
src/pages/List.js
import React from 'react'; class List extends React.Component { render() { return <p>This is the list page.</p>; } } export default List;
We're going to make it so that going to the homepage loads our List component, and going to /react loads our Detail component. To make this happen we need to add a new route, then move the existing one.
As a reminder, here is your current index.js file
src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, IndexRoute, useRouterHistory } from 'react-router'; import { createHashHistory } from 'history'; import Detail from './pages/Detail'; const appHistory = useRouterHistory(createHashHistory)({ queryKey: false }) ReactDOM.render( <Router history={appHistory} onUpdate={() => window.scrollTo(0, 0)}> <Route path="/" component={ Detail } /> </Router>, document.getElementById('app') );
Please add an import for the new List component you made a moment ago. If you're not sure, it should look like this:
src/index.js
import List from './pages/List';
Now we need to move our existing route so that it handles /react and make a new route to handle /, like this:
src/index.js
<Route path="/" component={ List } /> <Route path="/react" component={ Detail } />
That's it! You should be able to point your web browser at to see "This is the list page", then point it at to see our old page.
That wasn't hard, right? Right. But neither was it very useful: we need a way for users to be able to select a GitHub repository to view, which means upgrading our List! | http://www.hackingwithreact.com/read/1/22/how-to-add-a-new-route-to-react-router | CC-MAIN-2019-04 | refinedweb | 326 | 66.44 |
At Second Street, we are proud to make white-label software that enables our customers to offer promotions and contests as part of their brand. One of the interesting development challenges behind that has been the need to embed our software on our customers' websites.
An
<iframe> can solve quite a few problems on the web, but it introduces a nearly-impenetrable wall of security. The only way through that wall, if your iframe is on a different domain, is via the HTML5
postMessage API. Unfortunately,
postMessage is messy.
The Problem with
postMessage
While it's great to have something to break the security barrier between a frame and the page it's embedded on,
postMessage has its downsides.
- Your event listener gets every message, from every frame. The signal-to-noise ratio is abysmal.
- There is no guarantee that the other side is ready to receive your message yet.
- Only strings can be sent over the wire.
- The concept of a request/response cycle is completely absent.
Our Tiny Solution
We created a library, talker.js, to solve this problem. At under 1kB minified and gzipped, it's perfect for embedding into applications to make communicating over
postMessage a breeze. And since it's released under the open source MIT License, you can start using it today!.
Using Talker.js
The
Talker constructor takes a
window, and an origin (or
'*' to accept messages from any origin).
var talker = new Talker(myFrame.contentWindow, '');
Sending Messages
Use
Talker#send to send a message to the other side. Messages have a namespace for organization, and can have an object sent for data transfer. The object must be able to pass through
JSON.stringify.
talker.send('myNamespace', { data: 'here' });
Listening for Messages
Talker will call
Talker#onMessage with a
Talker.IncomingMessage. That message has properties for the
namespace and
data it was originally sent with, as well as an
id and a reference to its
talker.
talker.onMessage = function(message) { console.log(message.namespace, message.data); console.log(message.id, message.talker); };
Responding to Messages
Use
Talker.IncomingMessage#respond to respond to a message with an object. This returns a promise via PinkySwear.js that may resolve with a response if one is sent, or may reject with an error.
talker.onMessage = function(message) { message.respond({ hello: 'there' }); }; talker.send('localStorage', { get: 'username' }) .then(function(message) { console.log(message.namespace, message.data); console.log(message.id, message.talker); }, function(error) { console.error(error); }) ;
Getting Talker
Talker.js distributions are available via Bower and GitHub. The source is also on GitHub. Talker is available as a global, a named or anonymous AMD package, or a Common JS package.
$ bower install talkerjs --save
If you'd like to contribute, please Fork us on GitHub, or file an issue with any bug reports or feature requests. | https://drive.secondstreet.com/introducing-talker/ | CC-MAIN-2018-39 | refinedweb | 470 | 59.7 |
install pyzbar with "pip3 install pyzbar" command.
This doesn't seem to be related to 2fa. 2fa is a Go application.
I'm getting an error when running after installing this package:
Traceback (most recent call last):
File "/usr/bin/authenticator", line 55, in <module>
from Authenticator.models import Logger
File "/usr/lib/python3.7/site-packages/Authenticator/models/__init__.py", line 26, in <module>
from .qr_reader import QRReader
File "/usr/lib/python3.7/site-packages/Authenticator/models/qr_reader.py", line 23, in <module>
from pyzbar.pyzbar import decode
ModuleNotFoundError: No module named 'pyzbar'
aurweb v5.0.0
AUR packages are user produced content. Any use of the provided files is at your own risk.
Latest Comments
deadmarshal commented on 2020-02-26 14:18
install pyzbar with "pip3 install pyzbar" command.
dmgk commented on 2019-07-14 14:21
This doesn't seem to be related to 2fa. 2fa is a Go application.
tycho01 commented on 2019-07-14 13:13
I'm getting an error when running after installing this package: | https://aur.archlinux.org/packages/2fa/ | CC-MAIN-2020-24 | refinedweb | 173 | 53.78 |
Building a Notepad Application from Scratch with Ionic (Angular). I have attempted to strike a balance between optimised/best-practice code, and something that is just straight-forward and easy enough for beginners to understand. Sometimes the “best” way to do things can look a lot more complex and intimidating, and doesn’t serve much of a purpose for beginners. You can always introduce more advanced concepts to your code as you continue to learn.
I will be making it a point to take longer to explain smaller concepts in this tutorial, more so than others, since it is targeted at people right at the beginning of their Ionic journey. However, I will not be able to cover everything in the level of depth required. I will mostly be including just enough to introduce you to the concept in this tutorial, and I will link out to further resources to explain those concepts in more depth.
- Two-way data binding
- Interpolations
-.1.0
This tutorial will assume that you have read at least some introductory content about Ionic, have a general understanding of what it is, and that you have Ionic set up on your machine. You will also need to have a basic understanding of HTML, CSS, and JavaScript.
If you do not already have Ionic set up on your machine, or you don’t have a basic understanding of the structure of an Ionic project, take a look at the additional resource below for a video walkthrough.
Additional resources:
1. Generate a New Ionic Project
Time to get started! To begin, we will need to generate a new Ionic application. We can do that with the following command:
ionic start ionic-angular-notepad blank --type=angular
We are naming our application
ionic-angular-notepad and we are using the
blank template from Ionic (which will just give us a bare-bones starter template). By supplying the
--type flag we are indicating we want to create an Ionic/Angular project (which will generate an Ionic 4 application for us).
You will be prompted to set up the Ionic Appflow SDK during this process, you can just say no to this for now. Once the application has finished generating, make it your working directory by running:
cd ionic-angular-notepad
2. Create the Required Pages/Services
This application will have two pages:
- Home (a list of all notes)
- Detail (the details of a particular note)
and we will also be making use of a service/provider:
- NotesService
which is going to be responsible for handling most of the logic around creating, updating, and deleting notes. We are going to create these now by using Ionic’s generate command. Since there is already a “Home” page by default, we won’t need to create that.
Run the following command to generate the detail page:
ionic g page Detail
Run the following commands to generate the service:
ionic g service services/Notes
The reason we use
services/Notes instead of just
Notes is that we want all of our services to be within a
services folder (by default, they will just be created in the project root directory).
3. Setting up Navigation/Routing
Now we move on to our first real bit of work – setting up the routes for the application. Most of this is handled automatically for us when we generate the pages, but we are going to make a couple of changes.
Modify src/app/app-routing.module.ts to reflect the following:
import { NgModule } from "@angular/core"; import { PreloadAllModules, Routes, RouterModule } from "@angular/router"; const routes: Routes = [ { path: "", redirectTo: "notes", pathMatch: "full" }, { path: "notes", loadChildren: "./home/home.module#HomePageModule" }, { path: "notes/:id", loadChildren: "./detail/detail.module#DetailPageModule" } ]; @NgModule({ imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })], exports: [RouterModule] }) export class AppRoutingModule {}
We’ve renamed our
home path to
notes just because I think it makes more sense for the URL to say
notes - this is purely a cosmetic change. We have also changed the path for our Detail page to:
notes/:id
This is not just a cosmetic change. By adding
:id to the path, which is prefixed by a colon
: we are creating a route that will accept parameters which we will be able to grab later..
Additional resources:/app/home/home.page.html to reflect the following:
<ion-header> <ion-toolbar <ion-title> Notes </ion-title> <ion-buttons <ion-button> <ion-icon</ion-icon> < for our Home page just yet, let’s change a few minor things and talk through the code that is there already.
Modify src/app/home/home.page.ts to reflect the following:
import { Component, OnInit } from '@angular/core'; import { AlertController, NavController } from '@ionic/angular'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage implements OnInit { constructor(private alertCtrl: AlertController, private navCtrl: NavController){ } ngOnInit(){ } }
At the top, we have our
imports – these are the dependencies that we will need to make use of in this page. We import
Component and
OnInit from the
@angular/core library, and we import
AlertController and
NavController from the
@ionic/angular library.
- Component allows us to create a component using the
@Componentdecorator and specifies the metadata for the page including the URL of its template and
.scssfile (required for all components/pages)
- OnInit allows us to implement the
ngOnInitmethod which will be triggered as soon as the page is initialised
- AlertController will allow us to create alert prompts
- NavController will allow us to control navigation using Ionic’s navigation methods
It isn’t enough to just import some of these dependencies, we also may need to set them up in our class using dependency injection. We need to “inject” these dependencies through the
constructor in the class. Take a look at the following code:
constructor(private alertCtrl: AlertController, private navCtrl: NavController){ }
What this is doing is setting up class members, which will be references to the injected dependency, that will be accessible through the class. In the case of the
AlertController we are basically saying:
“Create a class member variable called alertCtrl which will be an instance of the AlertController service”
By prefixing this with
private we are saying that we want this variable to be accessible anywhere inside of this class (but not outside of the class). We could also use
public which would make the variable accessible anywhere inside or outside of the class.
This means that anywhere in this class we will be able to reference
this.alertCtrl or
this.navCtrl to access the methods that they each provide.
It’s going to be hard for us to go much further than this without starting to work on our Notes service, as this is what is going to allow us to add, update, and delete notes. Without it, we don’t have anything to display!
Additional resources:
5. Creating an Interface
Before we implement our Notes service, we are going to define exactly “what” a note is by creating our own custom type with an interface.
Angular.
Create a folder and file at src/app:
6. Implement the Notices Service
The pages in our application are responsible for displaying views/templates on the screen to the user. Although they are able to implement logic of their own in their associates
*.page.ts files,
Let’s implement the code, and then talk through it. I’ve added comments to various parts of the code itself, but we will also talk through it below.
Modify src/services/notes.service.ts to reflect the following:
import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; import { Note } from '../interfaces/note'; @Injectable({ providedIn: 'root' }) export class NotesService { public notes: Note[] = []; public loaded: boolean = false; constructor(private storage: Storage) { } load(): Promise<boolean> { // Return a promise so that we know when this operation has completed return new Promise((resolve) => { // Get the notes that were saved into storage this.storage.get('notes').then((notes) => { // Only set this.notes to the returned value if there were values stored if(notes != null){ this.notes = notes; } // This allows us to check if the data has been loaded in or not this.loaded = true; resolve(true); }); }); } save(): void { // Save the current array of notes to storage this.storage.set('notes', this.notes); } getNote(id): Note { // Return the note that has an id matching the id passed in(); } } }
Once again, we have our imports at the top of the file. Rather than
Component we use
Injectable this time, which provides the
@Injectable decorator we use with all of our services/providers. This allows us to define where the service is
providedIn which in this case (and in most cases) is
root, meaning that a single instance of this service will be available for use throughout our entire application.
We also import
Storage which we inject through the constructor as we will be making use of it to save and load data throughout the service, and we also import our
Note interface that we just created.
We set up two class members above our constructor:
noteswhich will be an array of notes (the
Note[]type means it will be an array of our
Notetype we created)
loadedwhich is a boolean (true or false) which will indicate whether or not the data has been loaded in from storage
Like the dependencies we inject through the constructor, variables declared above the constructor will be accessible throughout the entire class using
this.notes or
this.loaded.
IMPORTANT: We will be making use of
this.storage throughout this class, but it won’t work until we complete the next step. There are additional dependencies that need to be installed for storage.
Our
load function is responsible for loading data in from storage (if it exists) and then setting it up on the
this.notes array. We surround this entire method with a
Promise that resolves when the operation is complete, as we will need a way to detect when the operation has finished later. This is asynchronous behaviour, and it is critically important to understand the difference between asynchronous and synchronous code – I’ve linked to further information on this in the additional resources at the end of this section.
The way in which we are loading data in this application I would describe as a “beginner friendly” approach. There are “better” ways to do this using observables, but this is a perfectly acceptable approach.
The
save function simply sets our
notes array on the
notes key in storage so that it can be retrieved later – we will call this whenever there is a change in data..
Finally, the
deleteNote method simply takes in a note and then removes that note from the array.
Additional resources:
- Asynchronous vs Synchronous: Understanding the Difference
- Navigation Basics & Passing Data Between Pages in Ionic & Angular
- When & How to Use Services/Providers in Ionic
7. Setting up Data Storage
Ionic provides a useful Storage API that will automatically handle storing data using the best mechanism available. However, it is not installed by default. To set up Ionic Storage, you will first need to install the following package:
npm install @ionic/storage --save
You will also need to make a change to your root module file.
Modify src/app/app.module.ts to reflect the following:
import { NgModule } from "@angular/core"; import { BrowserModule } from "@angular/platform-browser"; import { RouteReuseStrategy } from "@angular/router"; import { IonicStorageModule } from "@ionic/storage";"; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, IonicStorageModule.forRoot()], providers: [ StatusBar, SplashScreen, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ], bootstrap: [AppComponent] }) export class AppModule {}
Notice that we have imported
IonicStorageModule from
@ionic/storage and we have added
IonicStorageModule.forRoot() to the
imports for the module.
Additional resources:
8. Finishing the Notes Page
With our notes service in place, we can now finish off our Home page. We will need to make some modifications to both the class and the template.
Modify src/app/home/home.page.ts to reflect the following:
import { Component, OnInit } from '@angular/core'; import { AlertController, NavController } from '@ionic/angular'; import { NotesService } from '../services/notes.service'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage implements OnInit { constructor(public notesService: NotesService, private alertCtrl: AlertController, private navCtrl: NavController){ } ngOnInit(){ this.notesService.load(); } addNote(){ this.alertCtrl.create({ header: 'New Note', message: 'What should the title of this note be?', inputs: [ { type: 'text', name: 'title' } ], buttons: [ { text: 'Cancel' }, { text: 'Save', handler: (data) => { this.notesService.createNote(data.title); } } ] }).then((alert) => { alert.present(); }); } }
We have added one additional
import which is the
NotesService. Just like the services we import from the Ionic library, we also need to inject our own service through the
constructor to make it available to use throughout this component.
We have added a call to the
load method of the Notes service, which will handle loading in the data from storage as soon as the application is started.
We have also added an
addNote() method which will allow the user to add a new note. We will create an event binding in the template later to tie a button click to this method, which will launch an
Alert on screen. This prompt will allow the user to enter a title for their new note, and when they click
Save the new note will be added.
Now we just need to finish off the template.
Modify src/app/home/home.page.html to reflect the following:
<ion-header> <ion-toolbar <ion-title> Notes </ion-title> <ion-buttons <ion-button (click)="addNote()"> <ion-icon</ion-icon> </ion-button> </ion-buttons> </ion-toolbar> </ion-header> <ion-content> <ion-list> <ion-item button detail * <ion-label>{{ note.title }}</ion-label> </ion-item> </ion-list> </ion-content>
We have modified our button in the header section to include a
click event binding that is linked to the
addNote() method. This will trigger the
addNote() method we just created whenever the user clicks on the button.
We have also modified our notes list:
<ion-list> <ion-item button detail * <ion-label>{{ note.title }}</ion-label> </ion-item> </ion-list>
Rather than just having a single item, we are now using
*ngFor which will loop over each note in our notes array in the notes service (which is why we reference notesService.notes).
Take notice of the * syntax used here for the *ngFor in the list, this is shorthand for creating an embedded template. Rather than literally rendering out:
<ion-item button detail *
to the DOM (Document Object Model), an embedded template will be created for each items specific data. So, if our notes array had 4 notes in it, then the
let note, which assigns a single element from the notes array to
note as we loop through the array. This allows us to reference its properties, which we are using to access an individual notes
id and
title here.
Since we want to view the details of an individual note by clicking on it, we set up the following
routerLink value:
[routerLink]="'/notes/' + note.id"
Using the square brackets around
routerLink means that we are binding an expression to
routerLink, rather than a literal value. In this case, we want to first evaluate the expression
'/notes' + note.id to something like
'/notes/12' before assigning it to the
routerLink,>. Just like with the square brackets, and interpolation indicated by the double curly braces is just a way to evaluate an expression before rendering it out on the screen. Therefore, this will display the title of whatever note is currently being looped over in our
*ngFor.
Additional resources:
- AlertController API
- An Introduction to Structural Directives: *ngIf & *ngFor
- Component and Template Interaction in Ionic
- Navigation Basics & Passing Data Between Pages in Ionic & Angular the class, and then we will implement the template.
Modify src/app/detail/detail.page.ts
import { Component, OnInit } from '@angular/core'; import { NavController } from '@ionic/angular'; import { ActivatedRoute } from '@angular/router'; import { NotesService } from '../services/notes.service'; import { Note } from '../interfaces/note'; @Component({ selector: 'app-detail', templateUrl: './detail.page.html', styleUrls: ['./detail.page.scss'], }) export class DetailPage implements OnInit { public note: Note; constructor(private route: ActivatedRoute, private notesService: NotesService, private navCtrl: NavController) { // Initialise a placeholder note until the actual note can be loaded in this.note = { id: '', title: '', content: '' }; } ngOnInit() { // Get the id of the note from the URL let noteId = this.route.snapshot.paramMap.get('id'); // Check that the data is loaded before getting the note // This handles the case where the detail page is loaded directly via the URL if(this.notesService.loaded){ this.note = this.notesService.getNote(noteId) } else { this.notesService.load().then(() => { this.note = this.notesService.getNote(noteId) }); } } noteChanged(){ this.notesService.save(); } deleteNote(){ this.notesService.deleteNote(this.note); this.navCtrl.navigateBack('/notes'); } }
This is very similar to our Home page, but there are a few differences. We are using a new import here called
ActivatedRoute. This will allow us to get information about the currently active route, and we want to do that because we need to access the
id of the note that is supplied through the route, e.g:
In our
ngOnInit function, we get this
id value using the
ActivatedRoute that we injected through the
constructor. We then use that
id to grab the specific note from the notes service. However, we first have to check if the data has been loaded yet since it is possible to load this page directly through the URL (rather than going through the home page first). If the data has not already been loaded in yet, then we load the data before attempting to grab the note using
getNote(). The note is then assigned to the
this.note class member.
Since the note is not immediately available to the template, we intialise an empty note in the
constructor so that our template won’t complain about data that does not exist. Once the note has been successfully fetched, the data in the template will automatically update.
navigateBack method of the
NavController.
Modidfy src/app/detail/detail.page.html to reflect the following:
<ion-header> <ion-toolbar <ion-buttons <ion-back-button</ion-back-button> </ion-buttons> <ion-title>{{ note.title }}</ion-title> <ion-buttons <ion-button (click)="deleteNote()"> <ion-icon</ion-icon> </ion-button> </ion-buttons> </ion-toolbar> </ion-header> <ion-content <ion-textarea (input)="noteChanged()" [(ngModel)]="note.content" placeholder="...something on your mind?"></ion-textarea> </ion-content>
Again,. We use an
ngModel which allows us to set up two-way data binding. This means that if the user changes the value in the
<ion-textarea> it will automatically update the
content property of our note to reflect this change. However, it also works in reverse. If we were to change the
content property of our note, then this change would also be reflected inside of the
<ion-textarea>. We generally use
ngModel for simple data/forms input – but for more advanced forms there are better ways to do this.
We also set up an event binding for
input on this component, which will trigger every time the user inputs anything. This will cause any changes to the note to be saved to storage since we are triggering the
save() method every time
noteChanged() is called.
Additional resources:
- Implementing a Master Detail Pattern in Ionic 4 with Angular Routing
- Advanced Forms & Validation in Ionic/theme/variables.scss file. You will find a bunch of CSS4 variables in this file that can be modified (if you aren’t familiar with CSS4 variables, I would recommend checking out the additional resources.
Modify src/theme.variables.scss to reflect the following:
///theme.variables.scss:/app/home/home.page.sc on Shadow DOM as this is a big part of styling in Ionic 4.
Modify src/app/detail/detail.page.scss to reflect the following:
ion-textarea { --background: #fff;. | https://www.joshmorony.com/building-a-notepad-application-from-scratch-with-ionic/ | CC-MAIN-2019-51 | refinedweb | 3,286 | 51.68 |
Barcode Software
Testing a Workgroup User Account in C#.net
Integration QR in C#.net Testing a Workgroup User Account
static String filename;
Using Barcode decoder for sample .net vs 2010 Control to read, scan read, scan image in .net vs 2010 applications.
BusinessRefinery.com/ barcodes
using split sql reporting services to access barcodes for asp.net web,windows application
BusinessRefinery.com/ barcodes
8: Managing the Data
using width .net winforms to print barcodes with asp.net web,windows application
BusinessRefinery.com/ bar code
using automatic .net framework crystal report to connect bar code on asp.net web,windows application
BusinessRefinery.com/ barcodes
Table 6-1 Coding of the CID Field
using keypress asp.net web pages to develop barcodes in asp.net web,windows application
BusinessRefinery.com/ barcodes
use excel spreadsheets bar code encoding to deploy barcodes with excel spreadsheets developers
BusinessRefinery.com/ bar code
import com.ms.xml.Document;
free qr code font for crystal reports
using barcode encoder for .net vs 2010 crystal report control to generate, create qr code iso/iec18004 image in .net vs 2010 crystal report applications. barcodes
BusinessRefinery.com/Quick Response Code
winforms qr code
using module winforms to use qr code 2d barcode in asp.net web,windows application
BusinessRefinery.com/qr-codes
In Summary
free qr code font for crystal reports
using connect .net to deploy qr for asp.net web,windows application
BusinessRefinery.com/QR Code
to encode denso qr bar code and qr bidimensional barcode data, size, image with .net barcode sdk compatible
BusinessRefinery.com/QR-Code
Entities
generate, create qr code jis x 0510 used none on excel spreadsheets projects
BusinessRefinery.com/QR
to insert qr-codes and qr barcode data, size, image with .net barcode sdk implementing
BusinessRefinery.com/qrcode
Part II:
generate, create barcode pdf417 alphanumberic none with office excel projects
BusinessRefinery.com/barcode pdf417
.net pdf 417 reader
Using Barcode reader for padding .net vs 2010 Control to read, scan read, scan image in .net vs 2010 applications.
BusinessRefinery.com/PDF-417 2d barcode
Appendix A: Windows XP Service Pack 1
generate, create ansi/aim code 39 request none for office excel projects
BusinessRefinery.com/USS Code 39
crystal reports pdf 417
using class .net to generate barcode pdf417 with asp.net web,windows application
BusinessRefinery.com/pdf417
2 1 3
pdf417 generator vb.net
use visual .net barcode pdf417 generator to use pdf 417 in vb documentation
BusinessRefinery.com/PDF 417
ssrs fixed data matrix
use sql database data matrix barcode drawer to print datamatrix 2d barcode with .net content
BusinessRefinery.com/Data Matrix 2d barcode
LETTER 8-7: BROADCAST SALES
c# data matrix barcode
using trial vs .net to deploy data matrix barcode with asp.net web,windows application
BusinessRefinery.com/Data Matrix
generate, create ansi/aim code 128 custom none for excel spreadsheets projects
BusinessRefinery.com/USS Code 128
The ADO.NET classes are found in System.Data.dll and are integrated with the XML classes found in System.Xml.dll. When compiling code that uses the System.Data namespace, reference both System.Data.dll and System.Xml.dll. I ve presented the long and formal definition of ADO.NET because it contains elements you ll learn about while working with the CarTracker application. I also chose it because I want you to refer to it whenever you re working with ADO.NET. Here is a less formal definition that I think summarizes what ADO.NET is all about: ADO.NET is the .NET Framework way of accessing and programmatically manipulating databases. With ADO.NET you can also manipulate other sources of data such as XML. With ADO.NET 2.0 came new ways of accessing data from different sources. In Visual C# 2008 Express Edition, you are limited to the following data sources: databases (SQL Server Express and Microsoft Access databases), Web services, and custom objects. It is much easier (that is, there is less code) to manipulate data in ADO.NET 2.0, especially when using all the tools included in Visual Studio 2008. Many new wizards and other tools make the experience of working with databases a pleasant one. Visual Studio 2008 covers numerous common scenarios with its tools and wizards, but it s also very powerful when used programmatically without using the visual tools. You will learn the basics in this book, but nothing is preventing you from learning more about data binding and ADO.NET and from unleashing powerful applications. With LINQ you can create queries within your Visual C# code and query and update all kinds of data (arrays, lists, XML, Web services, SQL databases) easily. Here s a formal definition of LINQ, and then let s jump into the code: Language-Integrated Query (LINQ) adds query capabilities to Visual C# and provides simple and powerful capabilities when you work with all kinds of data. Rather than sending a query to a database to be processed, or working with different query syntax for each type of data that you are searching, LINQ introduces queries as part of the Visual C# language. It uses a unified syntax regardless of the type of data. LINQ enables you to query data from a SQL Server database, XML, in-memory arrays and collections, ADO.NET datasets, or any other remote or local data source that supports LINQ. You can do all this with common Visual C# language elements. Because your queries are written in the Visual C# language, your query results are returned as strongly typed objects. These objects support IntelliSense, which enables you to write code faster and catch errors in your queries at compile time instead of at run time. LINQ queries can be used as the source
Appendix F:
To demonstrate some of what I ve described so far in the chapter, I decided to create an activity many of us writing business process software will (hopefully) find useful an FTP activity. This activity, FtpGetFileActivity, retrieves files from a remote FTP server using the built-in .NET Web-based FTP classes. It is possible to use those same classes for writing files to remote FTP resources, but I leave that activity for you to create as an exercise. Note I ll work under the assumption that you have a known (and correctly configured) FTP site to work with. For the purposes of discussion here, I ll use the well-known Internet Protocol (IP) address 127.0.0.1 as the server s IP address. (Of course, this represents localhost.) Feel free to replace this IP address with any valid FTP server address or host name you prefer. It is beyond the scope of this chapter to address FTP security issues and server configuration. If you are using Internet Information Server (IIS) and need more information regarding FTP configuration, see for assistance. To host the FTP activity, I created a sample application I called FileGrabber. (Its user interface is shown in Figure 13-1.) With it, you can provide an FTP user account and password as well as the FTP resource you want to retrieve. The resource I ll be downloading is an image file of the Saturn V rocket moving into position for launch, and I ve provided the image on the book s CD for you to place on your FTP server as well. Assuming your FTP server was your local machine, the URL for the image is. If you don t use my image file, you ll need to modify the file in the URL to match whatever file you have available on your local server, or use any valid URL from which you can download files.
engineers, network administrators, systems administrators, LAN managers, or MCSE, and use the title the company uses. Simple and effective and it gives the impression that you understand the company s way of thinking. If you can t fit the job title into your work experience, find a way to work it into your career objective statement or your cover letter. It s crucial that the hiring manager see the exact phrase he s looking for if your r sum is going to make the cut.
Part IV
Oxidation half-reaction Cu(s) Cu2+(aq) + 2e
4
Check Event Viewer Fix problems reported in Event Viewer before
3. If you have multiple operating systems on the machine, from the Default Operating System list box, select the operating system you want to have boot by default. 4. If you want to boot the default operating system automatically, without waiting, clear the Time To Display List Of Operating Systems check box. Otherwise, specify how long you want to display a list of options in the box provided. 5. If you want recovery options automatically displayed in the event of problems, select the Time To Display Recovery Options When Needed check box, and set the time for it. 6. Select the Write An Event To The System Log check box, if available, to record an entry in the event log when the system experiences a crash. 7. Select the Send An Administrative Alert check box to send an alert to administrators over the network when the system crashes. 8. Select the Automatically Restart option to instruct Windows Small Business Server to reboot the system in the event of a crash. Otherwise the system remains at a blue screen until an administrator manually reboots it. 9. From the Write Debugging Information list box, select how much debugging information you want to record. Note that if you have a
By default, all views will use the master layout defined in the application configuration file. However, customers often request a different look and feel for an application s administrative views, either for aesthetic purposes or to visually highlight to users that they ve moved to a different section of the application. It s not particularly difficult to do this with a Zend Framework application: Simply create a new layout for administrative views, and then switch to it as needed within individual actions. Here s an example:
By the way, more than one event is being triggered by pressing the Enter key, but the one you ll trap is the KeyUp event.
Microblogging and Persistent Presence
Call History Count Update
More QR Code on C#
how to generate barcode in asp.net using c#: Tools for Troubleshooting in C# Paint Denso QR Bar Code in C# Tools for Troubleshooting
com.google.zxing.qrcode c#: Troubleshooting Group Policy and System Policy in visual C#.net Writer qr codes in visual C#.net Troubleshooting Group Policy and System Policy
Articles you may be interested
qr code c# tutorial: Using the Terminal Services Manager in C# Display QR Code 2d barcode in C# Using the Terminal Services Manager
upc internet praha: Download at Wow! eBook in visual basic.net Encode UPC-A Supplement 5 in visual basic.net Download at Wow! eBook
asp.net barcode generator free: What is causing the certificate validation to fail What must you do to fix the problem in .NET Encode qr barcode in .NET What is causing the certificate validation to fail What must you do to fix the problem
java code 128 reader: EXAM RESOURCES in .net C# Generator DataMatrix in .net C# EXAM RESOURCES
how to generate and scan barcode in asp.net using c#: WHAT IS VALUE INVESTING AND WHY IT MAKES DOLLARS AND SENSE in C#.net Integrating code-128b in C#.net WHAT IS VALUE INVESTING AND WHY IT MAKES DOLLARS AND SENSE
asp.net barcode generator free: Design Patterns in .NET Implement qr bidimensional barcode in .NET Design Patterns
distinguishing barcode scanners from the keyboard in winforms: U Step 4. Review the Knowledge You Need to Score High in visual C#.net Development barcode pdf417 in visual C#.net U Step 4. Review the Knowledge You Need to Score High
print barcode labels using c#: Call Processing Functions in C# Incoporate Denso QR Bar Code in C# Call Processing Functions
vb.net barcode scanner programming: 2: Internet Networking in C# Integrated PDF417 in C# 2: Internet Networking
qr code c# tutorial: F31ws14 in visual C# Generating QR Code 2d barcode in visual C# F31ws14
asp.net barcode generator source code: Root CA 20 years in .NET Printing Denso QR Bar Code in .NET Root CA 20 years
generate barcode in c# windows application: Part 4: Managing Windows Server 2003 Systems in C#.net Generation qr barcode in C#.net Part 4: Managing Windows Server 2003 Systems
create bar code in vb.net: Copyright 2002 The McGraw-Hill Companies, Inc. Click Here for Terms of Use. in .NET Generating Code39 in .NET Copyright 2002 The McGraw-Hill Companies, Inc. Click Here for Terms of Use.
qrcode.net c# example: MSC Identification in visual C# Generating qr-codes in visual C# MSC Identification
excel barcode font freeware: Optimal Project Sequencing in c sharp Generation code128b in c sharp Optimal Project Sequencing
asp.net barcode generator free: Acknowledgments in .NET Build qr bidimensional barcode in .NET Acknowledgments
qr code c# sample: Part 6: Managing Windows Server 2003 Networking and Print Services in visual C#.net Render QR Code 2d barcode in visual C#.net Part 6: Managing Windows Server 2003 Networking and Print Services
barcode reader in c# codeproject: TEN in visual C# Access Code128 in visual C# TEN
vb.net barcode reader free: Using Outlook Express Advanced Features in C#.net Make PDF 417 in C#.net Using Outlook Express Advanced Features
java barcode reader library open source: Figure 7-1 Pulling it all together in Java Generator qr barcode in Java Figure 7-1 Pulling it all together | http://www.businessrefinery.com/yc2/363/448/ | CC-MAIN-2022-05 | refinedweb | 2,270 | 57.67 |
Introduction on Native keyword in Java
The native keyword acts as a link between JAVA language and a chunk of code or library written in different languages except for JAVA which may be dependent on the machine you are operating on. If the native keyword is applied to a method, then that means the method will be implemented using native code written in some other language (like C or C++) via JNI (JAVA native interface).
Syntax
The syntax of native code is the same as normal function definition with the “native” keyword added at the starting of the function.
For example:
Public class testing
{public native String testMethod (String parameter);}
Here the public is an access modifier. It should be public so that another file can use it. The string is the return data type of the function. It can be integer, character or Boolean depending upon the keyword. The parameter passed to this function is of data type string as well. Everything should be kept underclass.
After function declaration, we call this function via object created and library loaded.
public static void main(String[] args)
{
System.loadLibrary("testing");
testing testingnew = new testing();
String output = testingnew.stringMethod("NATIVE");
}
Library defined above should be loaded first and the n its object is created. With the help of this object, the native function is called.
How does the Native keyword work?
There should be two files. One containing JAVA code while the other one should have C/C++ legacy code. Java code will be used to call the legacy code. This legacy code will interact with hardware and return the expected output.
When the legacy code interacts with hardware then it will not follow the guidelines laid out by JAVA. This code will do the desired processing to get the output and pass the results to JNI. Java native interface will then check in its directory containing all the rules pertaining to native code (This comes under a file called javah.exe in SDK). JNI is designed as part of the Java toolkit. After this processing, the JAVA will publish the outputs in the JAVA language itself. When we are creating the program in JAVA then we must make sure that there is a variable/ data flow link between the JAVA file and the legacy file so that there is a smooth flow of data between both.
Steps explaining how to make use of native keywords are given below:
- Write the JAVA code containing native method, shared library loaded and save it using “filename.JAVA”.
- Compile JAVA code and convert the code to bytecode.
- Create a C/C++ header file containing a native function signature which should be called.
- Write C/C++ code has a native method’s implementation.
- Run JAVA executable file to see the results.
Example
We should write code in Eclipse and run the code to create a library using which then C code will be implemented.
Code: package com.slackerOne;
public class JPP {
public static native void pAccess();
public static native int pRead();
public static native void pWrite(int port, int output);
static{
System.loadLibrary("JPPlibs");
}
public void jAccess(){
JPP.pAccess();
}
public int jRead(){
return JPP.pRead();
}
public void jWrite(int port, int output){
JPP.pWrite(port, output);
}
}
After saving this code in the new “class” of the java project. We have to set up a run environment to generate a header file.
When we will run this we should get a library generated.
Output:
Here we created the header file from the java code which will act as a link between native code and java language.
Advantages of Native Keyword in Java
- It provides an added advantage to JAVA to interact with the code written in other languages and reduce the work to have the same code written in JAVA, hence reducing the code redundancy.
- It improves the overall code performance. As the code is written in other languages may be faster when it works with the machine language in comparison to JAVA. We can then use the JAVA program to call this code.
- Using this approach, we can directly give system calls. Reducing the probability of external interference and improving the sped of code execution.
- You can dynamically call a pre-loaded library (written in any language other than JAVA) using an arbitrary driving code written in JAVA and still get a response in JAVA.
- It makes it accessible for JAVA to reach the hardware resources which are available to be used by other languages only.
- In case you have a platform-dependent code already build-up for your application and whose features are not supported via JAVA, in that case, we can have native code and link this native code to JAVA via native keyword.
Rules
- The native keyword is to be used before the method name.
- Native method declaration does not have the body and should end with a semicolon as these methods are not defined in JAVA but are present in C/C++ language.
- Native methods can not be declared as an abstract method.
- Since there is no surety if the previous old code is written in accordance to IEEE 754 standard (The IEEE Standard for Floating-Point Arithmetic is a technical standard for floating-point arithmetic established in 1985 by the Institute of Electrical and Electronics Engineers) so, we can not declare these native methods as strictftp.
- The Java Native Interface (JNI) specification is designed by JAVA to define the rules and declarations to implement native methods, like conversion of data types between Java and the native code.
Conclusion
The native keyword is which bridges the gap between native languages and JAVA. This can be used as a critical link if our software’s interaction with hardware is more to get the efficient code using pre-existing code. It makes the implementation work lesser in comparison to designing a new application code from scratch wherever it could be avoided.
Recommended Articles
This is a guide to Native keyword in Java. Here we discuss How does the Native keyword work with the examples, as well as the advantages, and the rules. You may also have a look at the following articles to learn more – | https://www.educba.com/native-keyword-in-java/?source=leftnav | CC-MAIN-2020-34 | refinedweb | 1,031 | 63.29 |
LoPy doesn't boot from sd card
Hello,
On the pycom github page it says if you have a sd card in you lopy, it will boot from it.
I have the boot.py and the main.py on the sd card. But still it isn't booting.
I have formatted the sd card to fat32.
When i copied the main.py and boot.py it gives me a message that it will be copied without any settings. Might this be the problem? or am i doing something else wrong?
Kind regards.
Thanks for the clear explanation.
I asked again because i read somewhere that it was possible, but i can't find that page anymore. But maybe that was the original pyboard too.
Well, then I will continue without :)
- jmarcelino last edited by jmarcelino
@mmarkvoort
As livius explained the instructions you found are for the original pyboard - not the Pycom boards! The pyboard has a SD card slot on the board itself so the pins are already allocated and dedicated to it.
On the Pycom boards the SD card is an optional add-on, you might have used the pins to attach other devices which could get confused or even damaged if the LoPy tries to communicate with them as if they were an SD card.
With this in mind I don't think automatically booting from the SD card will be possible, at least not in a general way that is safe and without establishing some sort of resource discovery/plug'n'play communication protocol between the LoPy and Expansion boards (something nice but maybe be a bit outside the scope of these boards)
My LoPy can detect de SD card and i can run from the SD card.
But I still can't boot from it.
Anyone who managed to boot from the SD card?
Your suggestion is working, thanks for that!
I have added the code in the main.py in /flash. In my boot.py in /flash I mount my sd card like you said, but not with the execfile('/sd/boot.py'). When the main of /flash is executed, the main of /sd will automatically be executed.
This is working now, but I still think this isn't like it supposed to be.
Maybe any one else can help?
I suppose this is not valid for pycom only pyboard
You must mount sd card self, e.g.
from machine import SD try: sd = SD() os.mount(sd, '/sd') execfile('/sd/boot.py') except: sd = None
if (sd<>None): execfile('/sd/main.py')
but maybe i am wrong and sd should be mounted automatically
then someone fix me | https://forum.pycom.io/topic/701/lopy-doesn-t-boot-from-sd-card/6 | CC-MAIN-2020-50 | refinedweb | 443 | 75.71 |
In article <20021123051628.GA3658@krispykreme>,Anton Blanchard <anton@samba.org> wrote:>>_t32 == 32 bit version, its not the size. egOh, I realize that. What I do not see is the point of the typedefs ATALL. They must go. They are crap. They have no reason for theirexistence.>asm-ia64/ia32.h: typedef unsigned short __kernel_ipc_pid_t32;>asm-mips64/posix_types.h: typedef int __kernel_ipc_pid_t32;>asm-parisc/posix_types.h: typedef unsigned short __kernel_ipc_pid_t32;>asm-ppc64/ppc32.h: typedef unsigned short __kernel_ipc_pid_t32;>asm-sparc64/posix_types.h: typedef unsigned short __kernel_ipc_pid_t32;>asm-x86_64/ia32.h: typedef unsigned short __kernel_ipc_pid_t32;>>Or do you mean we should use typedef u16 __kernel_ipc_pid_t32? Yeah,>I can understand that.That helps, by removing half of the reason why they are crap - the usingof types that are not architecture-safe in a generic ABI file. But theother half of the reason is still there:It doesn't remove the rest of the reason: that "__kernel_" prefix ismeaningless (since the type shouldn't be visible in a non-kernelnamespace ANYWAY, and that is the only reason for the prefix in thefirst place). Basically, you have two cases: - you have types that are _truly_ generic 32-bit compatibility stuff, and are the same on all architectures that use this compatibility layer. But if they are truly generic, they shouldn't need a new typedef AT ALL. You should just realize that "loff_t" is always a "s64", and then just use s64 in the compatibility functions/structures. No need to make up some new typedef. - You have types (like the above) where the compatibility layer actually has _different_ types for different architectures. In which case they should be in an architecture-specific file, not in some generic file. And the name should not be "__kernel_xxxx_t32", but "compat32_xxxx_t" or something.In _neither_ case is it valid to have a generic architecture-independentfile that makes up new types. See? And THAT is why I thin kthe patch iscrud. Linus-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/2002/11/25/107 | CC-MAIN-2013-20 | refinedweb | 351 | 60.51 |
Hello, Kent.I've been reading the code and am still very far from understandingthe.* It's unfortunate but true that different parts of kernel are held to different standards in terms of conformance to overall style and structure. Code for obscure device, for example, is allowed to be way more weird than common core code. That said, one thing which is generally frowned upon is bringing in lots of foreign constructs because that tends to make the code much more difficult to follow for other people than plain silly code. Even for drivers, code with a lot of wrappers and foreign constructs (synchronization, data structure...) tend to get nacked and are recommended to convert to existing infrastructure even if that ends up, say, more verbose code. It is also true that new constructs and mechanisms are constantly being added to kernel and the ones used by bcache could be useful enough to have; however, with my currently limited understanding, the oddities seem too much.* Too many smart macros. Macros suck. Smart ones double suck.* For file internal ones, it's okay to be somewhat relaxed with namespace separation but bcache code seems to be going too far. It also becomes a lot worse with macros as warnings and errors from compiler get much more difficult to decipher. e.g. things like next() and end() macros are calling for trouble.* Somewhat related to the above, I'm not a fan of super-verbose symbols but I *hope* that the variable names were just a tiny bit more descriptive. At least, the ones used as arguments.* The biggest thing that I dislike about closure is that it's not clear what it does when I see one. Is it a refcount, synchronization construct or asynchronous execution mechanism? To me, it seems like a construct with too many purposes and too much abstraction, which tends to make it difficult to understand, easy to misuse and difficult to debug. IMHO, constructs like this could seem very attractive to small group of people with certain concepts firmly on their minds; however, one man's paradise is another man's hell and we're often better off without either. In many ways, closure feels like kobject and friends. I'd like to recommend using something more concerete even if that means more verbosity. ie. if there are lots of bio sequencing going on, implement and use bio sequencer. That's way more concerete and concerete stuff tends to be much easier to wrap one's head around mostly because it's much easier to agree upon for different people and they don't have to keep second-guessing what the original author would have on his/her mind while implementing it.point so I might change my mind but these were the impressions I gotupto this point. I'll keep on reading. Specific comments follow.On Wed, May 09, 2012 at 11:10:17PM -0400, Kent Overstreet wrote:> +#define simple_strtoint(c, end, base) simple_strtol(c, end, base)> +#define simple_strtouint(c, end, base) simple_strtoul(c, end, base)> +> +#define STRTO_H(name, type) \> +int name ## _h(const char *cp, type *res) \> +{ \...> +} \> +EXPORT_SYMBOL_GPL(name ## _h);> +> +STRTO_H(strtoint, int)> +STRTO_H(strtouint, unsigned int)> +STRTO_H(strtoll, long long)> +STRTO_H(strtoull, unsigned long long)Function defining macros == bad. Can't it be implemented with acommon backend function with wrappers implementing limits? Why notuse memparse()?> +ssize_t hprint(char *buf, int64_t v)> +{> + static const char units[] = "?kMGTPEZY";> + char dec[3] = "";> + int u, t = 0;> +> + for (u = 0; v >= 1024 || v <= -1024; u++) {> + t = v & ~(~0 << 10);> + v >>= 10;> + }> +> + if (!u)> + return sprintf(buf, "%llu", v);> +> + if (v < 100 && v > -100)> + sprintf(dec, ".%i", t / 100);> +> + return sprintf(buf, "%lli%s%c", v, dec, units[u]);> +}> +EXPORT_SYMBOL_GPL(hprint);Not your fault but maybe we want integer vsnprintf modifier for this.Also, sprintf() sucks.> +ssize_t sprint_string_list(char *buf, const char * const list[],> + size_t selected)> +{> + char *out = buf;> +> + for (size_t i = 0; list[i]; i++)> + out += sprintf(out, i == selected ? "[%s] " : "%s ", list[i]);> +> + out[-1] = '\n';> + return out - buf;> +}> +EXPORT_SYMBOL_GPL(sprint_string_list);sprintf() sucks.> +bool is_zero(const char *p, size_t n)> +{> + for (size_t i = 0; i < n; i++)This doesn't build. While loop var decl in for loop is nice, thekernel isn't built in c99 mode. If you want to enable c99 modekernel-wide, you're welcome to try but you can't flip thatper-component.> + if (p[i])> + return false;> + return true;> +}> +EXPORT_SYMBOL_GPL(is_zero);>> +int parse_uuid(const char *s, char *uuid)> +{> + size_t i, j, x;> + memset(uuid, 0, 16);> +> + for (i = 0, j = 0;> + i < strspn(s, "-0123456789:ABCDEFabcdef") && j < 32;> + i++) {> + x = s[i] | 32;> +> + switch (x) {> + case '0'...'9':> + x -= '0';> + break;> + case 'a'...'f':> + x -= 'a' - 10;> + break;> + default:> + continue;> + }> +> + if (!(j & 1))> + x <<= 4;> + uuid[j++ >> 1] |= x;> + }> + return i;> +}> +EXPORT_SYMBOL_GPL(parse_uuid);Hmmm... can't we just enforce fixed format used by vsnprintf()?> +void time_stats_update(struct time_stats *stats, uint64_t start_time)> +{> + uint64_t now = local_clock();> + uint64_t duration = time_after64(now, start_time)> + ? now - start_time : 0;> + uint64_t last = time_after64(now, stats->last)> + ? now - stats->last : 0;> +> + stats->max_duration = max(stats->max_duration, duration);> +> + if (stats->last) {> + ewma_add(stats->average_duration, duration, 8, 8);> +> + if (stats->average_frequency)> + ewma_add(stats->average_frequency, last, 8, 8);> + else> + stats->average_frequency = last << 8;> + } else> + stats->average_duration = duration << 8;> +> + stats->last = now ?: 1;> +}> +EXPORT_SYMBOL_GPL(time_stats_update);if {} else {}Even if one of the branches is single line. Also, I'm not sure this(and a few others) is general enough to be common utility.> +#ifdef CONFIG_BCACHE_LATENCY_DEBUG> +unsigned latency_warn_ms;> +#endif> +> +#ifdef CONFIG_BCACHE_EDEBUG> +> +static void check_bio(struct bio *bio)> +{> + unsigned i, size = 0;> + struct bio_vec *bv;> + struct request_queue *q = bdev_get_queue(bio->bi_bdev);New line missing.> + BUG_ON(!bio->bi_vcnt);> + BUG_ON(!bio->bi_size);> +> + bio_for_each_segment(bv, bio, i)> + size += bv->bv_len;> +> + BUG_ON(size != bio->bi_size);> + BUG_ON(size > queue_max_sectors(q) << 9);> +> + blk_recount_segments(q, bio);> + BUG_ON(bio->bi_phys_segments > queue_max_segments(q));> +}...> +void bio_map(struct bio *bio, void *base)> +{> + size_t size = bio->bi_size;> + struct bio_vec *bv = bio->bi_inline_vecs;> +> + BUG_ON(!bio->bi_size);> + bio->bi_vcnt = 0;> + bio->bi_io_vec = bv;I'd prefer these assignments didn't have indentations.> +.> + if (base) {> + bv->bv_page = is_vmalloc_addr(base)> + ? vmalloc_to_page(base)> + : virt_to_page(base);> +> + base += bv->bv_len;> + }> +> + size -= bv->bv_len;> + }> +}> +EXPORT_SYMBOL_GPL(bio_map);> +> +#undef bio_alloc_pagesWhy is this undef necessary? If it's necessary, why isn't there anyexplanation?> +int bio_alloc_pages(struct bio *bio, gfp_t gfp)> +{> + int i;> + struct bio_vec *bv;New line missing.> + bio_for_each_segment(bv, bio, i) {> + bv->bv_page = alloc_page(gfp);> + if (!bv->bv_page) {> + while (bv-- != bio->bi_io_vec + bio->bi_idx)> + __free_page(bv->bv_page);> + return -ENOMEM;> + }> + }> + return 0;> +}> +EXPORT_SYMBOL_GPL(bio_alloc_pages);> +> +struct bio *bio_split_front(struct bio *bio, int sectors, bio_alloc_fn *_alloc,> + gfp_t gfp, struct bio_set *bs)> +{> + unsigned idx, vcnt = 0, nbytes = sectors << 9;> + struct bio_vec *bv;> + struct bio *ret = NULL;> +> + struct bio *alloc(int n)> + {> + if (bs)> + return bio_alloc_bioset(gfp, n, bs);> + else if (_alloc)> + return _alloc(gfp, n);> + else> + return bio_kmalloc(gfp, n);> + }These are now separate patch series, right? But, please don't usenested functions. Apart from being very unconventional (does gnu99even allow this?), the implicit outer scope access is dangerous whenmixed with context bouncing which is rather common in kernel. We(well, at least I) actually want cross stack frame accesses to beexplicit.> +unsigned popcount_64(uint64_t x)> +{> + static const uint64_t m1 = 0x5555555555555555LLU;> + static const uint64_t m2 = 0x3333333333333333LLU;> + static const uint64_t m4 = 0x0f0f0f0f0f0f0f0fLLU;> + static const uint64_t h01 = 0x0101010101010101LLU;> +> + x -= (x >> 1) & m1;> + x = (x & m2) + ((x >> 2) & m2);> + x = (x + (x >> 4)) & m4;> + return (x * h01) >> 56;> +}> +EXPORT_SYMBOL(popcount_64);> +> +unsigned popcount_32(uint32_t x)> +{> + static const uint32_t m1 = 0x55555555;> + static const uint32_t m2 = 0x33333333;> + static const uint32_t m4 = 0x0f0f0f0f;> + static const uint32_t h01 = 0x01010101;> +> + x -= (x >> 1) & m1;> + x = (x & m2) + ((x >> 2) & m2);> + x = (x + (x >> 4)) & m4;> + return (x * h01) >> 24;> +}> +EXPORT_SYMBOL(popcount_32);How are these different from bitmap_weight()?> +#ifndef USHRT_MAX> +#define USHRT_MAX ((u16)(~0U))> +#define SHRT_MAX ((s16)(USHRT_MAX>>1))> +#endif...These compat macros can be removed for upstream submission, right?> +#define BITMASK(name, type, field, offset, size) \> +static inline uint64_t name(const type *k) \> +{ return (k->field >> offset) & ~(((uint64_t) ~0) << size); } \> + \> +static inline void SET_##name(type *k, uint64_t v) \> +{ \> + k->field &= ~(~((uint64_t) ~0 << size) << offset); \> + k->field |= v << offset; \> +}More function defining macros.> +#define DECLARE_HEAP(type, name) \> + struct { \> + size_t size, used; \> + type *data; \> + } name> +> +#define init_heap(heap, _size, gfp) \Ummm.... so, essentially templates done in macros. Please don't dothat. Definitely NACK on this.> +#define DECLARE_FIFO(type, name) \> + struct { \> + size_t front, back, size, mask; \> + type *data; \> + } name> +> +#define fifo_for_each(c, fifo) \Ditto. Templates are already yucky enough even with compiler support.IMHO, it's a horrible idea to try that with preprocessor in C.> +#define DECLARE_ARRAY_ALLOCATOR(type, name, size) \> + struct { \> + type *freelist; \> + type data[size]; \> + } nameDitto.> +#define strtoi_h(cp, res) \> + (__builtin_types_compatible_p(typeof(*res), int) \> + ? strtoint_h(cp, (void *) res) \> + :__builtin_types_compatible_p(typeof(*res), long) \> + ? strtol_h(cp, (void *) res) \> + : __builtin_types_compatible_p(typeof(*res), long long) \> + ? strtoll_h(cp, (void *) res) \> + : __builtin_types_compatible_p(typeof(*res), unsigned int) \> + ? strtouint_h(cp, (void *) res) \> + : __builtin_types_compatible_p(typeof(*res), unsigned long) \> + ? strtoul_h(cp, (void *) res) \> + : __builtin_types_compatible_p(typeof(*res), unsigned long long)\> + ? strtoull_h(cp, (void *) res) : -EINVAL)Is this *really* necessary?> +#define strtoul_safe(cp, var) \> +({ \> + unsigned long _v; \> + int _r = strict_strtoul(cp, 10, &_v); \> + if (!_r) \> + var = _v; \> + _r; \> +})> +> +#define strtoul_safe_clamp(cp, var, min, max) \> +({ \> + unsigned long _v; \> + int _r = strict_strtoul(cp, 10, &_v); \> + if (!_r) \> + var = clamp_t(typeof(var), _v, min, max); \> + _r; \> +})> +> +#define snprint(buf, size, var) \> + snprintf(buf, size, \> + __builtin_types_compatible_p(typeof(var), int) \> + ? "%i\n" : \> + __builtin_types_compatible_p(typeof(var), unsigned) \> + ? "%u\n" : \> + __builtin_types_compatible_p(typeof(var), long) \> + ? "%li\n" : \> + __builtin_types_compatible_p(typeof(var), unsigned long)\> + ? "%lu\n" : \> + __builtin_types_compatible_p(typeof(var), int64_t) \> + ? "%lli\n" : \> + __builtin_types_compatible_p(typeof(var), uint64_t) \> + ? "%llu\n" : \> + __builtin_types_compatible_p(typeof(var), const char *) \> + ? "%s\n" : "%i\n", var)Ditto.I'm gonna stop here. It should be pretty clear what I'm bitchingabout by now. :) Please make it C and, better, kernel C.Thanks.--tejun | http://lkml.org/lkml/2012/5/22/423 | CC-MAIN-2013-20 | refinedweb | 1,613 | 57.06 |
Frameworks like Bootstrap tend to come with a lot of CSS. Often you use only a small part of it. Typically, you bundle even the unused CSS. It's possible, however, to eliminate the portions you aren't using.
PurifyCSS is a tool that can achieve this by analyzing files. It walks through your code and figures out which CSS classes are being used. Often there is enough information for it to strip unused CSS from your project. It also works with single page applications to an extent.
uncss is a good alternative to PurifyCSS. It operates through PhantomJS and performs its work differently. You can use uncss itself as a PostCSS plugin.
You have to be careful if you are using CSS Modules. You have to whitelist the related classes as discussed in purifycss-webpack readme.
To make the demo more realistic, let's install Pure.css, a small CSS framework, as well and refer to it from the project so that you can see PurifyCSS in action. These two projects aren't related in any way despite the naming.
npm install purecss --save
To make the project aware of Pure.css,
import it:
src/index.js
import "purecss";...
The
importworks because webpack will resolve against
"browser": "build/pure-min.css",field in the package.json file of Pure.css due to resolve.mainFields. Webpack will try to resolve possible
browserand
modulefields before looking into
main.
You should also make the demo component use a Pure.css class, so there is something to work with:
src/component.js
export default (text = "Hello world") => { const element = document.createElement("div");element.className = "pure-button";element.innerHTML = text; return element; };
If you run the application (
npm start), the "Hello world" should look like a button.
Building the application (
npm run build) should yield output:
Hash: 36bff4e71a3f746d46fa Version: webpack 4.1.1 Time: 739ms Built at: 3/16/2018 4:26:49 PM Asset Size Chunks Chunk Names main.js 747 bytes 0 [emitted] main main.css 16.1 KiB 0 [emitted] main index.html 220 bytes [emitted] ...
As you can see, the size of the CSS file grew, and this is something to fix with PurifyCSS.
Using PurifyCSS can lead to significant savings. In the example of the project, they purify and minify Bootstrap (140 kB) in an application using ~40% of its selectors to mere ~35 kB. That's a big difference.
purifycss-webpack allows to achieve similar results. You should use the
MiniCssExtractPlugin with it for the best results. Install it and a glob helper first:
npm install glob purifycss-webpack purify-css --save-dev
You also need PurifyCSS configuration as below:
webpack.parts.js
const PurifyCSSPlugin = require("purifycss-webpack"); exports.purifyCSS = ({ paths }) => ({ plugins: [new PurifyCSSPlugin({ paths })], });
Next, the part has to be connected with the configuration. It's essential the plugin is used after the
MiniCssExtractPlugin; otherwise, it doesn't work:
webpack.config.js
...const path = require("path"); const glob = require("glob");const parts = require("./webpack.parts");const PATHS = { app: path.join(__dirname, "src"), };... const productionConfig = merge([ ...parts.purifyCSS({ paths: glob.sync(`${PATHS.app}/**/*.js`, { nodir: true }), }),]);
The order matters. CSS extraction has to happen before purifying.
If you execute
npm run build now, you should see something:
Hash: 36bff4e71a3f746d46fa Version: webpack 4.1.1 Time: 695ms Built at: 3/16/2018 4:29:54 PM Asset Size Chunks Chunk Names main.js 747 bytes 0 [emitted] main main.css 2.07 KiB 0 [emitted] main index.html 220 bytes [emitted] ...
The size of the style has decreased noticeably. Instead of 16k, you have roughly 2k now. The difference would be even more significant for more massive CSS frameworks.
PurifyCSS supports additional options including
minify. You can enable these through the
purifyOptions field when instantiating the plugin. Given PurifyCSS cannot pick all of the classes you are always using, you should use
purifyOptions.whitelist array to define selectors which it should leave in the result no matter what.
Using PurifyCSS loses CSS source maps even if you have enabled them with loader specific configuration due to the way it works underneath..
webpack-critical and html-critical-webpack-plugin implement the technique as a
HtmlWebpackPlugin plugin. isomorphic-style-loader achieves the same using webpack and React.
critical-path-css-tools by Addy Osmani lists other related tools.
Using PurifyCSS can lead to a significant decrease in file size. It's mainly valuable for static sites that rely on a massive CSS framework. The more dynamic a site or an application becomes, the harder it becomes to analyze reliably.
To recap:
MiniCssExtractPlugin.. | https://survivejs.com/webpack/styling/eliminating-unused-css/index.html | CC-MAIN-2018-34 | refinedweb | 761 | 53.07 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.