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 |
|---|---|---|---|---|---|
Using C# and Wix# to Build Windows Installer Packages
- |
-
-
-
-
-
-
Read later
Reading List
We brought back Oleg Shilo, author of the CS-Script for Notepad++, to talk about Wix#.
InfoQ: For the benefit of our readers who haven't heard of it before, what is WiX#?
Oleg: Wix# (WixSharp) is a deployment authoring framework targeting Windows Installer (MSI). Wix# allows building complete MSI setups from a deployment specification expressed with C# syntax. The typical Wix# source file for building MSI contains plain-vanilla C# code, which uses a C# class structure to define (mimic) WiX entities.
Wix# answers many MSI authoring challenges. It solves the common MSI/WiX authoring limitations in a very elegant and yet unorthodox way. Wix# follows the steps of other transcompilers like Script#, CoffeeScript or GWT by using source code of a more manageable syntax (C# in this case) to produce the desired source code of a less manageable syntax (WiX). A "more manageable syntax" in this context means less verbose and more readable code. The code with a better compile-time error checking and availability of the advanced tools.
Wix# also removes any need to develop MSI sub-modules (Custom Actions) in a completely different language (e.g. C++) by allowing both components and behavior to be defined in the same language (C#). This also allows homogeneous, simplified and more consistent source code structure.
But what is even more important is that Wix# provides an abstraction layer that hides all the complexity and unintuitive nature of MSI/WiX and allows expressing the deployment algorithm in a more natural way. The following is a typical Wix# example that demonstrates a Wix# script for building an MSI file for installation of "My App" product:using System; using WixSharp; class Script { static public void Main() { var project = new Project("My App", new Dir(@"%ProgramFiles%\My Company\My App", new File(@"\\BuildServer\LatestRelease\Bin\MyApp.exe"), new File(@"\\BuildServer\LatestRelease\Bin\MyApp.exe.config"), new File(@"\\BuildServer\LatestRelease\Docs\readme.txt"))); project.GUID = new Guid("6f330b47-2577-43ad-9095-1861ba25889b"); Compiler.BuildMsi(project); } }
Of course Wix# can handle more complex scenarios (Custom Actions or even custom UI written in WPF or WinForms) but the sample above is a perfect demonstration of what Wix# is really about.
Wix# belongs to the CS-Script toolset - an Open Source script engine suite for executing C# scripts. The InfoQ readers may be already familiar with it as I have already described it in my previous interview about CS-Script Notepad++ plugin.
InfoQ: Why did you choose to express Wix# in the form of an API instead of a domain specific language?
Oleg: The objective of Wix# is not to replace XML syntax with a different syntax. The alternative syntax would only address one of many practical limitations of the MSI+WiX combination. With Wix# I wanted to bring the deployment development back to the main stream programming. I wanted to move it closer to the developers. I wanted the very same developers who creates software to be able to create very quickly and comfortably deployment solutions as well. DSL would mean that developers need to learn yet another syntax and also to suffer from absence of the code assistance tools (e.g. Intellisense). Most likely DSL would also require developing Custom Actions in another syntax again. Instead, I wanted C# and your favorite IDE to become a one-stop-shop for the deployment development. Then your development team doesn't need a designated WiX-guy, the usual programming skill set is sufficient enough for implementing practically any deployment algorithm.
Though there is a less obvious reason for not choosing DLS approach. The typical DSL story is either a translation of one syntax to another one or a conversion of one programming model to another one. The translation story has very little practical value in case of WiX. While it is simple to implement it would only map the original WiX syntax one-to-one to a new simpler one and leave the all MSI limitations unaffected. From the other hand, conversion to a new clean and more intuitive programming model is exactly what WiX is needed. Such a conversion is usually achieved with high-level generic programming languages (C# in case of Wix#). And after that the new programming model is typically bound to a new DSL syntax. However in Wix# case this last step (new syntax binding) wouldn't bring any extra value. Wast majority of Windows developers is already comfortable or at least familiar with .NET languages. Thus the new DSL syntax would only bring a new overhead. So I decided to stick with C#.
Saying that, a simple translation based DSL on top of Wix# programming model may make some sense and it is actually easy to implement. But it is a completely different story...
InfoQ: Aside from the complexity of the WiX format, what do you feel is the biggest hindrance for WiX adoption?
Oleg: This is a very good question. Yes WiX is indeed very complex but the complexity isn't the real obstacle for the WiX adoption. Close ties to MSI are. WiX dramatically simplifies access to the MSI programming model. However this model is the core of the problem not the difficulties with accessing it. Thus WiX users still have to put up with the nuisances of MSI but now via XML syntax.
Here I have to stop and say a few words in defense of WiX. The faulty MSI programming model isn't WiX's fault. In fact considering what WiX did for MSI it would be almost impossible to expect WiX to address the MSI limitations. In order to really appreciate WiX we need to look back at the evolution of Microsoft deployment technologies.
When MSI was introduced it was trying to be the 'answer for everything'. And as with many Microsoft technologies it was over-engineered from the start. It hasn't changed sense then. Microsoft implemented many complicated MSI features that have very little practical value today (e.g. components, MSM, advertised installation...).
And there is no surprise that Microsoft recognized the problem and got rid of all these features in their latest attempt - ClickOnce. ClickOnce is an extremely lean deployment framework. In fact Microsoft completely ditched the MSI concept and implemented ClickOnce from scratch as an MSI alternative. It is light, clever and minimalistic (in a good way). Though it is completely closed and neither customizable nor extendable.
On top of the internal flaws MSI is extremely development unfriendly. MSI setup file is a database file. The deployment logic is expressed via the data in the tables. Microsoft expected the MSI development to be conducted by entering the data manually, field by field, with their MSI-table editor Orca. This gave a fantastic revenue opportunity for InstallShiled (by offering overpriced MSI support) but left developers with practically nothing. Then WiX happened. And it stopped the "MSI chaos". WiX absolutely deserves all credit for bringing the order and making authoring MSI into a software development (not data entry) activity - "building the binary from the source file". Thus WiX allowed to populate those MSI tables from the XML file instead of doing it manually. However it did not changed the essence of the MSI development. With WiX the developers still had (and have) to think "in MSI Tables".
Just a couple weeks ago one of Wix# users shared his work around for a simple registry-only MSI scenario. The problem was that MSI/WiX required the install directory to be defined...even if you are not going to install any files but registry key only. The work around was to define dummy install directory and then ... define "remove directory" action to avoid the physical creation of the dummy directory during the installation. All this is not because of the deployment requirements but because of the MSI mind bending limitation: Directory table must have at least a single entry.
Wix# from another hand allows automatic creation of the dummy directory entry and hiding the MSI/WIX complexity completely:var project = new Project("MyProduct", new RegValue(RegistryHive.LocalMachine, "Software\\My Company\\My Product", "Message", "Hello"), new RegValue(RegistryHive.LocalMachine, "Software\\My Company\\My Product", "Count", 777)); project.GUID = new Guid("6f330b47-2577-43ad-9095-1861ba25889b"); Compiler.BuildMsi(project);
The WiX equivalent of the code above will take about 40 lines of very dense XML content and batch file for executing WiX compiler and linker.
"Dummy directory" is not the only case. There are plenty of other MSI/WiX syntactic "obstructions" that are avoided in Wix#.
Many WiX gurus think that being so close to MSI architecture is a strength of WiX because it allows the ultimate access to the MSI functionality. I disagree. I believe it prevents the whole technology adoption because it ignores developer needs. Thus WiX is completely MSI-oriented instead of being developer oriented. But we shouldn't blame WiX for this. I am not even convinced WiX should be concerned about this at all. In my opinion there should be another layer that would take any deployment requirement/specification (e.g. Wix# file) and convert it into MSI-DB specification (WiX file).
WiX is playing the same role in the MSI environment as IL in .NET. IL allows the ultimate access to the CLR functionality but yet no one is using it for the development. We have all .NET high level languages for this. Thus if I rephrase your question as: "What is the biggest hindrance for IL adoption?" it will be easy to answer. There is no need for such an adoption. We have much better development options than IL (while IL is a vital part of the whole.NET technology). And Wix# is an attempt to bring at least one of such "better options" but into MSI domain. Thus Wix# or any similar solution is just a next logical evolutionary step from WiX.
InfoQ: What do you see as the most exciting feature that WX# offers beyond making basic installer packages easier?
Oleg: There are a few very strong features worth to mention.
a. First of all is that unbeatable simplicity of the managed Custom Actions, which comes from the power of the high level programming language (C#):using System; using WixSharp; class Script { static void Main() { var project = new Project("CustomActionTest", new ManagedAction("MyAction", Return.check, When.After, Step.InstallInitialize, Condition.NOT_Installed)); Compiler.BuildMsi(project); } } public class CustomActions { [CustomAction] public static ActionResult MyAction(Session session) { MessageBox.Show("Hello World!", "Embedded Managed CA"); session.Log("Begin MyAction Hello World"); return ActionResult.Success; } }
b. Custom UI is the another one. Wix# not only allows injecting a plain vanilla WinForm dialog into the UI sequence. It also makes it possible to create a complete custom GUI and hook it to the MSI engine at runtime. This fantastic possibility offered by MSI API is completely overlooked by practically all MSI authoring frameworks, while Microsoft uses it in so many products (e.g. Office, Visual Studio setups).
I do consider the UI customization as very controversial deployment technique and discourage (for design reasons) developers from going this way. But I just couldn't ignore the user demands and implemented it anyway. The following is the screenshot of the WPF sample (from the Wix# distro) for the custom UI:
c. The last feature I want to mention is Wix# extensibility. The deployment definition is just a C# classes:var project = new Project("My App", new Dir(@"%ProgramFiles%\My Company\My App", new AllFiles(@"\\BuildServer\LatestRelease\*.*")));
In cases when Wix# functionality is not sufficient you can directly manipulate generated XML (WiX) content my means of the Wix# compiler event handlers (just before the XML is passed to the MSI compiler). You can inject or remove any element or attribute from the XML tree. The distributable samples demonstrate this technique by showing how the ASP.NET web site can be installed by using Wix# native functionality as well as by injecting required XML just before the compilation.
By the way the samples library is so significant that it takes ~95% of the whole Wix# codebase.
At this stage of Wix# life cycle I consider it's core functionality to be practically complete. Thus the new features will rater represent horizontal then vertical evolution. They will be mostly about integration with the development tools and making the developers more comfortable with the framework. My plans include publishing Wix# in NuGet, providing a complete equivalent of the full MSI UI but as an external set of WinForm dialogs, developing dedicated Notepad++ plugin and possibly MSBuild task with the project template (currently Visual Studio handles Wix# as a regular C# project). And of course processing the users feedback.
Wix# is available on CodePlex under the MIT license.domain. For the last 5 years he worked as a Product Leader at Aqsacom Australia (Lawful Interception).
Marvin Fenner
Wix# user, love it! Great interview! Learned a couple helpful things here!
by
Jim Daniels
I used Wix# to do a tricky setup of a .NET dll registered for COM Interop on a Windows 2008 Server. Another team member had done a little WiX XML installer, but looking at the XML and trying to figure out how to make XML "do installer stuff" just made my head hurt. Then I saw the CodeProject Wix# article, and decided to give it a try. What a relief and a pleasure to code an installer in C#!! Yes, there were some tricky parts and quirks, and I had to learn some WiX and Windows Installer in the process, to know what Wix# could and couldn't do. For example, I had to learn how to make installer components 64-bit so they hit the 64-bit registry, using syntax like "{ AttributesDefinition = "Component:Win64=yes" }". But, in the end, it all worked!!
I was able to give our server admin guys a walkthrough of the C# code for the installer before asking them to install it on "their" servers, so they could see what it was doing and trust the process. Having reviewed the source, they were happy to then accept my MSI installer, and install it on the servers with confidence and trust.
Pretty sure I was the Wix# user Oleg mentioned in the article who pointed out the dummy directory left on the target system after a registry-only install. It felt "dirty" leaving a stray directory on the servers after an install. I found some WiX XML syntax and used the XML injection technique to bundle it neatly into my Wix# installer. Then Oleg did a nice enhancement to Wix# that removes the directory in situations like mine. Now I've been bugging him to automatically import .reg files into Wix# to further simplify registry entries deployment, and he has it in process.
There are now a few more Wix# questions and answers on Stack Overflow than there were a couple weeks ago, under the "WixSharp" tag, courtesy of me. WiX XML people have a great helpful presence on Stack Overflow, which also helps Wix# users. The great thing is that you can ask WiX questions, and get WiX XML answers, and then take those answers and use them in your Wix# installer.
I will have to try Oleg's tip in the article:
"The deployment definition is just a C# class"
This will be a huge help in large installs with tons of files to deploy, where the list of files and folders is subject to frequent additions or changes. Website deployments come quickly to mind... new pages, new folders, on an ongoing basis.
For most .NET developers, I believe Wix# + WiX XML (via XML Injection) is so much better of an option for Windows installers than anything else I've seen out there.
Thanks Oleg, for all your fantastic work making this available to .NET developers! | https://www.infoq.com/articles/WixSharp | CC-MAIN-2018-34 | refinedweb | 2,644 | 55.44 |
I wrote this code for the Chef Easy Queries Problem in CPP (Contest Page | CodeChef). It is satisfying the sample cases as well as all the test cases except one (the first test case). I have tried nearly everything, but that case just does not budge.
My algorithm -
Input the values of T,n,k.
Then run a loop T times. Inside this run another loop n times. In the inside loop, ask for Query (Q) and increment the day (day) by 1. Add it to the leftover queries from days before (left). From this quantity subtract (k). If it becomes negative, then break the loop and output the value of day we have.
If the whole loop runs without (left) becoming negative, it means no free days till now. So, we increment the (day) variable by the quotient of (left) upon (k) plus 1.
This is our answer if (left) does not become negative.
I can’t find anything wrong with this, yet I am not able to solve the first test case of this problem. Any help would be appreciated.
#include
using namespace std;
int main() {
long long int T;
cin>>T;
for(long long int i=0;i<T;i++){
long long int n,k,left=0,Q,day=0; cin>>n>>k; for(long long int j=0;j<n;j++){ day++; cin>>Q; left+=Q; left-=k; if(left<0){ cout<<day<<endl; break; } } if(left>=0){ day+=(left/k)+1; cout<<day<<endl; }
}
return 0;
} | https://discuss.codechef.com/t/chef-easy-queries-problem-runtime-error/82657 | CC-MAIN-2021-10 | refinedweb | 251 | 83.25 |
IRC, freenode, #hurd, 2012-04-22
<youpi> btw, I was wondering, when working on namespace mangling, did they think about automatitioning ? <youpi> autopartitioning, I meant <youpi> i.e. with a foo.img file, open foo.img,,part1 <braunr> what are you referring to with namespace mangling <youpi> and voila <youpi> I don't remember the exact term they used <braunr> you mean there is a hurd library that parses names and can direct to different services depending on part of the name ? <youpi> namespace-based_translator_selection <youpi> yes <braunr> i thought it only handled directories <braunr> well, the classical path representation * civodul finds it ugly <youpi> civodul: because of potential conflict, and the not-too-nice ",," part? <youpi> actually I wonder whether using directory access would be nicer <youpi> i.e. you have a foo.gz, just open foo.gz/gunzip to get the unzipped content <youpi> and for foo.img.gz, open foo.img.gz/gunzip/part/1 <civodul> youpi: because of the interpretation of special chars in file names <civodul> users should be free to use any character they like in file names <civodul> foo.gz/gunzip looks nicer to me <youpi> ok, so we agree <youpi> that said, the user could choose the separator <youpi> the namespace can be not run by root for everybody, but just for your shell, run by yourself <antrik> civodul: the user can't use any character anyways... '/' and '\0' are reserved :-P <civodul> antrik: '/' isn't quite reserved on the Hurd :-) <civodul> you could implement dir_lookup such that it does something special about it <civodul> (server-side) <antrik> civodul: as for overloading '/', although I haven't thought it through entirely, I guess that would work for nodes that present as files normally. however, it would *not* work for directory nodes <antrik> which would be quite a serious limitation IMHO <antrik> I can think of various kinds of useful directory translators <antrik> what's more, one of the main use cases I originally had in mind is a policy filter <antrik> you could pass a directory name with a appropriate filter applied to tar for example, so it wouldn't try to follow any translators <antrik> I don't see why taking an obscure prefix like ,, would be much of a problem in practice anyways <antrik> (also, it doesn't strictly prevent the user from having such file names... you just need to escape it if accessing such files through the namespace multiplexer. though admittedly that would need some special handling in *some* programs to work properly) | http://www.gnu.org/software/hurd/community/gsoc/project_ideas/namespace-based_translator_selection/discussion.html | CC-MAIN-2016-07 | refinedweb | 424 | 56.49 |
While working for one of my previous projects I came across a requirement where I wanted to transfer my XML data into Java Beans or objects. Many of you also might have faced same scenario. In this article I will show, how you can achieve this functionality using a set of Java libraries called JOX that makes it easy to transfer data between XML documents and Java Beans.
How JOX Works
JOX matches an XML document to the fields of a java bean and will use a DTD when writing an XML document if one is available. Because JOX identifies the Java Bean at runtime, you can transmit XML into different classes.
Other approaches to achieve this functionality are using KBML (Koala Bean Markup Language) and Quick/JXML suite of libraries. KBML has <property> and <value> tags. Quick/JXML gives you the same XML document flexibility as JOX. Only price you pay is that you must use a special schema language called QJML to describe the mapping between XML and Java. With JOX, for e.g. if I have an Address bean that has addressLine1 and addressLine2 properties. You could read in an XML file containing <address-line1> and <address-line2> properties. JOX lets you use any form of XML document and any Java Bean, and you don’t have to create a separate schema to describe the mapping between Java and XML like JXML. This way JOX differs from other two libraries.
JOX has following rules, which need to be followed while using:
JOX is an instant to use and you don’t have to learn any new language or format. JOX readers and writers rip open on to Input/Output Streams, Readers and Writers so you can use them with existing Java IO streams. JOX can also write a bean to a DOM object so we can pass it to the XSLT processor.
Following example shows how to transmit XML data into Java Bean. Here is the XML file sample.xml, from which we will transmit data to Java Bean.
<?xml version="1.0"?>
<SampleRoot>
<colors>red</colors>
<colors>yellow</colors>
<colors>green</colors>
<colors>orange</colors>
<value>44</value>
<price>75</price>
<firstName>Vikas</firstName >
</SampleRoot>
Now as I mentioned, you need to create a Bean with getter/setter methods. Also keep in mind that XML tag names must match bean property names.
For e.g. following are the bean methods (from SampleTest.Java) for tags <value> and <price> respectively.
public int getValue(){
return value;
}
public void setValue(int aValue){
value = aValue;
}
public int getPrice(){
return price;
}
Now TransmitXml.java reads in the XML file and stores its values into SampleBean.
import com.wutka.jox.JOXBeanInputStream;
import java.io.FileInputStream;
JOXBeanInputStream is An InputStream filter that reads XML into a bean. When you read an XML document, you must supply either a class or an object instance. The input stream will attempt to match XML tags to bean attributes in the class/object you supply.
If you supply a class, the input stream will automatically create a new object instance to hold the data.
The stream understands the basic Java data types and their object equivalents, plus strings and dates. Anything else must be a bean. It can also read arrays of any of the supported types or of beans if it tries to read a bean with an indexed property.
If there are XML fields that don't match the bean, it will ignore them. If the data types are not compatible, you will get an exception. At some point the stream will be smart enough to skip over incompatible fields.
public class TransferXml{
public static void main(String[] args){
try{
FileInputStream fIn = new FileInputStream("sample.xml");
JOXBeanInputStream joIn = new JOXBeanInputStream(fIn);
SampleTestBean testBean = (SampleTestBean) joIn.readObject(SampleTestBean.class);
System.out.println(testBean.getFirstName());
System.out.println(testBean.getPrice());
String colors[] = testBean.getColors();
for(int i=0;i<colors.length; i++){
System.out.println(colors[i]);
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
}
Note: Before running the code, download JOX from and put jox116.jar file into classpath so that the java code can find corresponding classes at compile and run time.
JOX understands all the Java primitive types (byte, char, short, int, long, float, double and boolean) and the object-wrapper versions of those types (Byte, Character, Short, etc.). It also understands java.util.Date and String types. If a property is a nested object, it tries to match the nested XML to the nested object. JOX understands indexed properties, too, so it essentially supports arrays.
This way effortlessly you can transmit XML data into Java Beans for any kind of Java application.
About the Author | http://devguru.com/content/features/tutorials/JOX/jox.html | CC-MAIN-2019-13 | refinedweb | 779 | 66.03 |
() {
QueryPerformanceFrequency(&li);
//)
address2 = std::move(myObj.address2);
#endif
};
int main()
perf_startup();
int total_copy_move_count = 0;
int total_vector_resizes = 0;
double total_pushback_time = 0.0;
std::vector<myUserObject> vec;
myUserObject obj;
obj.name = "Stephan T. Lavavej Stephan T. Lavavej Stephan T. Lavavej";
obj.telephone = "314159265 314159265 314159265 314159265 314159265";
obj.address = "127.0.0.0 127.0.0.0 127.0.0.0 127.0.0.0 127.0.0.0 127.0.0.0";
obj.name2 = "Mohammad Usman. Mohammad Usman. Mohammad Usman. ";
obj.telephone2 = "1234567890 1234567890 1234567890 1234567890 1234567890";
obj.address2 = "Republik Of mancunia. Republik Of mancunia Republik Of mancunia";
const long long start = counter();
for (int i = 0; i<1050000; ++i)
{
size_t capacity = vec.capacity();
size_t size = vec.size();
vec.push_back(obj);
if (capacity == size) // indication that vector reallocation has occurred.
{
++total_vector_resizes;
total_copy_move_count += size;
}
const long long finish = counter();
total_pushback_time = (finish-start)*1.0 / frequency();
// print result
std::cout << std::endl;
std::cout << std::fixed;
std::cout << "Total Pushback time: \t" << total_pushback_time << " sec" << std::endl;
std::cout << "Total number of vector reallocations: \t" << total_vector_resizes << std::endl;
std::cout << "Total number of objects copied/moved: \t" << total_copy_move_count << std::endl;
VS2008:
c:\TEMP\STLPerf>cl /EHsc /nologo /W4 /O2 /GL /D_SECURE_SCL=0 rvalue.cpp
rvalue.cpp
Generating code
Finished generating code
c:\TEMP\STLPerf> rvalue.exe
Total Pushback time: 8.309241 sec
Total number of vector reallocations: 36
Total number of objects copied/moved: 3149622
VS2010:
Total Pushback time: 2.335225 secTotal number of vector reallocations: 36Total number of objects copied/moved: 3149622
As you can see that in this specific scenario we are getting more than 3 times performance boost. This gain is due to the fact that the move machinery is used during vector reallocations, which is cheaper as compared to the copy machinery (copy construction and copy assignment). And the bigger your object is and the larger your vector is, the more performance gain you will get. So those of you who use vectors on a big scale, this is something you will surely love. Vector Reallocation (STL Types)
Now the interesting part is that similar to the sample code above, we have implemented move semantics (move constructors and move assignment operators) for our STL types in VS2010. It is worth mentioning here that for some types, in order to improve performance especially in situations where the copy was taking a lot of time such as vector reallocation, we used a trick called “swaptimization” before VS2010. (see pt.#16 in this blog post) Now with the arrival of rvalue references we don’t need that anymore and we have replaced those swaptimization tricks with the rvalue reference machinery and, guess what, we are now even faster. The following example shows one such scenario where we used swaptimization earlier.
long long total_copy_move_count = 0;
long long total_vector_resizes = 0;
std::vector<std::string> v_str;
long long start = counter();
for (int i = 0; i<12000000; ++i)
size_t size = v_str.size();
size_t capacity = v_str.capacity();
v_str.push_back("I think, therefore I am");
if (size == capacity) // indication that vector reallocation has occurred.
{
total_copy_move_count += size;
}
}
long long finish = counter();
total_pushback_time = ((finish - start)*1.0 / frequency());
std::cout << std::endl;
c:\TEMP\STLPerf>cl /EHsc /nologo /W4 /O2 /GL /D_SECURE_SCL=0 swaptimization.cpp
swaptimization.cpp
c:\TEMP\STLPerf> swaptimization.exe
Total Pushback time: 6.717094 sec
Total number of vector reallocations: 42
Total number of objects copied/moved: 35875989
Total Pushback time: 3.780286 sec
You can see that moving to rvalue references hasn’t impacted the performance. In fact, in this particular example, we are almost twice as fast as VS2008. The credit for this gain also goes to rvalue references, not specifically during vector reallocation, but during push_back() instead. As you can see that we are passing a literal string (an rvalue- see footnote) to the function. So the move machinery comes into play here again, giving us another performance boost.
This is all what I have to share in my blog. If you have any questions about performance of STL or in general about STL, please feel free to write to me at: Mohammad.Usman at microsoft.com.
Thanks!
-Usman
* String literals are actually lvalues (C++03 5.1/2), whereas all other literals are rvalues. However, since we’ve got a vector<string>, push_back() takes const string&. This constructs a temporary std::string, which is an rvalue. That’s where move semantics comes into play.
Bog
David LeBlanc and Michael Howard literally wrote the book on “Writing Secure Code”. David has also developed the SafeInt class, a template class that performs “checked” operations on integer types (with a name like SafeInt what else would you expect). In VS2010 we decided to ship the SafeInt class in the box, so users no longer need to go and download it separately and “install” it themselves. Ale Contenti was the main instigator behind this decision and now that VS2010 Beat 1 has shipped, Ale and David meet with Charles from Channel 9 to talk about the class and it uses. We hope you enjoy the video and feel free to post any questions/feedback on the Channel 9 site.
Hello.
The!!!
Hi,
My name is Bogdan Mihalcea and I’m a developer on the C++ Project & Build team. In the last 2 years I worked on a new C++ project system build on top MSBuild.
I’m writing this blog to share some excellent news related to improvements we made to the performance of project conversion since the Beta1 build. This was possible because of the feedback we got from you, and I want to thank you for doing so!
During our development milestones, we had tests reporting that we have a very slow conversion for specific types of projects. They were usually containing many files (1000+) and they had a significant percentage of them containing file level configurations. After we analyzed the root cause and the costs of fixing, we made the assumption that these projects with many file level configurations were not very common, so the impact of the performance in this scenario would be low. Another assumption we made was that the conversion it is a onetime thing so the impact even if big for those rare cases it is a onetime tax. Based on these assumptions we prioritized the fix lower and decided to invest our time in making the performance of main line scenarios better.
Our team has a customer plan which includes the early release of the product through Beta1 and having various face to face meetings with customers. One of these events is the Visual C++ DevLab, which last time we kept in May 09. During this event we noticed that 20% of the customers were experiencing a very slow conversion.
We investigated and we realized that all cases were caused by less than 5% of the projects in the solution, which took the majority of conversion time. One common detail about those few projects is that they were very heavy on file level configurations. From the discussions with the customers we realized that it is unfortunately easy to get in that state due to various reasons (evolutionary codebases, easy to cause human error due to bulk select, bugs in previous conversions, not a easy bulk way to revert the file level configurations to project level).
That pretty much invalidated our assumption that it is not common to get in a situation where a customer can have a project with 1000+ files and more than half have file level configurations. The first assumption was also invalidated from the discussions we had with the customers and from feedback we received from Beta1’s customers, which revealed that even if the projects that have this case are not very common the unfortunate thing is that it is common for customers with hundreds of projects have 1 or 2 of these and that will impact the whole experience of the conversion for a much bigger percentage of the customers, than what we estimated earlier.
Furthermore the second assumption was challenged as well as we learnt from your feedback that conversion might not be a onetime tax as most of the companies prefer to stay for months in a dual state with the development done in parallel on both products and it is common to maintain only the previous version files as a baseline for changes and to reconvert always when the new product is used. Considering the new feature we added in Dev10, native multitargeting, this seems to make this approach even more popular.
After we got all this feedback we acted on it. We analyzed the code paths and we found places where we could optimize for this type of scenarios and made the fix. Below is an extract from our measurements before and after the fix.
Project
Files/vcproj
Configurations
% files in vcproj with FileConfigurations
Previous Conversion Time
Current Conversion Time
Customer
~4000
4
50%
55 min
8 sec
MVP
~5000
8
80%
1h 40min
23 sec
PerfLab test
~200
2
less than 10%
2.8s
1.4s
~200
16
100%
50 min
10 sec
The common case projects (PerfLab test), with only few file level configurations, were impacted too as you can see from the above table. We used pristine lab machines dedicated to performance runs and the results are specific numbers to these machines.
We are constantly on lookout for feedback and we are adjusting our priorities based on it, and we will try to keep you guys up to date with the progress we make.
Regards,
Bogdan Mihalcea
C++ Project & Build
Thanks.
Hello, I’m Mitchell Slep, a developer on the Visual C++ compiler team. I’m very excited to tell you about a new feature in Visual Studio 2010 - C++ IntelliSense can now display compiler-quality syntax and semantic errors as you browse and edit your code!
We display a wavy underline or “squiggle” in your code at the location of the error. Hovering over the squiggle will show you the error message. We also show the error in the Error List window. The squiggles are great for showing you errors in the code you are currently viewing or editing, whereas the Error List window can help you find problems elsewhere in the translation unit, all without doing a build.
We had two scenarios in mind when designing this feature. One is of course productivity – it’s very convenient to be able to fix errors as they happen instead of waiting to discover them after a build, which can save you a lot of time. We also wanted to improve the experience when IntelliSense doesn’t work. IntelliSense has always been a black box – it often worked well, but if it didn’t, you had no idea why. Now IntelliSense has a powerful feedback mechanism that allows you take corrective action – either by fixing errors in your code or making sure your project is configured correctly.
One decision we had to make when designing this feature was how often to update the errors as you edit your code. If we don’t do it often enough, the errors quickly become out of date and irrelevant. But doing it too often can also lead to irrelevant results, like a squiggle under ‘vect’ while you’re in the middle of typing ‘vector’! We also don’t want to hog your CPU with constant background parsing.
We found that a good balance was to wait for 1 second of idle time after you edit or navigate to a new part of the code before beginning to update the errors. In this case ‘idle’ means that you haven’t typed anything and you haven’t navigated to a different part of the code.
We also experimented with some different designs for what to do with existing errors during the short window of time between when you make an edit and when the newly updated errors are available. For instance, one design we tried was to clear all squiggles on the screen immediately after an edit, and then redraw the new errors when they are available. We also considered a variant of this where we only clear the squiggles on the lines below the location of your edit (since making an edit can generally only affect code appearing after it). These designs have the advantage that you never see a stale squiggle, but in usability studies we found that this produced an annoying flickering affect, and also some confusion as to whether a squiggle disappeared because it was fixed or because it was just temporarily being updated. The design we went with was to leave existing squiggles in place after an edit, and then swap them with the new errors when they are available. This works well since the updates are very fast.
One of the technical challenges with this feature was making it fast. As many of you know, large C++ projects can often take several hours to build. One of the ways we get around this is by having IntelliSense focus on a single translation unit at a time (a translation unit is a .cpp file plus all of its included headers). However, even that didn’t give us the kind of responsiveness we wanted for a live-compilation feature like squiggles.
To get even better performance, we’ve developed some innovate incremental parsing techniques that minimize the amount of code we need to parse. This allows IntelliSense to parse your code much faster than the time it would take to do an actual build (or even the time it would take to compile a single .cpp file). The ideas are simple, but are challenging to implement in a complex, context-sensitive language like C++.
When you first open a file, we parse just enough code to build up a global symbol table, skipping over a lot of code (like function-bodies) that only introduces local symbols. Once we’ve built up the symbol table, we lazily parse the code that we skipped “on-demand”. For instance, we only parse the inside of a function body when you actually view it on the screen. If you make changes inside a function body, we are able to reparse just that function body. Of course, all of this only happens during idle time, as described above. These parsing techniques allow us to show you fast, relevant errors even as you edit large, complex code bases.
If your solution already builds with Visual Studio, you will immediately benefit from having accurate syntax and semantic errors reported by IntelliSense as you browse and edit your code. But this feature is also good news for those of you with external build systems. The IntelliSense errors in the Error List window can guide you towards setting up a solution with accurate IntelliSense. For instance, if you load up a solution configured for an external build system, you might see something like this:
Now you know that you need to adjust your Include Path. Making these tweaks to your solution will dramatically improve the quality of IntelliSense you get with an external build system.
It’s been a lot of fun working on this feature and especially dogfooding it – it’s great not to have to do builds all the time! You can preview this feature in Beta 1 and I look forward to hearing your feedback in the comments.
The!
Hi, my name is Boris Jabes. I've been working on the C++ team for over 4 years now (you may have come across my blog, which has gone stale...). Over the past couple of years, the bulk of my time has been spent on re-designing our IDE infrastructure so that we may provide rich functionality for massive code bases. Our goal is to enable developers of large applications that span many millions lines of code to work seamlessly in Visual C++. My colleagues Jim and Mark have already published a number of posts (here, here and here) about this project and with the release of Visual Studio 2010 Beta 1 this week; we're ready to say a lot more. Over the next few weeks, we will highlight some of the coolest features and also delve into some of our design and engineering efforts.
In this post, I want to provide some additional details on how we built some of the core pieces of the C++ language service, which powers features like Intellisense and symbol browsing. I will recap some of the information in the posts I linked to above but I highly recommend reading the posts as they provide a ton of useful detail.
Without going into too much detail, the issue we set about to solve in this release was that of providing rich Intellisense and all of the associated features (e.g. Class View) without sacrificing responsiveness at very high scale. Our previous architecture involved two (in)famous components: FEACP and the NCB. While these were a great way to handle our needs 10+ years ago, we weren’t able to scale these up while also improving the quality of results. Multiple forces were pulling us in directions that neither of these components could handle.
1. Language Improvements. The C++ language grew in complexity and this meant constant changes in many places to make sure each piece was able to grok new concepts (e.g. adding support for templates was a daunting task).
2. Accuracy & Correctness. We need to improve accuracy in the face of this complexity (e.g. VS2005/2008 often gets confused by what we call the “multi-mod” problem in which a header is included differently by different files in a solution).
3. Richer Functionality. There has been a ton of innovation in the world of IDEs and it’s essential that we unlock the potential of the IDE for C++ developers.
4. Scale. The size of ISV source bases has grown to exceed 10+ million lines of code. Arguably the most common (and vocal!) piece of feedback we received about VS2005 was the endless and constant reparsing of the NCB file (this reparsing happened whenever a header was edited or when a configuration changed).
Thus, the first step for us in this project was to come up with a design that would help us achieve these goals.
Our first design decision involved both accuracy and scalability. We needed to decouple the Intellisense operations that require precise compilation information (e.g. getting parameter help for a function in the open cpp file) from the features that require large-scale indexes (e.g. jumping to a random symbol or listing all classes in a project). The architecture of VS2005 melds these two in the NCB and in the process lost precision and caused constant reparsing, which simply killed any hope of scaling. We thus wanted to transition to a picture like this (simplified):
At this point, we needed to fill in the blanks and decide how these components should be implemented. For the database, we wanted a solution that could scale (obviously) and that would also provide flexibility and consistency. Our existing format, the NCB file, was difficult to modify when new constructs were added (e.g. templates) and the file itself could get corrupted leading our users to delete it periodically if things weren’t working properly in the IDE. We did some research in this area and decided to use SQL Server Compact Edition, which is an in-process, file-oriented database that gives us many of the comforts of working with a SQL database. One of the great things of using something like this is that gave us real indexes and a customizable and constant memory footprint. The NCB on the other hand contained no indexes and was mapped into memory.
Finally, we needed to re-invent our parsers. We quickly realized that the only reasonable solution for scalability was to populate our database incrementally. While this seems obvious at first, it goes against the basic compilation mechanism of C++ in which a small change to a header file can change the meaning of every source file that follows, and indeed every source file in a solution. We wanted to create an IDE where changing a single file did not require reparsing large swaths of a solution, thus causing churn in the database and even possibly locking up the UI (e.g. in the case of loading wizards). We needed a parser that could parse C++ files in isolation, without regard to the context in which they were included. Although C++ is a “context sensitive” language in the strongest sense of the word, we were able to write a “context-free” parser for it that uses heuristics to parse C++ declarations with a high degree of accuracy. We named this our “tag” parser, after a similar parser that was written for good old C code long ago. We decided to build something fresh in this case as this parser was quite different than a regular C++ parser in its operation, is nearly stand-alone, and involved a lot of innovative ideas. In the future, we’ll talk a bit more about how this parser works and the unique value it provides.
With the core issue of scalability solved, we still needed to build an infrastructure that could provide highly accurate Intellisense information. To do this, we decided to parse the full “translation unit” (TU) for each open file in the IDE editor* in order to understand the semantics of the code (e.g. getting overload resolution right). Building TUs scales well – in fact, the larger the solution, the smaller the TU is as a percentage of the solution size. Finally, building TUs allows us to leverage precompiled header technology, thus drastically reducing TU build times. Using TUs as the basis for Intellisense would yield highly responsive results even in the largest solutions.
Our requirements were clear but the task was significant. We needed rich information about the translation unit in the form of a high-level representation (e.g. AST) and we needed it available while the user was working with the file. We investigated improving on FEACP to achieve this goal but FEACP was a derivation of our compiler, which was not designed for this in mind (see Mark’s post for details). We investigated building a complete compiler front-end designed for this very purpose but this seemed like an ineffective use of our resources. In the 1980s and 1990s, a compiler front-end was cutting-edge technology that every vendor invested in directly but today, innovation lies within providing rich value on top of the compiler. As a result there has been a multiplication of clients for a front-end beyond code generation and we see this trend across all languages: from semantic colorization and Intellisense to refactoring and static analysis. As we wanted to focus on improving the IDE experience, we identified a third and final option: licensing a front-end component for the purposes of the IDE. While this may seem counter-intuitive, it fit well within our design goals for the product. We wanted to spend more resources on the IDE, focusing on scale and richer functionality and we knew of a state-of-the-art component built by the Edison Design Group (commonly referred to as EDG). The EDG front-end fit the bill as it provides a high-level representation chock-full of the information we wanted to build upon to provide insight in the IDE. The bonus is that already handles all of the world’s gnarly C++ code and their team is first in line to keep up with the language standard.
With all these pieces in place, we have been able to build some great new end-to-end functionality in the IDE, which we’ll highlight over the coming weeks. Here’s a sneak peek at one we’ll talk about next week: live error reporting in the editor.
* - We optimize by servicing as many open files as possible with a single translation unit..
Visual Studio 2010 Beta 1 is now available for download. I've recently blogged about how Visual C++ in VS 2010 Beta 1, which I refer to as VC10 Beta 1, contains compiler support for five C++0x core language features: lambdas, auto, static_assert, rvalue references, and decltype. It also contains a substantially rewritten implementation of the C++ Standard Library, supporting many C++0x standard library features. In the near future, I'll blog about them in Part 4 and beyond of "C++0x Features in VC10", but today I'm going to talk about the STL changes that have the potential to break existing code, which you'll probably want to know about before playing with the C++0x goodies.
Problem 1: error C3861: 'back_inserter': identifier not found
This program compiles and runs cleanly with VC9 SP1:
C:\Temp>type back_inserter.cpp
#include <algorithm>
using namespace std;
int square(const int n) {
return n * n;
int main() {
vector<int> v;
v.push_back(11);
v.push_back(22);
v.push_back(33);
vector<int> dest;
transform(v.begin(), v.end(), back_inserter(dest), square);
for (vector<int>::const_iterator i = dest.begin(); i != dest.end(); ++i) {
cout << *i << endl;
}
C:\Temp>cl /EHsc /nologo /W4 back_inserter.cpp
back_inserter.cpp
C:\Temp>back_inserter
121
484
1089
But it fails to compile with VC10 Beta 1:
back_inserter.cpp(19) : error C3861: 'back_inserter': identifier not found
What's wrong?
Solution: #include <iterator>
The problem was that back_inserter() was used without including <iterator>. The C++ Standard Library headers include one another in unspecified ways. "Unspecified" means that the Standard allows but doesn't require any header X to include any header Y. Furthermore, implementations (like Visual C++) aren't required to document what they do, and are allowed to change what they do from version to version (or according to the phase of the moon, or anything else). That's what happened here. In VC9 SP1, including <algorithm> dragged in <iterator>. In VC10 Beta 1, <algorithm> doesn't drag in <iterator>.
When you use a C++ Standard Library component, you should be careful to include its header (i.e. the header that the Standard says it's supposed to live in). This makes your code portable and immune to implementation changes like this one.
There are probably more places where headers have stopped dragging in other headers, but <iterator> is overwhelmingly the most popular header that people have forgotten to include.
Note: Range Insertion and Range Construction
By the way, when seq is a vector, deque, or list, instead of writing this:
copy(first, last, back_inserter(seq)); // Bad!
You should write this:
seq.insert(seq.end(), first, last); // Range Insertion - Good!
Or, if you're constructing seq, simply write this:
vector<T> seq(first, last); // Range Construction - Good!
They're not only slightly less typing, they're also significantly more efficient. copy()-to-back_inserter() calls push_back() repeatedly, which can trigger multiple vector reallocations. Given forward or better iterators, range insertion and range construction can just count how many elements you've got, and allocate enough space for all of them all at once. This is also more efficient for deque, and you may as well do it for list too.
Problem 2: error C2664: 'std::vector<_Ty>::_Inside' : cannot convert parameter 1 from 'IUnknown **' to 'const ATL::CComPtr<T> *'
C:\Temp>type vector_ccomptr.cpp
#include <atlcomcli.h>
vector<CComPtr<IUnknown>> v;
v.push_back(NULL);
C:\Temp>cl /EHsc /nologo /W4 vector_ccomptr.cpp
vector_ccomptr.cpp
C:\Temp>vector_ccomptr
C:\Temp>
C:\Program Files\Microsoft Visual Studio 10.0\VC\INCLUDE\vector(623) : error C2664: 'std::vector<_Ty>::_Inside' : cannot convert parameter 1 from 'IUnknown **' to 'const ATL::CComPtr<T> *'
with
[
_Ty=ATL::CComPtr<IUnknown>
]
and
T=IUnknown
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
C:\Program Files\Microsoft Visual Studio 10.0\VC\INCLUDE\vector(622) : while compiling class template member function 'void std::vector<_Ty>::push_back(_Ty &&)'
_Ty=ATL::CComPtr<IUnknown>
vector_ccomptr.cpp(9) : see reference to class template instantiation 'std::vector<_Ty>' being compiled
C:\Program Files\Microsoft Visual Studio 10.0\VC\INCLUDE\vector(625) : error C2040: '-' : 'IUnknown **' differs in levels of indirection from 'ATL::CComPtr<T> *'
Solution: Use CAdapt
The Standard containers prohibit their elements from overloading the address-of operator. CComPtr overloads the address-of operator. Therefore, vector<CComPtr<T>> is forbidden (it triggers undefined behavior). It happened to work in VC9 SP1, but it doesn't in VC10 Beta 1. That's because vector now uses the address-of operator in push_back(), among other places.
The solution is to use <atlcomcli.h>'s CAdapt, whose only purpose in life is to wrap address-of-overloading types for consumption by Standard containers. vector<CAdapt<CComPtr<T>>> will compile just fine. In VC10 Beta 1, I added operator->() to CAdapt, allowing v[i]->Something() to compile unchanged. However, typically you'll have to make a few other changes when adding CAdapt to your program. operator.() can't be overloaded, so if you're calling CComPtr's member functions like Release(), you'll need to go through CAdapt's public data member m_T . For example, v[i].Release() needs to be transformed into v[i].m_T.Release() . Also, if you're relying on implicit conversions, CAdapt adds an extra layer, which will interfere with them. Therefore, you may need to explicitly convert things when pushing them back into the vector.
Problem 3: error C2662: 'NamedNumber::change_name' : cannot convert 'this' pointer from 'const NamedNumber' to 'NamedNumber &'
C:\Temp>type std_set.cpp
#include <set>
class NamedNumber {
NamedNumber(const string& s, const int n)
: m_name(s), m_num(n) { }
bool operator<(const NamedNumber& other) const {
return m_num < other.m_num;
string name() const {
return m_name;
int num() const {
return m_num;
void change_name(const string& s) {
m_name = s;
private:
string m_name;
int m_num;
void print(const set<NamedNumber>& s) {
for (set<NamedNumber>::const_iterator i = s.begin(); i != s.end(); ++i) {
cout << i->name() << ", " << i->num() << endl;
set<NamedNumber> s;
s.insert(NamedNumber("Hardy", 1729));
s.insert(NamedNumber("Fermat", 65537));
s.insert(NamedNumber("Sophie Germain", 89));
print(s);
cout << "--" << endl;
set<NamedNumber>::iterator i = s.find(NamedNumber("Whatever", 1729));
if (i == s.end()) {
cout << "OH NO" << endl;
} else {
i->change_name("Ramanujan");
C:\Temp>cl /EHsc /nologo /W4 std_set.cpp
std_set.cpp
C:\Temp>std_set
Sophie Germain, 89
Hardy, 1729
Fermat, 65537
--
Ramanujan, 1729
std_set.cpp(55) : error C2662: 'NamedNumber::change_name' : cannot convert 'this' pointer from 'const NamedNumber' to 'NamedNumber &'
Conversion loses qualifiers
Solution: Respect set Immutability
The problem is modifying set/multiset elements.
In C++98/03, you could get away with modifying set/multiset elements as long as you didn't change their ordering. (Actually changing their ordering is definitely crashtrocity, breaking the data structure's invariants.)
C++0x rightly decided that this was really dangerous and wrong. Instead, it flat-out says that "Keys in an associative container are immutable" (N2857 23.2.4/5) and "For [set and multiset], both iterator and const_iterator are constant iterators" (/6).
VC10 Beta 1 enforces the C++0x rules.
There are many alternatives to modifying set/multiset elements.
· You can use map/multimap, separating the immutable key and modifiable value parts.
· You can copy, modify, erase(), and re-insert() elements. (Keep exception safety and iterator invalidation in mind.)
· You can use set/multiset<shared_ptr<T>, comparator>, being careful to preserve the ordering and proving once again that anything can be solved with an extra layer of indirection.
· You can use mutable members (weird) or const_cast (evil), being careful to preserve the ordering. I strongly recommend against this.
I should probably mention, before someone else discovers it, that in VC10 Beta 1 we've got a macro called _HAS_IMMUTABLE_SETS . Defining it to 0 project-wide will prevent this C++0x rule from being enforced. However, I should also mention that _HAS_IMMUTABLE_SETS is going to be removed after Beta 1. You can use it as a temporary workaround, but not as a permanent one.
Problem 4: Specializing stdext::hash_compare
If you've used the non-Standard <hash_set> or <hash_map> and specialized stdext::hash_compare for your own types, this won't work anymore, because we've moved it to namespace std. <hash_set> and <hash_map> are still non-Standard, but putting them in namespace stdext wasn't accomplishing very much.
Solution: Use <unordered_set> or <unordered_map>
TR1/C++0x <unordered_set> and <unordered_map> are powered by the same machinery as <hash_set> and <hash_map>, but the unordered containers have a superior modern interface. In particular, providing hash and equality functors is easier.
If you still want to use <hash_set> and <hash_map>, you can specialize std::hash_compare, which is where it now lives. Or you can provide your own traits class.
By the way, for those specializing TR1/C++0x components, you should be aware that they still live in std::tr1 and are dragged into std with using-declarations. Eventually (after VC10) this will change.
This isn't an exhaustive list, but these are the most common issues that we've encountered. Now that you know about them, your upgrading experience should be more pleasant.
Stephan T. Lavavej
Visual C++ Libraries Developer
Hello, my name is Xiang Fan and I am a developer on the C++ Shanghai team.
Today I’d like to talk about two linker options related to security: /DYNAMICBASE and /NXCOMPAT.
These two options are introduced in VS2005, and target to improve the overall security of native applications.
You can set these two options explicitly in VS IDE:
These two options have three available values in the IDE: On, Off and Default.
They are set to “On” if you create native C++ application using VS2008 wizard.
When VS2008 upgrades projects created by older version of VC which doesn’t support these options, it will set them to “Off” after upgrade.
If you set them to “Default”, linker will treat it as “Off”.
After several years adoption, we plan to change the behavior of “Default” to “On” in VS2010 to reinforce the security. And we’d like to get your feedback.
Here are the detailed information about these two options:
1. DYNAMICBASE
/DYNAMICBASE modifies the header of an executable to indicate whether the application should be randomly rebased at load time by the OS. The random rebase is well known as ASLR (Address space layout randomization).
This option also implies “/FIXED:NO”, which will generate a relocation section in the executable. See /FIXED for more information.
In VS2008, this option is on by default if a component requires Windows Vista (/SUBSYSTEM 6.0 and greater)
/DYNAMICBASE:NO can be used to explicitly disable the random rebase.
This article talks about ASLR:
ASLR is supported only on Windows Vista and later operating systems. It will be ignored on older OS.
ASLR is transparent to the application. With ASLR, the only difference is OS will rebase the executable unconditionally instead of doing it only when an image base conflict exists.
2. NXCOMPAT
/NXCOMPAT is used to specify an executable as compatible with DEP (Data Execution Prevention)
Notice that, this option applies for x86 executable only. Non-x86 architecture versions of desktop Windows (e.g. x64 and IA64) always enforce DEP if the executable is not running in WOW64 mode.
Here is a comprehensive description of DEP:
This option is on by default if a component requires Windows Vista (/SUBSYSTEM 6.0 and greater).
/NXCOMPAT:NO can be used to explicitly specify an executable as not compatible with DEP.
However, the administrator can still enable the DEP even if the executable is not specified as compatible with DEP. So you should always test your application with DEP on.
Windows Vista SP1, Windows XP SP3 and Windows Server 2008 add a new API SetProcessDEPPolicy to allow the developer to set DEP on their process at runtime rather than using linker options. See the following link for more details:
There are several common (and incomplete) patterns which are not compatible with DEP (See for more information.)
a. Dynamic code generated in heap or new, malloc and HeapAlloc functions are non-executable. An application can use the VirtualAlloc function to allocate executable memory with the appropriate memory protection options.
Another option is to pass HEAP_CREATE_ENABLE_EXECUTE when create the heap via HeapCreate. Then the memory allocated by the subsequent HeapAlloc will be executable.
b. Executable code in data section
They should be migrated to a code section
Security vulnerabilities are more exploitable than they would be if DEP were enabled. So you should always make your application DEP compatible and turn DEP on.
The following sample demonstrates the code which is not compatible with DEP.
It also shows two DEP compatible ways to run the code on heap.
Running code in data section or on stack almost always implies security holes. You have to put the code in code section or heap instead.
#include "windows.h"
#include <cstdio>
typedef void (*funType)();
unsigned char gCode[] = {0xC3}; // ”ret” instruction on x86
const size_t gCodeSize = sizeof(gCode);
// these are not DEP compatible
void RunCodeOnHeap()
unsigned char *code = new unsigned char[gCodeSize];
memcpy(code, gCode, gCodeSize);
funType fun = reinterpret_cast<funType>(code);
fun();
delete []code;
// these are DEP compatible
void RunCodeOnHeapCompatible1()
unsigned char *code = (unsigned char *)::VirtualAlloc(NULL, gCodeSize, MEM_COMMIT, PAGE_READWRITE);
DWORD flOldProtect;
::VirtualProtect(code, gCodeSize, PAGE_EXECUTE_READ, &flOldProtect);
::VirtualFree(code, 0, MEM_RELEASE);
void RunCodeOnHeapCompatible2()
HANDLE hheap = ::HeapCreate(HEAP_CREATE_ENABLE_EXECUTE, 0, 0);
unsigned char *code = (unsigned char *)::HeapAlloc(hheap, 0, gCodeSize);
::HeapFree(hheap, 0, code);
::HeapDestroy(hheap);
INT DEPExceptionFilter(LPEXCEPTION_POINTERS lpInfo)
// please check
// for more information
if (lpInfo->ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION &&
lpInfo->ExceptionRecord->ExceptionInformation[0] == 8) {
return EXCEPTION_EXECUTE_HANDLER;
return EXCEPTION_CONTINUE_SEARCH;
__try
{
RunCodeOnHeap();
printf("RunCodeOnHeap: OK\n");
__except (DEPExceptionFilter(GetExceptionInformation()))
printf("RunCodeOnHeap: Fail due to DEP\n");
RunCodeOnHeapCompatible1();
printf("RunCodeOnHeapCompatible1: OK\n");
printf("RunCodeOnHeapCompatible1: Fail due to DEP\n");
RunCodeOnHeapCompatible2();
printf("RunCodeOnHeapCompatible2: OK\n");
printf("RunCodeOnHeapCompatible2: Fail due to DEP\n");
Output:
cl test.cpp /link /nxcompat:no
RunCodeOnHeap: OK
RunCodeOnHeapCompatible1: OK
RunCodeOnHeapCompatible2: OK
cl test.cpp /link /nxcompat
RunCodeOnHeap: Fail due to DEP
In summary, “cl test.cpp” is equivalent to “cl test.cpp /link /nxcompat:no /dynamicbase:no” before VS2010. We plan to change it to “cl test.cpp /link /nxcompat /dynamicbase” in VS2010.
If you have any concerns about the default behavior change of these two options, don’t hesitate to give your feedback. Thanks!
Xiang:
For each project that you want to target at the RC version of the Windows 7 SDK do the following:Built: | http://blogs.msdn.com/vcblog/ | crawl-002 | refinedweb | 6,403 | 53.1 |
Use pthread_getspecific(3T) to get the calling thread's binding for key, and store it in the location pointed to by value.
Prototype: int pthread_getspecific(pthread_key_t key);
#include <pthread.h> pthread_key_t key; void *value; /* key previously created */ value = pthread_getspecific(key);
No errors are returned.
Example 2-2 shows an excerpt from a multithreaded program. This code is executed by any number of threads, but it has references to two global variables, errno and mywindow, that. So, references to errno by one thread refer to a different storage location than references to errno by other threads.
The mywindow variable is intended to refer to a stdio stream connected to a window that is private to the referring thread. So, as with errno, references to mywindow by one thread should refer to a different storage location (and, ultimately, a different window) than references to mywindow by other threads. The only difference here is that the threads library takes care of errno, but the programmer must somehow make this work for mywindow.
The next example shows how the references to mywindow work. The preprocessor converts references to mywindow into invocations of the _mywindow() procedure.
This routine in turn invokes pthread_getspecific(), passing it the mywindow_key global variable (it really is a global variable) and an output parameter, win, that receives the identity of this thread's window.
thread_key_t mywin_key; FILE *_mywindow(void) { FILE *win; pthread_getspecific(mywin_key, &win); return(win); } #define mywindow _mywindow() void routine_uses_win( FILE *win) { ... } void thread_start(...) { ... make_mywin(); ... routine_uses_win( mywindow ) ... }
The mywin_key variable identifies a class of variables for which each thread has its own private copy; that is, these variables are thread-specific data. Each thread calls make_mywin() to initialize its window and to arrange for its instance of mywindow to refer to it.
Once this routine is called, the thread can safely refer to mywindow and, after _mywindow(), the thread gets the reference to its private window. So, references to mywindow behave as if they were direct references to data private to the thread.
Example 2-4 shows how to set this up(),, a call is made to the create_window() routine, which sets up a window for the thread and sets the storage pointed to by win to refer to it. Finally, a call is made to pthread_setspecific(), which associates the value contained in win (that is, the location of the storage containing the reference to the window) with the key.
After this, whenever this thread calls pthread_getspecific(), passing the global key, it gets the value that was associated with this key by this thread when it called pthread_setspecific().
When a thread terminates, calls are made to the destructor functions that were set up in pthread_key_create(). Each destructor function is called only if the terminating thread established a value for the key by calling pthread_setspecific(). | https://docs.oracle.com/cd/E19620-01/805-5080/tlib-81719/index.html | CC-MAIN-2018-05 | refinedweb | 464 | 50.67 |
Project::Euler::Lib::Types - Type definitions for Project::Euler
version 0.20
use Project::Euler::Lib::Types qw/ ProblemLink PosInt /;
(Most) all of the types that our modules use are defined here so that they can be reused and tested. This also helps prevent all of the namespace pollution from the global declarations.
Create the subtypes that we will use to validate the arguments defined by the extending classes.
A URL pointing to a problem definition on.
as Str, message { sprintf(q{'%s' is not a valid link}, $_ // '#UNDEFINED#') }, where { $_ =~ m{ \A \Q\E \d+ \z }xms };
In an effort to limit text runoff, the problem name is limited to 80 characters. Similarly, the length must also be greater than 10 to ensure it is something useful. Also, only characters, numbers, spaces, and some punctuation (!@#$%^&*(){}[]<>,.\\/?;:'") are allowed
as Str, message { sprintf(q{'%s' must be a string between 10 and 80 characters long}, $_ // '#UNDEFINED#') }, where { length $_ > 10 and length $_ < 80; };
An integer greater than 0.
as Int, message { sprintf(q{'%s' is not greater than 0}, $_ // '#UNDEFINED#') }, where { $_ > 0 }
An array of PosInts.
An integer less than 0.
as Int, message { sprintf(q{'%s' is not less than 0}, $_ // '#UNDEFINED#') }, where { $_ < 0 }
An array of NegInts.
A DateTime:: object coerced using DateTime::Format::DateParse
class_type MyDateTime, { class => 'DateTime' }; coerce MyDateTime, from Str, via { DateTime::Format::DateParse->parse_datetime( $_ ); };
Adam Lesperance <lespea@gmail.com>
This software is copyright (c) 2010 by Adam Lesperance.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. | http://search.cpan.org/dist/Project-Euler/lib/Project/Euler/Lib/Types.pm | CC-MAIN-2015-14 | refinedweb | 275 | 62.98 |
A thread has attributes, which specify the characteristics of the thread. The attributes default values fit for most common cases. To control thread attributes, a thread attributes object must be defined before creating the thread.
Read the following to learn more about creating threads:
The thread attributes are stored in an opaque object, the thread attributes object, used when creating the thread. It contains several attributes, depending on the implementation of POSIX options. It is accessed through a variable of type pthread_attr_t. In AIX, the pthread_attr_t data type is a pointer to a structure; on other systems it may be a structure or another data type.
The thread attributes object is initialized to default values by the pthread_attr_init subroutine. The attributes are handled by subroutines. The thread attributes object is destroyed by the pthread_attr_destroy subroutine. This subroutine may free storage dynamically allocated by the pthread_attr_init subroutine, depending on the implementation of the threads library.
In the following example, a thread attributes object is created and initialized with default values, then used and finally destroyed:
pthread_attr_t attributes; /* the attributes object is created */ ... if (!pthread_attr_init(&attributes)) { /* the attributes object is initialized */ ... /* using the attributes object */ ... pthread_attr_destroy(&attributes); /* the attributes object is destroyed */ }
The same attributes object can be used to create several threads. It can also be modified between two thread creations. When the threads are created, the attributes object can be destroyed without affecting the threads created with it.
The following attribute is always
defined.
The value of the attribute is
returned by the pthread_attr_getdetachstate
subroutine; it can be set by the pthread_attr_setdetachstate
subroutine. Possible values for this attributes are the following
symbolic constants:
The default value is PTHREAD_CREATE_JOINABLE.
If you create a thread in the joinable state, you must pthread_join (Calling the pthread_join Subroutine) with the thread. Otherwise, you may run out of storage space when creating new threads, because each thread takes up a signficant amount of memory.
The following attributes are also
defined in AIX. They are intended for advanced programs and may require
special execution privilege to take effect. Most programs will operate
correctly with the default settings.
The use of these attributes is
explained in Scheduling Attributes.
The use of these attributes is explained in Stack Attributes.
Creating a thread is accomplished by calling the pthread_create subroutine. This subroutine creates a new thread and makes it runnable.
When calling the pthread_create subroutine, you may specify a thread attributes object. If you specify a NULL pointer, the created thread will have the default attributes. Thus, the code fragment:
pthread_t thread; pthread_attr_t attr; ... pthread_attr_init(&attr); pthread_create(&thread, &attr, init_routine, NULL); pthread_attr_destroy(&attr);
is equivalent to:
pthread_t thread; ... pthread_create(&thread, NULL, init_routine, NULL);
When calling the pthread_create subroutine, you must specify an entry-point routine. This routine, provided by your program, is similar to the main routine for the process. It is the first user routine executed by the new thread. When the thread returns from this routine, the thread is automatically terminated.
The entry-point routine has one parameter, a void pointer, specified when calling the pthread_create subroutine. You may specify a pointer to some data, such as a string or a structure. The creating thread (the one calling the pthread_create subroutine) and the created thread must agree upon the actual type of this pointer.
The entry-point routine returns a void pointer. After the thread termination, this pointer is stored by the threads library unless the thread is detached. See Synchronization Overview for more information about using this pointer.
The pthread_create subroutine returns the thread ID of the new thread. The caller can use this thread ID to perform various operations on the thread.
Depending on the scheduling parameters of both threads, the new thread may start running before the call to the pthread_create subroutine returns. It may even happen that, when the pthread_create subroutine returns, the new thread has already terminated. The thread ID returned by the pthread_create subroutine through the thread parameter is then already invalid. It is, therefore, important to check for the ESRCH error code returned by threads library subroutines using a thread ID as a parameter.
If the pthread_create subroutine is unsuccessful, no new thread is created, the thread ID in the thread parameter is invalid, and the appropriate error code is returned.
The thread ID of a newly created thread is returned to the creating thread through the thread parameter. The current thread ID is returned by the pthread_self subroutine.
A thread ID is an opaque object; its type is pthread_t. In AIX, the pthread_t data type is an integer. On other systems, it may be a structure, a pointer, or any other data type.
To enhance the portability of programs using the threads library, the thread ID should always be handled as an opaque object. For this reason, thread IDs should be compared using the pthread_equal subroutine. Never use the C equality operator (==), because the pthread_t data type may be neither an arithmetic type nor a pointer.
The first multi-threaded program discussed is short. It displays "Hello!" in both English and French for five seconds. Compile with cc_r or xlc_r. See Developing Multi-Threaded Programs for more information on compiling thread programs.
#include <pthread.h> /* include file for pthreads - the 1st */ #include <stdio.h> /* include file for printf() */ #include <unistd.h> /* include file for sleep() */
void *Thread(void *string) { while (1) printf("%s\n", (char *)string); pthread_exit(NULL); }
int main() { char *e_str = "Hello!"; char *f_str = "Bonjour !"; pthread_t e_th; pthread_t f_th; int rc; rc = pthread_create(&e_th, NULL, Thread, (void *)e_str); if (rc) exit(-1); rc = pthread_create(&f_th, NULL, Thread, (void *)f_str); if (rc) exit(-1); sleep(5); /* usually the exit subroutine should not be used see below to get more information */ exit(0); }
The initial thread (executing the main routine) creates two threads. Both threads have the same entry-point routine (the Thread routine), but a different parameter. The parameter is a pointer to the string that will be displayed.
Understanding Threads
Threads Basic Operation Overview
Terminating Threads
List of Threads Basic Operation Subroutines
Threads Library Options | http://ps-2.kev009.com/wisclibrary/aix51/usr/share/man/info/en_US/a_doc_lib/aixprggd/genprogc/create_threads.htm | CC-MAIN-2022-21 | refinedweb | 1,007 | 57.47 |
High-Availability System Architecture
Basic blueprints for file servers, Web servers, and DNS servers
By Spyros Sakellariadis
This article is from the July 2002 issue of Windows & .NET Magazine.
You'll find a glut of articles that discuss high-availability concepts and strategies, as well as a plethora of articles that cover the engineering details of high-availability solutions' components. You're probably ready for an article that shows you how to put those components to use in your IT environment. Perhaps you've promised a high service level agreement (SLA) to your customers, and now you need to know how you're going to keep that promise. If you need to configure a high-availability Windows 2000 file server, Web server, or DNS server, you'll find this article's collection of basic blueprints extremely valuable.
High-Availability Management Phases
Application availability is inversely proportional to the total application downtime in a given time period (typically a month), and the total downtime is simply the sum of the duration of each outage. To increase a system's availability, you need to decrease the duration of outages, decrease the frequency of outages, or both. Before I discuss useful technologies, you need to understand the phases of a postoutage restoration.
In the event of a serious outage, you would need to build a new server from scratch and restore all the data and services in the time available to you. Suppose you've promised an SLA of 99.5 percent, and you're counting on only one outage per month. (For information about calculating availability percentages, see the sidebar "Measuring High Availability.") Within 3 hours and 43 minutes of the start of an outage, you would need to work through the following five restoration phases:
Diagnostic phase—Diagnose the problem and determine an appropriate course of action.
Procurement phase—Identify, locate, transport, and physically assemble replacement hardware, software, and backup media.
Base Provisioning phase—Configure the system hardware and install a base OS.
Restoration phase—Restore the entire system from media, including the system files and user data.
Verification phase—Verify the functionality of the entire system and the integrity of user data.
Regardless of your SLA, you need to know how long the phases take. Each phase can introduce unexpected and unwelcome delays. For example, an unconstrained diagnostic phase can take up the lion's share of your available time. To limit how much time your support engineers spend diagnosing the problem, set up a decision tree in which the engineers proceed to the procurement phase if they don't find what's wrong within 15 minutes. The procurement phase can also be time-consuming if you keep the backup media offsite and have to wait for it to be delivered. I once experienced a situation in which the truck delivering an offsite backup tape crashed en route to our data center. You might think 3 hours and 43 minutes is a short period of time in which to restore service, but in reality, you might have only about 2 hours to complete the actual restoration phase.
Measuring High Availability
The:
x = (n - y) * 100/n.
Blueprint for High-Availability File Servers
A file server doesn't require much CPU capacity or memory. To support 500 users and 200GB of data, you might use one small server, such as a Compaq ProLiant DL380 with two Pentium III processors and 512MB of RAM. With minimal accessories, such a setup costs about $9700 retail. If you use a DLT drive that provides an average transfer rate of 5MBps, physically restoring 200GB of data will take 666 minutes, or 11 hours and 6 minutes. Add an hour for the diagnostic, procurement, base provisioning, and verification phases, and you're looking at 726 minutes to recover from an outage. If you assume one outage per 31-day month (44,640 minutes), then $9700 buys you a file server with an SLA of 98.37 percent.
To increase the availability of file servers, you can use standard strategies: Reduce the time required to restore the file share and data during an outage and reduce the frequency of outages. Many technologies address each of these strategies for file servers. As a starting point, let's look at basic implementations that use the following techniques: data partitioning, snapshot backup-and-restore technologies, and fault-tolerant systems.
Data partitioning. In the configuration that Figure 1 shows, FileServer2 contains product data, FileServer3 contains images, and so on. To make this partitioning transparent to the user, you can implement a technology such as Microsoft Dfs, which lets you create a virtual file system from the physical nodes across the network. A user who connects to \fileserver1\share would see a directory structure that appears to show all data as if it were residing on FileServer1, even though some of the data physically resides on FileServer2.
Table 1 SLA Costs and Data Partitioning
Table 1 shows the availability you can achieve through data partitioning. (This table uses a typical SLA formula and assumes that you need to restore only one server during the outage.) The cost per server goes down as you accumulate servers and as the number and size of the servers' disks decrease. Obviously, the partitioning option is costly in terms of server hardware, so you need to decide whether you can live with an average of 12 hours 6 minutes (726 minutes) unscheduled downtime per month. Perhaps spending an extra $23,800 ($33,500 minus $9700) to reduce that time to 3 hours 13 minutes (193 minutes) makes sense for you. Data partitioning is particularly cost-prohibitive if you have huge quantities of data and need dozens of servers or more.
Snapshot backup and restore. An alternative to data partitioning is to implement faster technology. Faster tape drives won't necessarily provide a quantum leap in performance, so you'll need to use snapshot backup-and-restore technology, which is typically available in conjunction with Independent Hardware Vendors (IHVs—e.g., EMC, Compaq) of enterprise storage systems. Upcoming software snapshot products might change this equation, but for now, you need to address the enterprise storage vendors.
Figure 2 shows a Storage Area Network (SAN) environment. You connect the SAN hardware to the server through a fibre channel connection (preferably redundant) and access the file system as if it were local. You can use a snapshot utility on the SAN to perform a quick backup (typically measured in seconds), then restore the data from a backup disk almost as quickly. As long as you create snapshots relatively frequently, you can restore data within the confines of even the most stringent SLA. Snapshot functionality might even be irrelevant—at my company, for the second half of 2001, our EMC SAN experienced 100 percent uptime, our Brocade switches boasted 99.9999861 percent availability, and we never experienced disk problems that required us to restore from snapshots. If you're concerned that the SAN might fail, you could implement redundant SANs with failover technology.
Unfortunately, unless a SAN replaces hundreds of small file servers, many hardware snapshot products and SAN technologies are prohibitively expensive. Even a small 400GB EMC and Brocade SAN infrastructure can cost $300,000. When you compare that price with that of two servers, each with 200GB of local storage—$19,400—you begin to understand the cost of very high availability. Cost-effective SAN and Network Attached Storage (NAS) vendors exist, so be sure to shop around carefully before you pass any final judgments about SLA costs.
Fault-tolerant systems. The two previous high-availability strategies focus on reducing the time necessary to restore the server and data. The third strategy involves implementing redundant systems that continue serving the client indefinitely if one system fails. You can make many components redundant—servers, disks, NICs, UPSs, switches, and so on. Some of these components are easy to add and relatively inexpensive. For example, if you add redundant NICs, power supplies, and disk controllers to the aforementioned ProLiant DL380 system, the cost rises from $9700 to about $11,600. However, ask yourself whether you need to spend that money. At my company, we're experiencing less than 0.025 percent failure rate on those components. (Probably the most crucial—and by far the cheapest—item you need is a UPS. If you don't have a UPS, put this article down and deploy one before reading any further.)
Let's look at three technologies for implementing redundant data and redundant servers: Dfs, RAID, and server clusters. The system in Figure 1 distributes user data across several physical locations and uses Dfs to present a simple, logical view of the data. If you have an exact replica of any of the file directories—for example, the \products directory—you can mount both the original and the replica at one point in the Dfs namespace. When users traverse a directory tree in Windows Explorer to reach the \products directory, they might be viewing data residing at the original or the replica. Dfs doesn't require that data in the various shares mounted at one point be identical, but you can configure Dfs so that it replicates the data on a schedule. If the server holding the replica crashes, users can still open files in the original location—a somewhat fault-tolerant scenario. If you configured multiple replicas, you would have even more redundancy. (If you want to have redundancy for the top-level share as well as the replicas of the data, you need to create a fault-tolerant Dfs root. For more information, see the Dfs documentation.) Any data not written to disk on the crashed server obviously would be lost, as would any nonreplicated data. The Dfs replication process isn't well suited for highly dynamic data, so you need to evaluate this technology carefully to determine whether it's appropriate for your SLA strategy.
You can set up Dfs to replicate data between servers. RAID addresses distribution and replication of data between one server's disks. On paper, computer disks boast extremely high reliability—for example, Seagate Technology claims that its Cheetah 36GB Ultra 160 SCSI disk provides 1,200,000 hours mean time between failures (MTBF), which means you can expect a failure approximately every 137 years. However, this MTBF value is deceiving. Hard disk failures are common and have many external causes. At my company, hard disks are our top-ranking hardware service item; we repair or replace an average of 66 disks per year in one data center that holds approximately 8000 disks of various ages. Executive Software's study "Survey.com Hard Drive Issues Survey" () uncovered similarly frightening statistics: 62 percent of data-center IT administrators rank disk failures as their top disk problem and estimate the average life of a SCSI disk at 3 or 4 years. The trick is to implement fault-tolerant RAID technology so that disk failures don't result in downtime.
Figure 3 shows a simple fault-tolerant RAID configuration. RAID 1 technology mirrors the disks in realtime: If one disk crashes or becomes corrupted, the other disk continues to operate as usual and the system sees no performance degradation—although it's now operating without redundancy. The system that Figure 3 shows uses RAID 1 mirroring for the OS and the swap files. If any disk fails, you can remove it and replace it with a healthy disk, without turning off the computer. The RAID 1 SCSI controller creates a copy of the OS or swap file on the new disk, then reestablishes fault tolerance. No downtime occurs as a result of a disk failure, albeit at the expense of doubling the number of drives in the system. (For further information about RAID technology, go to the Advanced Computer & Network Web site at.)
RAID 5 technology introduces additional fault tolerance by allocating portions of each disk in the array to parity data. This setup enables realtime reconstruction of corrupted data if one disk in the array fails. The parity data reduces the amount of usable space in the array by the equivalent of one disk out of the entire array. As with RAID 1, you can remove and replace the failed disk without turning off the computer, and you experience no downtime—but you do experience some performance degradation during an outage. In a RAID 5 array, only one disk in the entire array isn't usable from the client's perspective, so RAID 5 is much less costly than RAID 1. The configuration in Figure 3 uses RAID 5 for the file data. In the event of one disk's failure, the client probably wouldn't notice degradation in the disk array's performance. In our example, if you used four 72GB disks, you would have three 72GB disks' worth of usable storage, or 216GB for user data.
The configuration in Figure 3 is typical of data-center systems. My company used this template last year for most systems, and those systems experienced no downtime as a result of physical disk failures, despite the 66 disks that we needed to replace.
Table 2 RAID Costs
Table 2 summarizes the cost of this redundancy for a ProLiant DL380 system that has 200GB of user data and 72GB disks for the data. The cost of the RAID systems is particularly high because the ProLiant DL380 can't house 8 to 10 drives without an external chassis, which adds considerably to the price. Drive redundancy doesn't protect against data corruption that results from software problems, and you might still need to restore from tape for a variety of reasons. Data redundancy does, however, protect you from the need to restore from tape because of a disk failure. You need to assess your SLA to determine whether you can justify the cost.
Depending on your environment and hardware, your next weakest link might either be a network device or the servers. To create a redundant server environment suitable for a high-availability file server, you can implement a simple server cluster in Windows 2000 Advanced Server.
Figure 4 shows a cluster that includes RAID technology for the disks. You can configure a server cluster in many ways, but the basic concept is that if one server fails, another server takes over the failed server's functions. In the case of a file server, if a failover occurs from one system to another, users can continue working on a document stored on a shared disk array, possibly noticing a short delay while their applications reconnect to the cluster. Meanwhile, you can then take the failed server offline and repair it without affecting the users' operations or your SLA. When you finish repairing the server, you can rejoin it to the cluster and regain server redundancy. (Some applications aren't cluster aware, so be sure to check the cluster documentation carefully before you deploy a cluster solution.)
Table 3 Two-Server Cluster Costs
Table 3 summarizes the hardware cost of server redundancy for two similarly configured ProLiant DL380 servers with 200GB of file data in a shared external drive chassis. These numbers are approximations. The recommended Compaq solution replaces the shared SCSI channel with a fibre channel configuration, but I kept the SCSI channel to keep prices down. Also, cluster support can involve additional software and operational costs—for example, whereas you can use Windows 2000 Server to install one file server, a cluster requires Windows 2000 Advanced Server.
Server redundancy won't reduce the time necessary to restore data (as the partitioning options do) and won't create redundant copies of the data (as the RAID options do). This option only increases the availability of the server that publishes the disk data to the user. If your weakest link isn't the server, you might not need server clustering. For example, in our data center, less than 1 percent of our clients felt that the cost of clustering file servers merited the additional reliability.
Blueprint for High-Availability Web Servers
In the media, you can find many statistics about the availability of Web servers. Every time a major corporation or government entity has a Web site problem, the news makes headlines. An interesting source for availability numbers is Keynote Systems, which publishes the Keynote Government 40 Index and the Keynote Business 40 Index. The October 29, 2001, index showed the Federal Bureau of Investigation (FBI), Library of Congress, and Supreme Court Web sites ran at 99.24 percent, 99.96 percent, and 99.62 percent availability, respectively. Similarly, during the Christmas holiday season, the average availability of the top 10 shopping Web sites (e.g., Nordstrom, Neiman Marcus, Saks Fifth Avenue) was 98.5 percent. How do you achieve such levels of availability for a Web server?
Your high-availability options for a Microsoft IIS Web server aren't terribly different from those for a file server. You can configure the system to reduce the time necessary to restore service and data after an outage, and you can reduce the frequency of outages. In addition to the techniques you use for file servers, two features of Windows 2000 Advanced Server and IIS are available: Virtual Directories for data partitioning and Network Load Balancing (NLB) for mirrored servers.
Data partitioning in a Web server environment is similar to building a partitioned file system. The primary difference is that you use IIS's Virtual Directories feature instead of Dfs to provide the unified namespace. For example, suppose you have multiple file servers (i.e., FileServer1 FileServer2, and so on), one of which will be the Web server (i.e., FileServer1). You configure the file servers just as you would in a file-server environment, then configure FileServer1 to be your Web server. Next, you use the Internet Services Manager (ISM) tool to publish a series of virtual directories off the root of the Web server. To do so, in ISM, right-click the root of the Web site on \fileserver1 and select New, Virtual Directory. Name the directory (e.g., \products), and identify the directory path for that data as \fileserver2\products. When users access your Web site's root, they can access the Products page as if it were on the root Web server—but the data actually resides on the small back-end FileServer2. The back-end server is small enough for you to restore in less than the allotted time, but the farm appears as one Web site to users.
In the case of a simple file server, you can use server redundancy (which the cluster example in Figure 4 shows) to reduce the frequency of perceived outages. In the case of a Web server, you have an additional option that's roughly equivalent to using Dfs replicas for a fault-tolerant file server. Because you're primarily reading individual document pages in a stateless action, whether subsequent reads take place from one server or another server is irrelevant. Therefore, you can provide a reasonably seamless user experience while you swap servers indiscriminately in the background. You can use Windows 2000 Advanced Server's NLB to manage those transitions.
Figure 5 shows a sample Web server farm that contains four identical servers. In this scenario, the best strategy is to simply build redundant servers, all of which contain the entire 200GB of data. To ensure that the data is identical on each server, you might use a service such as Dfs and the Windows 2000 File Replication Service (FRS) to duplicate the information across the servers or use a third-party product to perform this type of replication. In a pure Microsoft environment, you might use the Site Server 3.0 Content Deployment Service or the Application Center 2000 Synchronization Service. Then, you install and configure the NLB service on all the servers so that they share one virtual IP (VIP) address.
When a user connects to the Web server cluster, the NLB service determines which server responds to the user. This determination depends on the NLB configuration. For example, in the case of the URL in Figure 5, the /www1.usi.net server might respond. If one of the servers fails, the NLB service simply fills the next user request from one of the remaining servers. The more servers you create, the less likely one server failure will affect your SLA. If you have two servers that handle 50 percent of the user traffic, one server's failure increases the other server's load by 100 percent. If you have five servers, one server's failure increases the load on the other four servers from 20 to 25 percent. As long as you have sufficient redundancy to maintain acceptable user performance while the failed server is offline, you'll meet your SLA by reducing or eliminating the number of outages that the user perceives.
Comparing the cost of using redundancy to enable a high-availability Web server with the cost of data partitioning a file server is interesting. In the scenario in Figure 1, the file servers collectively hold 200GB of available disk space for user data, whereas the scenario in Figure 5 requires that each Web server contain the full 200GB of disk space. Furthermore, in Figure 1, the file servers can be fairly small, regardless of whether you use one or five servers. A Web server, however, is more taxing on CPU capacity and memory; if you have only one Web server, you need a much more powerful machine, such as a ProLiant DL580 with four processors and 2GB of RAM. If you have multiple Web servers, you might be able to get away with the ProLiant DL380 in the example that Figure 1 shows.
Table 4 Web Load-Balancing Costs
Table 4 shows the relative costs. The price of a large server is greater than the price of multiple small servers. One reason for the higher cost is that the ProLiant DL580 needs an external drive chassis. Multiple load-balanced and redundant servers, with a theoretical SLA of 100 percent, are sometimes cheaper than one server that provides no redundancy.
Large public Web sites typically use a combination of technologies to achieve high availability. Figure 6 shows one method of combining strategies into an environment that boasts numerous high-availability components. The scenario uses redundant load-balanced front-end Web servers, so the user will always be able to connect to the site. Server clustering ensures that a server is always available to handle file-system requests. Finally, to guarantee the availability of data, the system uses a redundant fibre channel fabric for access to an enterprise SAN. Only the number of servers in the front-end and back-end clusters—and any communications components between the client and servers—limit this architecture's availability. For more information about this kind of complex architecture, see the Microsoft article "Web Server Load Balancing and Redundancy".
Blueprint for High-Availability DNS Servers
You can build a high-availability DNS system in much the same way that you build a highly available file server, except that the quantity of data is typically much smaller. Your primary concern is typically not the time necessary to restore the data but rather the availability of the DNS server. Therefore, you probably don't need to worry about a solution that decreases a DNS server's restore time. Your architecture must ensure that a client requesting name resolution can always find a DNS server that contains your zone data. The most complex high-availability DNS solution you need is simply two or three servers that have complete copies of all the host records you want to publish.
When an Internet client needs to find the IP address of a server in your domain, it issues a DNS query, which starts a series of events that culminate in a DNS server sending a query on the client's behalf to your DNS server. For example, InterNIC's records for my company show that we're running four DNS servers. If a client enters the URL in a browser, a DNS query eventually arrives at one of our four DNS servers, which replies with the address of our Web server. If you register multiple DNS server addresses with InterNIC, DNS clients can address queries to any of your DNS servers, and if one of your DNS servers is unavailable, the clients can query the other servers. The result is that the client perceives continuous service, even if one of the DNS servers is down. For comparison purposes, at press time, Cisco Systems has registered two DNS servers, IBM has registered four, and Microsoft has registered six.
To create redundant DNS servers, you install the DNS service on two or more servers. On one of those servers, you use DNS Manager to add the domain's host information. On each of the other DNS servers, you use DNS Manager to specify that the server is a secondary DNS server for the domain and that it should copy the host data from the primary DNS server. DNS takes care of the initial data replication from the primary server to the secondary servers, as well as any subsequent replication of updates if the data on the primary server changes. In a Windows 2000 environment, you can specify that the DNS data reside in Active Directory (AD), in which case AD replication takes care of the DNS transfers and you don't need to specify primary and secondary DNS servers. In addition to increasing the number of secondary DNS servers for fault tolerance, you can create intermediary DNS servers that simply cache responses from your DNS servers without holding a copy of the DNS database. These caching servers reduce the load on your primary and secondary DNS servers by reducing the number of queries that ultimately reach those servers. Your DNS records might be cached in any number of other DNS servers on the Internet, increasing the resolving capacity of your system at no cost. (Some people refer to this phenomenon as a scale away strategy.)
Assemble the Building Blocks
You need to determine how much availability you truly need, as well as which components you can combine to produce your chosen level of availability. I focused this discussion on blueprints for building simple high-availability systems on Windows 2000 systems. Although more complex applications—such as Microsoft Exchange 2000 Server and Microsoft SQL Server 2000—require more sophisticated configurations, you can still use many of the same building blocks I have provided in this article. (For detailed information about these building blocks, see "Related Articles in Previous Issues.")
Related Articles in Previous Issues
You can obtain the following articles from Windows & .NET Magazine's Web site at.
DAVID CHERNICOFF
"Components of a High-Availability System," November 2000, InstantDoc ID 15702
JOHN GREEN
"RAID Performance Configuration," June 1999, InstantDoc ID 5398
TOM HENDERSON
"SAN Topology," June 2000, InstantDoc ID 8693
TIM HUCKABY
"The Tao of Network Load Balancing," September 2001, InstantDoc ID 21838
KATHY IVENS
Getting Started with Windows 2000, "Definitely Dfs," June 2001, InstantDoc ID 20725
GREG TODD
"Microsoft Clustering Solutions," November 2000, InstantDoc ID 15701. | http://technet.microsoft.com/en-us/library/cc750543.aspx | CC-MAIN-2014-15 | refinedweb | 4,537 | 50.67 |
Victimless Canary Testing with Scientist .NET
Matt Eland
Updated on
・4 min read
.NET Testing (3 Part Series)
If you're tired of users finding errors before you do, a library called Scientist has some answers.
When we release new code, we test it with as much rigor as we can, but it's very hard to replicate the full range of data, workflows, and environments where users use our software.
This makes early users effectively a form of canary testers like the canaries coal miners brought with them into the mines to get early warning of hazardous gasses.
The problem is, we never want our users to effectively become a "dead canary" and encounter a bug that we could have spared them from if something else could have found it first.
Scientist
The Scientist library offers a solution. Using Scientist, the new code is deployed alongside the old, and Scientist runs an experiment in which it executes the legacy code as well as an experimental new version, then compares the two versions together.
Regardless of whether the results of these two methods match, the result of the legacy version is used and returned to the caller, meaning that the user is shielded from any issues caused by the new version.
This means that errors in the new routine can be found without users ever seeing them. If a user’s data finds some error or logic gap in a new version of the code, the user should be completely ignorant of that fact and keep on using the software as if it worked the way it did prior to the update.
Instead, the results of this comparison are sent to a results publisher which can log to a number of places and allow the development team to tweak the new routine before going live with the feature.
This allows us to rewrite or expand portions of our code, ship the fixed version alongside the old, and then compare the implementations against live production data. Once we’ve collected enough data to be satisfied with the new routine, we can issue a new release removing Scientist and the Legacy Routine from the equation.
Using Scientist
An example in C# using Scientist .NET is listed below:
var legacyAnalyzer = new LegacyAnalyzer(); var newAnalyzer = new RewrittenAnalyzer(); var result = Scientist.Science<CustomResult>("Experiment Name", experiment => { experiment.Use(() => legacyAnalyzer.Analyze(resume, container)); experiment.Try(() => newAnalyzer.Analyze(resume, container)); experiment.Compare((x, y) => x.Score == y.Score); });
In this example, we call out to
Scientist.Science and declare that we expect a custom result type of type
CustomResult back from the method invocation. From there, we give Scientist a name for the experiment (available to the result publisher) and tell it to Use a legacy implementation. This method’s return value will always be returned. We can also declare 1 to many different experiments to compare it to via the Try method. Finally, we can define a custom means to Compare the two results looking for equality.
Note that Scientist .NET will, by design, run the different routines in random ordering.
Testing with Scientist
Scientist can also be used inside of unit tests to compare a legacy and a refactored way of doing things. In such cases, you wouldn’t want the refactored version to exhibit different behavior, so you could rely on a custom result publisher to fail a unit test.
Result Publishing
The results of the experiment are then published to the result publisher. A custom result publisher is defined below for reference:
public class ThrowIfMismatchedPublisher : IResultPublisher { public Task Publish<T, TClean>(Result<T, TClean> result) { if (result.Mismatched) { var sb = new StringBuilder(); sb.AppendLine($"{result.ExperimentName} had mismatched results: "); foreach (var observation in result.MismatchedObservations) { sb.AppendLine($"Value: {observation.Value}"); } result.Mismatched.ShouldBeFalse(sb.ToString()); } return Task.CompletedTask; } }
This will allow Scientist to run in such a way that mismatches throw exceptions, which is useful only in unit testing scenarios (for production scenarios you’d want to log to a log file, error reporting service, database, etc).
This publisher can then be provided to scientist by setting
Scientist.ResultPublisher = new ThrowIfMIsmatchedPublisher();
Summary
Scientist has a lot of value for cases where you want to replace bit by bit of an application, try a performance improvement, or other forms of incremental changes. Scientist is not, however, suited for scenarios where the code is creating some external side effect such as modifying a database, sending an E-Mail, or making some sort of modifying external API call since both the legacy and the new routine will run.
The library is available in a wide variety of languages from Ruby to .NET to JavaScript to R to Kotlin and others. Additionally, the core concepts of the library are simple and can be used by any language.
Ultimately Scientist is a very helpful library for comparing old and new versions of your codebase and for giving your users a buffer between bleeding edge features and unwittingly acting as a dead canary.
.NET Testing (3 Part Series)
The Many Flavors of Technical Presentations
Learn about various technical presentation formats to choose the best one for you
I like this concept and pattern! Testing with production data without risking user experience.
I wonder if there there is a way to extend this to functions that have external impact. I guess that would depend heavily on the application so might be tricky for a generic solution.
Thanks for bringing this to my attention. :)
Absolutely! I've focused strongly on quality for myself and my team this year and discovering Scientist has been perhaps the largest impact for our team, competing only with snapshot testing using Jest and Snapper.
I've applied to give a presentation on this subject in mid January at a large conference and I'm hopeful I'll be able to share it with more people, because it really is an interesting way of thinking.
You're spot on about the external impact aspects of this. While scientist is best suited for pure functions or things without an external impact, if you follow it to the extreme you start looking at using mock objects in production for your experiments so that they use a FakeEmailSender, for example.
Either that or Scientist forces you to structure your application in such a way that it has a lot of pure functions that can be tested. In the E-Mail example, you could structure your app in such a way that it builds an E-Mail object in one method and sends it in another, then you use Scientist to test the building of that object.
I suppose that expanding Scientist's scope forces you to follow the Single Responsibility Principle as well as encouraging Dependency Inversion.
I may write more on advanced Scientist use cases in the future.
Great! Looking forward to hearing more from you on the topic. Would be interesting to hear about Jest and Snapper also. | https://dev.to/integerman/victimless-canary-testing-with-scientist-9nn | CC-MAIN-2019-51 | refinedweb | 1,160 | 51.99 |
>>
Defining multiple plots to be animated with a for loop in Matplotlib
Python Data Science basics with Numpy, Pandas and Matplotlib
63 Lectures 6 hours
MatPlotLib with Python
9 Lectures 2.5 hours
DATAhill Solutions Srinivas Reddy
To define multiple plots to be animated with a for loop in matplotlib, we can take followings steps −
- Set the figure size and adjust the padding between and around the subplots.
- Create a new figure or activate an existing figure using figure method.
- Add an axes to the current figure and make it the current axes.
- Initialize two variables, N and x, using numpy.
- Get the list of lines and bar patches.
- Animate the lines and rectangles (bar patches) in a for loop.
- Make an animation by repeatedly calling a function *func*.
- To display the figure, use show() method.
Example
from matplotlib import pyplot as plt from matplotlib import animation import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig = plt.figure() ax = plt.axes(xlim=(0, 2), ylim=(0, 100)) N = 4 x = np.linspace(-5, 5, 100) lines = [plt.plot(x, np.sin(x))[0] for _ in range(N)] rectangles = plt.bar([0.5, 1, 1.5], [50, 40, 90], width=0.1) patches = lines + list(rectangles) def animate(i): for j, line in enumerate(lines): line.set_data([0, 2, i, j], [0, 3, 10 * j, i]) for j, rectangle in enumerate(rectangles): rectangle.set_height(i / (j + 1)) return patches anim = animation.FuncAnimation(fig, animate, frames=100, interval=20, blit=True) plt.show()
Output
- Related Questions & Answers
- How can Matplotlib be used to create multiple plots iteratively in Python?
- How to get multiple overlapping plots with independent scaling in Matplotlib?
- Defining a discrete colormap for imshow in Matplotlib
- How can multiple plots be plotted in same figure using matplotlib and Python?
- Adding a legend to a Matplotlib boxplot with multiple plots on the same axis
- How to align multiple plots in a grid using GridSpec Class in Matplotlib
- Logscale plots with zero values in Matplotlib
- How can Bokeh be used to visualize multiple bar plots in Python?
- Change the default background color for Matplotlib plots
- How to reuse plots in Matplotlib?
- Defining the midpoint of a colormap in Matplotlib
- Plotting animated quivers in Python using Matplotlib
- How can Matplotlib be used to three-dimensional line plots using Python?
- How to plot an animated image matrix in matplotlib?
- PHP Defining Multiple Namespaces in same file
Advertisements | https://www.tutorialspoint.com/defining-multiple-plots-to-be-animated-with-a-for-loop-in-matplotlib | CC-MAIN-2022-40 | refinedweb | 413 | 58.48 |
Re: Debugging C# apps that use USB and Dial-up internet via Ethern
- From: "Michel Verhagen (eMVP)" <michel@xxxxxxxxxx>
- Date: Thu, 10 Apr 2008 07:52:18 +1200
Yes, that is correct. Probably best to try it out on a XP machine first. Easier to play with routing tables and metrics etc. When you get something that works, apply it on CE.
Good luck,
Michel Verhagen, eMVP
GuruCE
Consultancy, training and development services.
William Powell wrote:
Chris and Michel,.
Thanks for your responses. I'll take a look into the IP helper routines and the wrappers from the SDF ver 2.2.
In general, are you recommending I use the IPHelper functions to:
- setup a route that specifies that the address of my debug host pc (192.168.5.52 for example) should be routed to the Ethernet driver
- setup a default route that selects the dial-up networking for all other network traffic
Is this correct?
Bill
"Chris Tacke, eMVP" wrote:
And if you're using SDF version 2.2, the OpenNETCF.Net.NetworkInformation namespace has all of the IPHelper routing stuff wrapped, so you don't even have tp write the definitions or P/Invokes for those.
--
Chris Tacke, Embedded MVP
OpenNETCF Consulting
Giving back to the embedded community
"Michel Verhagen (eMVP)" <michel@xxxxxxxxxx> wrote in message news:OZTwSTlmIHA.1768@xxxxxxxxxxxxxxxxxxxxxxxThe IPHelper functions should be able to help you out. What you want is change the route or the metric (look at SetIpForwardEntry, SetIfEntry, etc).
Good luck,
Michel Verhagen, eMVP
GuruCE
Consultancy, training and development services.
William Powell wrote:WinCE Experts,
We are developing a WinCE 6.0 headless device (based on the Atmel 9260 and Adeneo BSP) that uses the USB function port as a virtual com port to a PC (customer requirement): two hardware modules that provide dial-up internet connections (GPRS and satellite); one Wifi module (with a provided Ethernet driver) for communication to a remote server ;and an ethernet port to support development only.
We currently have included the CoreCon components and the Autolauncher in the build and can successfully create a flash based image that boots and is ready for C# application debugging. We also autolaunch the cerhost tool to allow the debug host to run the cerdisp tool to view a display on the device (for development purposes)
Problem:
With the ethernet connection running to support debugging, we cannot seem to get the dialup networking to recognize the dialup port as the preferred networking transport. Test case 1:
To test, we've isolated the ethernet connection to the host by selecting a static IP address and connected only the debug host PC and the target system on a network (no DHCP, no access to the internet, no DNS). [We've also tried this using a router not connected to the internet with just the host and target on the router network and DHCP assigned IP addresses]
We starteup the OS image with a shell and created dialup entries for the modem in the registry. When we initiate the dialup connection via the control panel networking application, the modem connects (GPRS data connection to the internet). We then try to ping a known site (google): the device resolves the name and gets the IP, but then I see an error message (transmit failed, error code 11010). The device is able to ping itself properly but is unable to send/receive any data.
Test case 2:
We wrote a test program that programmatically starts the dialup connection (using OpenNETCF calls) and transfers data over the connection. This program is downloaded via ethernet (run without debugging) from Visual Studio 2005, we disconnect the ethernet cable (there is a pause in the program to give us time to do this), and the program then executes, successfully starts the dialup networking connection, and successfully transfers data over the dialup connection. So, it appears if the ethernet connection is "not available" (but driver still installed), WinCE select the other (dialup) networking connection and works.
Question:
Is there a way to setup to use ethernet debugging to debug an application that uses dialup networking such that the debugging packets are routed to the ethernet port but other packets use the dialup networking connection.
Any help would greatly improve our ability to debug the program...
Bill Powell
- References:
- Debugging C# apps that use USB and Dial-up internet via Ethernet
- From: William Powell
- Re: Debugging C# apps that use USB and Dial-up internet via Ethernet
- From: Michel Verhagen (eMVP)
- Re: Debugging C# apps that use USB and Dial-up internet via Ethernet
- From: Chris Tacke, eMVP
- Re: Debugging C# apps that use USB and Dial-up internet via Ethern
- From: William Powell
- Prev by Date: Re: Windows OneCare
- Next by Date: Re: I have a problem with eBox-2300, cann't run WinCE
- Previous by thread: Re: Debugging C# apps that use USB and Dial-up internet via Ethern
- Next by thread: I have a problem with eBox-2300, cann't run WinCE
- Index(es): | http://www.tech-archive.net/Archive/WindowsCE/microsoft.public.windowsce.embedded/2008-04/msg00195.html | crawl-002 | refinedweb | 836 | 54.56 |
Hey all. I was sick and missed 2 days of my Java class but i have been trying to catch up. This is my lab assignment that i didnt get till 2 days before it was due... i will post some of my code that i have worked on so far and if anyone could give me pointers because im having trouble understanding java since im mainly a C programmer. Thanks ahead of time to anyone who will help!
Suppose a company bought an item for certain amount of money and sells it. Do the following:
Part 1.
(a) Recognize that this situation describes an entity and give it a name.
(b) List possible attributes for this entity.
(c) List possible operations for this entity.
(d) List two objects for this entity. That is, give two exampls of such a transaction - in terms of their names, the cost of each item, and amount that each is sold for.
Part 2.
write a partial class definition to include:
(a) The name of the class, and
(b) The variable declarations for the class.
Part 3. Define an appropriate constructor for the class.
Part 4.
(a) Define accessor methods that returns the value prepresented by each variable.
(b) Include a mutator method that calculates the profit, (assuming profit was made).
(c) Provide mutator methods to change the name, the purchasing price, and the selling price of the product.
Part 5 Write a test class that will generate output.
So far my code is looking like this.
public class Riotsales { private int RP1points; private int RP2cost; private int RP2points; private int RPtotal; public Riotsales RP1 (int RP1sales, int RP2sales, int RPtotal) { RP1sales = 1000; RP2sales = 2000; RPtotal = RP1sales + RP2sales } public int getRP1() { return RP1sales; } public int getRP2() { return RP2sales; } public int getRPtotal() { return RPtotal; }
And here is my Test class which i know is really messed up
all the 8221's are actually " which is weird that its changing it to numbersall the 8221's are actually " which is weird that its changing it to numbersclass TestRiotsales { public static void main (String[] args) System.out.println(“The total sales for the day are:” ); System.out.println(“-----------------------------------------------------“); System.out.println(); System.out.println(“1000 Riot points: ” + RP1sales, “ sales.”); System.out.println(“2000 Riot points: ” + RP2sales, “ sales.”) System.out.println(“Riot Corp.”); System.out.println(“--------------------------”); System.out.println(“Product: 1000 Riot Points”); System.out.println(“Purchase Price: $0.00”); System.out.println(“Sale Price: $” + RP2cost,); System.out.println(“--------------------------”); System.out.println(“Profit: $” + RP2cost,); System.out.println(); System.out.println(“Riot Corp.”); System.out.println(“--------------------------”); System.out.println(“Product: 2000 Riot Points”); System.out.println(“Purchase price: $0.00”); System.out.println(“Sale Price: $” + RP1cost,); System.out.println(“--------------------------”); System.out.println(“Profit: $” + RP2cost,); } | http://www.javaprogrammingforums.com/whats-wrong-my-code/29865-could-use-little-help-please-ty.html | CC-MAIN-2016-18 | refinedweb | 455 | 57.57 |
The Legacy Developer’s Guide to Java 9
You can’t take advantage of Java 9’s shiny new features if your application needs to support older versions of Java… or can you? Here’s what Java 9 offers the developers of legacy Java applications.
Introduction: The Curse of the New Java Release
Every few years, a new version of Java is released. Speakers at JavaOne tout the new language constructs and APIs, and laud their benefits. Excited developers line up, eager to use the new features. It’s a rosy picture, except most developers are charged with maintaining and enhancing existing applications, not creating new ones from scratch. Most applications, particularly commercially sold applications, need to be backwards-compatible with earlier versions of Java, which won’t support these new. Do you want to use the
java.util.concurrent.ThreadLocalRandom class to generate pseudo-random numbers in a multi-threaded application? Too bad if your application needs to run on Java 6 as well as on Java 7, 8 and 9.
The result is that legacy developers feel like kids with their noses pressed up against the window of the candy store, and they’re not allowed in. It can be disappointing and frustrating.
Is there anything in the upcoming Java 9 release that’s aimed at developers working on legacy Java applications? Is there anything that makes our life easier, while at the same time allows us to use the exciting new features that are coming out next year? Fortunately, the answer is yes.
By the way, this is not a complete guide to everything new in Java 9. A great guide to all the new features in Java 9 can be found here.
What We Do Now
There are ways to shoehorn new platform features into legacy applications that need to be backward-compatible. Particularly, there are ways to take advantage of new APIs. It can get a little ugly, however.
We can use late binding to attempt to access a new API when our application also needs to run on older versions of Java that don’t support that API. For example, let’s say that we want to use the
java.util.stream.LongStream class that was introduced in Java 8, and we want to use
LongStream’s
anyMatch(LongPredicate) method, but the application has to run on Java 7. We could create a helper class as follows:
public class Long.
Now, we want to access. (In fact, it’s tedious already, with a single API.) It’s also not type safe, since we can’t actually mention
LongStream or
LongPredicate in our code. Finally, it’s much less efficient, because of the overhead of the reflection and the extra try-catch blocks. So, while we can do this, it’s not much fun, and it’s error-prone if we’re not careful.
While we can access new APIs and still have our code remain backward-compatible, we can’t do this at all for new language constructs. For example, let’s say that we want to use lambdas in code that also needs to run in Java 7. We’re out of luck. The Java compiler will not let us specify a source compliance level later than its target compliance level. So, if we set a source compliance level of 1.8 (i.e., Java 8), and a target compliance level of 1.7 (Java 7), it will not allow us to proceed.
Multi-Release JAR Files to the Rescue
Until recently, there hasn’t been a good way to use the latest Java features while still allowing the application to run on earlier versions of Java that don’t support the applications. Java 9 finally provides a way to do this for both new APIs and for new Java language constructs: and uses the classes in that nook, and ignores any classes of the same name in the regular part of the JAR file. If you’re running Java 8 or earlier, however, the JVM doesn’t know about this special nook and will ignore it, and only runs the classes in the regular part of the JAR file. In the future, when Java 10 comes out, there’ll be we rewrite classes
A and
B to use some new Java 9-specific features. Later, Java 10 comes out and we run this JAR file on a Java 8 JVM, it ignores the
\META-INF\Versions section, since it doesn’t know anything about it and isn’t looking for it. Only the original classes
A,
B,
C and
D are used. When we run it using Java 9, the classes under
\META-INF\Versions\9 are used, and are used instead of the original classes
A and
B, but the classes in
\META-INF\Versions\10 are ignored. When we run it using Java 10, both
\META-INF\Versions branches are used; particularly, the Java 10 version of
A is used, as is the Java 9 version of
B, and the default versions of
C and
D. will contain a version of the
jar.exe tool that supports creating multi-release JAR files. Other non-JDK tools will also provide support., which means that an incorrect classpath might be discovered only after an application has been run for a long time, or after it has been run many times. The entire module system is large and complex, and we are not going to provide a complete discussion in this article. (There are plenty of good explanations, including the one here.) Rather, we are going to concentrate on aspects of modularization that support developers of legacy Java applications.
I’d like to preface the discussion by saying that modularization is a very good thing, and for whatever reason, you can just put it in the classpath, and it will work as it always has, the necessary modules are present, and can report an error if any are missing. As mentioned before,, we. Once they’re modularized, you can leave them in the classpath or put them in the module path. In most cases, everything should just work as before. Your legacy JAR files should be at home in the new module system. Of course, the more you modularize, the more dependency information can be checked, and missing modules and APIs will be detected far earlier in the development cycle, possibly saving you a lot of work.
Supplying Your Own Java Environment:. Of course,, and.
Summing Up
One of the problems with having to maintain a legacy Java application is that you’re shut out their applications supporting older versions of Java.
Multi-release JAR files allow developers to work with new Java 9 features, and segregate them in a part of the JAR file where earlier Java versions won’t see them. This makes it easy for developers to write code for Java 9 and leave the old code for Java 8 and earlier, and allow the runtime to choose the classes it can run.
Java modules allow developers to get better dependency checking by writing any new JAR files in a modular style, while leaving old code unmodularized. The system is remarkably tolerant, is designed for gradual migration, and will almost always work with legacy code that knows nothing about the module system.
The modular JDK and jlink allow users to easily create self-contained runtime images, so that an application is guaranteed to come with the Java runtime that it needs to run, and that everything that it needs is guaranteed to be there. Previously, this was an error-prone process, but with Java 9 the tools are there to make it just work.
Unlike earlier Java releases, the new features of Java 9 are ready for you to use, even if you have an older Java application and need to make sure that customers can run your application even if they’re not as eager as you are to move up to the newest Java version.
A version of this article was originally published on TechBeacon:. | https://jnbridge.com/blog/legacy-developers-guide-java-9 | CC-MAIN-2018-34 | refinedweb | 1,347 | 60.85 |
On Thursday, Aug 28, 2003, at 12:31 Europe/London, Bill de hÓra wrote:
> Dain Sundstrom wrote:
>
>> Theoretical Computer Science discussions are titillating, but this is
>> engineering. If we go off and create a whole new exception
>> hierarchy, we will have a massive learning curve for new coders, and
>> we will have to come up with a hack to get our new hierarchy to play
>> well with the spec required exception handling system. What I am
>> saying is we get Java and J2EE warts and all.
>
> Strong agreement. My point was that minimizing the number of new
> checked exceptions in Geronimo should be considered. Their
> profileration (or not) is very much an engineering matter.
There always seems to be an interesting debate about 'unchecked' versus
'checked' exceptions. There's really no difference, bar the fact that
(in effect) every method has 'throws RuntimeException, Error'
automatically appended to the end of it during compile time.
One point that is definitely worth noting is that whilst having a lot
of VerySpecificException classes is good, it's still important to have
a message in it. It may well be a message that's provided in the
exception's contructor, but it should be there:
public class VerySpecificException extends LessSpecificException {
public VerySpecificException() {
super("A very specific exception message");
}
}
Otherwise, you can end up with a bunch of exceptions where
e.getMessage() == null. This is a nightmare to debug in logs unless the
type is also present.
For logging exceptions, I strongly think that the logging mechanism
should do:
log(e.getClass() + ":" + e.getLocalizedMessage());
or
log(e.toString())
rather than
log(e.getMessage())
Note that this applies also when chaining exceptions (and the exception
doesn't support nesting the Throwable directly); using
throw new MyException(other.toString())
is much better than
throw new MyException(other.getMessage())
because it (a) will use getLocalizedMessage(), and (b) if there is no
message it will still print out the type
Hopefully this is useful experience gained from looking through many
WebSphere logs and problems when only exception messages are passed and
not 'toString'
Alex. | http://mail-archives.apache.org/mod_mbox/geronimo-dev/200308.mbox/%3CCB17FAC6-D953-11D7-B0AA-0003934D3EA4@ioshq.com%3E | CC-MAIN-2014-23 | refinedweb | 345 | 50.87 |
vue-handy-scroll
Handy floating scrollbar component for Vue.js v2.6.0+.
vue-handy-scroll is a component that solves the problem of scrolling lengthy content horizontally when that content doesn’t fit into the viewport. It creates a scrollbar which is attached at the bottom of the scrollable container’s visible area and which doesn’t get out of sight when the page is scrolled, thereby making horizontal scrolling of the container much handier.
Installation
vue-handy-scroll is available on npm, so you may add it to your project as usual:
npm install vue-handy-scroll
After that you may import the component in your app:
import HandyScroll from "vue-handy-scroll";
If you don’t use module bundlers but instead prefer using the component directly in a browser, you may add the component on your page through some CDN such as jsDelivr or unpkg. E.g.:
<script src=""></script> <script src=""></script> or <script src=""></script> <script src=""></script>
Usage
Adding the component in templates
Add the component in your templates as follows:
<HandyScroll> <!-- Place horizontally wide contents here --> </HandyScroll>
or (in DOM templates):
<handy-scroll> <!-- Place horizontally wide contents here --> </handy-scroll>
Updating scrollbar
If the layout of your web page may dynamically change, and these changes affect scrollable containers, then you need a way to update the scrollbar every time the container’s sizes change. This can be done by emitting the event
update through the event bus provided by the component.
import {EventBus} from "vue-handy-scroll"; // ... some actions which change the total scroll width of the container ... EventBus.$emit("update", {sourceElement: this.$el});
As demonstrated by the example above, when emitting the event, you may pass a reference to the source element. The component uses this reference to detect which scrollable container is actually affected, and updates only the one that contains the provided source element inside it. If you emit the
update event without providing the source element, all instances of the component will be updated.
Custom viewport element
Sometimes, you may want to place the floating scrollbar in a container living in a positioned box (e.g. in a modal popup with
position: fixed). To do so, the component needs to be switched to a special functioning mode by specifying the prop
custom-viewport:
<HandyScroll : <!-- Place horizontally wide contents here --> </HandyScroll>
The resulting rendered HTML will have the following structure:
<div class="handy-scroll-viewport"> <!-- slot “viewport-before” --> <div class="handy-scroll-body"> <!-- slot “body-before” --> <div class="handy-scroll-area"> <!-- Horizontally wide contents goes here (slot “default”) --> </div> <!-- slot “body-after” --> </div> <!-- slot “viewport-after” --> </div>
Notice the placement of named slots in this structure (denoted by comments for clarity). You may use them to distribute content as needed. E.g.:
<HandyScroll : <template #vieport-before> whatever meaningful to be placed between “viewport’s” and “body’s” opening tags </template> <!-- Place horizontally wide contents here --> </HandyScroll>
The
.handy-scroll-viewport element is a positioned block (with any type of positioning except
static) which serves for correct positioning of the scrollbar widget. Note that this element itself should not be scrollable. The
.handy-scroll-body element is a vertically scrollable block (with
overflow: auto) which encloses the target container the floating scrollbar is mounted in.
The component provides some basic styles for elements with classes
.handy-scroll-viewport and
.handy-scroll-body. Feel free to adjust their styles in your stylesheets as needed (it that case you’ll probably need deep selectors
::v-deep).
“Unobtrusive” mode
You can make the floating scrollbar more “unobtrusive” so that it will appear only when the mouse pointer hovers over the scrollable container. To do so just set the prop
unobtrusive to
true:
<HandyScroll : <!-- Place horizontally wide contents here --> </HandyScroll> | https://vuejsexamples.com/handy-floating-scrollbar-component-for-vue-js/ | CC-MAIN-2022-40 | refinedweb | 625 | 54.63 |
.
Upgrading from 3.6.x to 3.8.x (Hazelcast IMDG Enterprise) when using
JCache:
Due to a compatibility problem,
CacheConfig serialization may not work if your member is 3.8.x where x < 5. Hence, you will need to use Hazelcast 3.8.5 or higher version where the problem is being fixed. This issue affects Hazelcast IMDG Enterprise only. that the Hazelcast member listens to and sends discovery messages through..
NOTE:
tcp-ip element also accepts the
interface parameter. Please refer to the Interfaces element description...
Hazelcast members operating on binaries of the same major and minor version numbers are compatible regardless of patch version.
For example, in a cluster with members running on version 3.7.1, it is possible to perform a rolling upgrade to 3.7.2 by shutting down, upgrading to
hazelcast-3.7.2.jar binary
and starting each member one by one. Patch level compatibility applies to both Hazelcast IMDG and Hazelcast IMDG Enterprise.
Starting with Hazelcast IMDG Enterprise 3.8, each next minor version released will be compatible with the previous one. For example, it will be possible to perform a rolling upgrade on a cluster running Hazelcast IMDG Enterprise 3.8 to Hazelcast IMDG Enterprise 3.9.
NOTE: The version numbers used in the paragraph below are only used as an example.
Let's assume a cluster with four members running on codebase version
3.8.0 with cluster version
3.8, that should be upgraded to codebase version
3.9.0 and cluster version
3.9. The rolling upgrade process for this cluster, i.e., replacing existing
3.8.0 members one by one with an upgraded
one at version
3.9.0, includes the following steps which should be repeated for each member:
3.8.0member.
3.9.0Hazelcast binaries.
... INFO: [192.168.2.2]:5701 [cluster] [3.9] Hazelcast 3.9 (20170630 - a67dc3a) starting at [192.168.2.2]:5701 ... INFO: [192.168.2.2]:5701 [cluster] [3.9] Cluster version set to 3.8
The version in brackets
[3.9] still denotes the member's codebase version (running on the hypothetical
hazelcast-3.9.jar binary). Once the member
locates existing cluster members, it sends its join request to the master. The master validates that the new member is allowed to join the cluster and
lets the new member know that the cluster is currently operating at
3.8 cluster version. The new member sets
3.8 as its cluster version and starts operating
normally.
At this point all members of the cluster have been upgraded to codebase version
3.9.0 but the cluster still operates at cluster version
3.8. In order to use
3.9 features
the cluster version must be changed to
3.9. There are two ways to accomplish this:, the cluster version is not yet known to a member that has not joined any cluster.
By default the newly started member will use the cluster protocol that corresponds to its codebase version until this member joins a cluster
(so for codebase
3.9.0 this means implicitly assuming cluster version
3.9). If, hypothetically, major changes in discovery & join operations
have been introduced which do not allow the member to join a
3.8 cluster, then the member should be explicitly configured to start
assuming a
3.8 cluster version.
Do I have to upgrade clients to work with rolling upgrades?
Starting with Hazelcast..
public static void main( String[] args ) {.
Hazelcast uses the name of a distributed object to determine which partition it will be put. Let's load two semaphores as shown below:
public static void main( String[] args ) {:
public static void main( String[] args ) {.
Hazelcast will partition your map entries and almost evenly distribute them onto all Hazelcast members. Each member carries approximately "(1/n
* total-data) + backups", n being System Properties section..,
EntryProcessor.processor:
Finally, when all the above steps are not enough, Hazelcast throws a Native Out of Memory Exception.
NOTE: This section is valid for Hazelcast 3.7 and higher releases..
NATIVE: (Hazelcast IMDG Enterprise HD) This option is used to enable the map to use Hazelcast's High-Density Memory Store. Please refer to the Using High-Density Memory Store with Map section.. null; } }
NOTE:..
backup-countis greater than 0).. by default, which means it applies only the last update on that key. However, you can set
MapStoreConfig#setWriteCoalescing to
FALSE and you can store all updates performed on a key to the data store.
NOTE: When you set
MapStoreConfig#setWriteCoalescing to
FALSE, after you reached per-node maximum write-behind-queue capacity, subsequent put operations will fail with
ReachedMaxSizeException. This exception will be thrown to prevent uncontrolled grow of write-behind queues. You can set per-node maximum capacity using the system property
hazelcast.map.write.behind.queue.capacity. Please refer to the System Properties section for information on this property and how to set the system properties.
In write-behind mode, when the
map.put(key,value) call returns:
backup-countis greater than, up.
NOTE: The return type of
loadAllKeys() is changed from
Set to
Iterable with the release of Hazelcast 3.5. MapLoader implementations from previous releases are also supported and do not need to be adapted.() ); } }
NOTE: Please.
puts are finished.
Now, let's create a
Consumer class. following are the example MultiMap" );).
The following are example semaphore" );.
IAtomicReference; but be careful about is sent.
Hazelcast
ICountDownLatch is the distributed implementation of
java.util.concurrent.CountDownLatch. consistency..
Replicated Map can be configured programmatically or declaratively.. Please see the In-Memory Format section. The default value is
OBJECT.
async-fillup: Specifies whether );
All properties that can be configured using the declarative configuration are also available using programmatic configuration by transforming the tag names into getter or setter Map serves the same purpose as it would on other
data structures in Hazelcast. You can use it to react on add, update, and remove operations. Replicated Maps do not yet support eviction..
The Fibonacci callable class below calculates the Fibonacci number for a given number. In the
calculate method, we check if the current thread is interrupted so that the code can respond to cancellations once the execution is started..orName() { return OFFLOADABLE_EXECUTOR; } }
Distributed queries access data from multiple data sources stored on either the same or different members.
Hazelcast partitions your data and spreads it across cluster of members..
Distributed query is highly scalable. If you add new members to the cluster, the partition count for each member is reduced and thus the time spent by each member on iterating its entries is reduced. In addition, the pool of partition threads evaluates the entries concurrently in each member, and member.'); Collection<Motorbike> result = map.values(p);
The exact same query may be executed using the
SQLPredicate as shown below:
Predicate p = new SQLPredicate('wheels[any].name', 'front'); →.ONE_PHASE );.. Caching is used to prevent additional request round trips for frequently used data. In both cases, caching can be used to gain performance or decrease application latencies..:
onCreatedmethod to call after an entry is created.
onUpdatedmethod to call after an entry is updated.
onRemovedmethod to call after an entry is removed.
onExpiredmethod to call after an entry expires.. );Manag); and different namespaces on the
CacheManager level, and therefore they.
Defining a Custom Cache Types, Implementing EntryProcessor section.
Since Hazelcast provides backups of cached entries on other members,>
Configuring>
You can mark Hazelcast Distributed Objects and add
<hz:spring-aware /> tag.
<hz:spring-aware / the first member. SpringAware. Spring 3.2 and later versions support JCache compliant caching providers. You can also use JCache caching backed by Hazelcast if your Spring version supports JCache.
underlying cache. You can configure a map with your cache's name if you want to set additional configuration(); }
..
This chapter describes Hazelcast's High-Density Memory Store and Hot Restart Persistence features along with their configurations, and gives recommendations on the storage sizing.
Hazelcast IMDG Enterprise HD IMDG Enterprise HD, the High-Density Memory Store is Hazelcast’s new single member)RestartStateImpl.LocalLocal member side and client side, you can refer to their sections as listed below.
Hazelcast provides the services discussed below Client.);
RELATED INFORMATION);
Hazelcast IMDG Enterprise
You can use SSL to secure the connection between the client and the members. site.
The example declarative and programmatic configurations below show how to configure a Java client for connecting to a Hazelcast cluster in AWS.
Declarative:
... <network> <aws enabled="true"> >
Programmatic:")); LifecycleListener, MembershipListener and DistributedObjectListener.).,
You can put a new
key1/value1 entry into a map by using POST call to
rest/maps/mapName/key1
If you want to retrieve an entry, you can use a GET call to. You can also retrieve this entry from another member of your cluster, such as
maps/mapName/key1..., for example. for Java Serializable., such as
IMap.replace(), and if byte-content of equal objects is different, you may face unexpected behaviors. For example, if the class relies on a hash map, the); } }
You explicitly perform writing and reading of fields. Perform reading in the same order as writing. | https://docs.hazelcast.org/docs/3.8.4/manual/html-single/index.html | CC-MAIN-2022-33 | refinedweb | 1,517 | 51.44 |
Undeclared identifier QGridLayout
i the header file <QtGui>, but the compiler note me that undeclared identifier QGridLayout
#include <QtGui>
QGridLayout *gridlayout = new QGridLayout;
I know i include <QGridLayout> file can solve it.
does it mean that if there are many widgets, i must include many header files ?
- kshegunov Qt Champions 2016
@ozzy
You're using Qt5, which means that you either have to do a full include of <QtWidgets> (widgets are in a separate module now) or include the
QGridLayout's header explicitly (which is the better way in my opinion).
You also might need to add the widgets module to your .pro file, if not done already, like this:
QT += widgets.
Kind regards.
- raven-worx Moderators
@ozzy
to add to @kshegunov post:
In case you are unsure in which module the class is contained you can quickly check on the very top of the related doc page.
my.pro file contain the sentence: greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
i change #include <QtGui> to #include <QtWidgets> everything works well.
Thank you ~ | https://forum.qt.io/topic/63160/undeclared-identifier-qgridlayout | CC-MAIN-2018-13 | refinedweb | 171 | 55.88 |
If you asked a group of developers, "What is the most difficult UI to implement?", I would guess a majority would have something to say about dates, calendars, and scheduling. Calendars are hard. Leap years, holidays, weekends - it's too much for someone to have to manage. You shouldn't have to remember "30 days has September..." in lieu of writing code.
When you throw "mobile" into the mix, it gets all that much more complicated. How do you create an effective UI that balances a small canvas with a month's or even a year's worth of event data?
NativeScript UI to the rescue! NativeScript UI is a clean abstraction on top of native calendar UIs provided by iOS and Android. With NativeScript UI we are building on the Telerik tradition of providing easy to use components that delight developers with their ease of use - and delight end users with their engaging features.
This post is part of our "week of NativeScript UI" that goes into the how-to of each NativeScript UI component. Today is all about the Calendar and is the final article of our series: Calendar component.
The Calendar component (known in code as RadCalendar), exposes a unified API on top of the native calendar controls provided by iOS and Android. No more individual, platform-specific implementations of event/scheduling UIs. With RadCalendar we do the heavy lifting for you and grant you the ability to add complex, mobile-optimized UI widgets to your app with a minimal amount of code.
RadCalendar allows you to display events inline (as in the above example), customize your week/month/year views, style calendars with CSS, and handle calendar events based on user interactions.
Navigate to your NativeScript project directory and install NativeScript UI Calendar with the following command (no manual download required):
tns plugin add nativescript-ui-calendarCalendar. If "XML namespace" scares you, have no fear. You just need to add a property to your root
<Page> element, like this:
<Page xmlns:
Next, we need to add a RadCalendar component to our XML markup, as in:
<Page xmlns: <calendar:RadCalendar </Page>
Believe it or not, a code sample this simple resolves into a nice looking calendar:
But let's add some events and see what else RadCalendar can do for us!
RadCalendar allows us to easily add event data via the
CalendarEvent class, which describes a single event and exposes a variety of properties.
Let's start by making some minor changes to our XML markup:
<Page xmlns="" xmlns: <ActionBar title="RadCalendar Demo" class="action-bar" /> <calendar:RadCalendar </Page>
What changed?
pageLoadedfunction to the
loadedevent (see below).
ActionBarto show a title in our view.
eventSource="{{ events }}"to associate the data source with our calendar.
Next, let's add some code to our JavaScript code-behind file:
var Observable = require("data/observable").Observable; var calendarModule = require("nativescript-telerik-ui-pro/calendar"); var page; var pageData = new Observable(); exports.pageLoaded = function(args) { page = args.object; page.bindingContext = pageData; var eventTitles = ["Lunch with Steve", "Meeting with Jane", "Q1 Recap Meeting"]; var events = []; var j = 1; for (var i = 0; i < eventTitles.length; i++) { var now = new Date(); var startDate = new Date(now.getFullYear(), now.getMonth(), j * 2, 12); var endDate = new Date(now.getFullYear(), now.getMonth(), (j * 2) + (j % 3), 13); var event = new calendarModule.CalendarEvent(eventTitles[i], startDate, endDate); events.push(event); j++; } pageData.set("events", events); }
In this code sample we are providing some fake event data to our calendar. The key line of code is this:
var event = new calendarModule.CalendarEvent(eventTitles[i], startDate, endDate);
This is where we are creating the individual event with the
CalendarEvent class. Note that the
startDate and
endDate variables are just plain JavaScript date objects!
Looking for Angular code samples? Check out our complete docs for Angular as well!
This results in the following changes to our calendar app:
Note that the styles you see come from the core light theme that is part of NativeScript, plus some customizations made with the NativeScript Theme Builder.
We have data in our calendar (which we can see based on the dot in iOS and the short event preview in Android). However, we'd like to actually see the event data somehow!
This is accomplished using the event view modes provided by RadCalendar. By tweaking our markup, we can see our event data either
Inline or via a
Popover:
<calendar:RadCalendar
Inline on iOS:
Popover on Android:
Now we don't always want to see our calendar in the full month view (which is the default). In scenarios where you want to show a different view of dates, you can use the RadCalendar's
viewMode property, which supports the following options:
Week(displays one week of dates)
Month(displays one month at a time - default)
MonthNames- (shows all month names in a year)
Year- (shows us an entire year of days on one screen - see below)
When swiping to move between weeks/months/years, NativeScript will use the host platform's native transitions. With RadCalendar, you can specify different transition modes:
You can try out these transitions by setting the
transitionMode property of your RadCalendar. Here is an example of the
Stack transition on iOS and Android:
RadCalendar allows you to create customized calendar controls with ease. Imagine adding a RadDataForm to the mix to create a fully-capable scheduling system! | https://blog.nativescript.org/a-deep-dive-into-telerik-ui-for-nativescripts-calendar/index.html | CC-MAIN-2021-21 | refinedweb | 897 | 54.12 |
React is an open source library built by Facebook for building user interfaces in a declarative approach. ImageEngine is an image CDN that helps accelerate the performance of your website with their plug-in toolsets.
This article explores the easiest technique to get started with the integration of ImageEngine in React. This is a React beginner friendly article, but in case you’re completely new to React, you can brush up the basics from their documentation and those are enough for implementing the code discussed here.
We will walkthrough the following topics:
- ImageEngine Component vs HTML Image Tag
- Demo
- Implementation
In case you’re already familiar with the ImageEngine, feel free to skip to the implementation details in section 2 and 3.
ImageEngine Component vs HTML Image Element
React natively does not provide any image component so the common approach is to use the native image element within JSX as follows:
<img src="/images/bike.jpg" alt="Bike" />
This works well, until you realise you would need various customisations to the images, such as changing the image format to the modern optimised image format like WebP or AVIF.
The series of steps to do this is:
- Convert all images throughout the website to the given new format.
- Compress the new images.
- Upload the new images to the desired storage such as S3.
- Refactor the code at all instances of image tags and change into the new particular format.
After all this effort, what about other customisations that are instance specific, like on the homepage hero image the requirements are to rotate the image by 20 degrees, the footer image might need to be stretched, or the image width might need some alterations etc.
All of this is time consuming and exerting and should be actually fixed with options in a custom Image Component itself.
Let’s take a look at how to get this done in the ImageEngine Image Component.
<Image src={`/images/bike.jpg`} alt="Bike" directives={{ width: 200, rotate: 20, outputFormat: 'webp' }} />
This is it, all the manual and laborious steps can be avoided by simply toggling the directives options such as setting width, rotate and even output format. This is how capable ImageEngine can make our native HTML Image Tag.
Demo
To play around with ImageEngine’s demo, you can head over to the website and toggle around with various options available with ImageEngine’s components. Please note, these are not the only available options. You can get the gist of how easy it is to generate images of various specifications without the need for any manual efforts of uploading, compressing, resizing, renaming in the code, purging the cache etc.
While you play around with various options in the browser, you can even open the Network Tab in the Dev Tools of your browser to find out the images being generated in real-time according to the attributes assigned to the image tag with various options for compression, size, sharpness etc.
Implementation
Now that you’re convinced of the power of ImageEngine, let’s get started with the ImageEngine Node library installation and setup.
Firstly, signup at ImageEngine.io if you haven’t already and go to the dashboard to get your delivery address.
Note: For quick start the ImageEngine Guide is self-explanatory and sufficient, the team also provides a video demo for further speedy start.
Next we move on to the code.
Install the library using the
npm install command in the terminal in the root folder of the project. Save option is added to be saved as a dependency for the project.
npm i @imageengine/react --save
A bonus for ImageEngine’s library is that it natively supports TypeScript, giving a smooth integration with the typescript react projects as well.
The next step is adding a provider to the root component in the React project. Generally, this is the
App.tsx or
App.jsx file.
First, import the ImageEngineProvider:
import { ImageEngineProvider } from "@imageengine/react"
Second, add the image provider to the root component with your specific delivery address like:
This is the host that serves the images from ImageEngine.
<ImageEngineProvider deliveryAddress="YOUR IMAGE DELIVER ADDRESS"> <div className="App"> </div> </ImageEngineProvider>
Finally, import the image component from ImageEngine and replace the image element with this:
import { Image } from "@imageengine/react"; <Image src={`/images/bike.jpg`} alt="Bike" directives={{ width: 100, fitMethod: “stretch”, rotate: 20, }} />
The demo code for this implementation is Open Sourced and can be checked at Github and to play with various ImageEngine options such as rotate, sharpness, rotate etc. A real interactive demo can be checked here.
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/iamyatin/getting-started-with-imageengine-and-react-31jn | CC-MAIN-2021-39 | refinedweb | 767 | 50.16 |
Abstract base for all MasterClients. More...
#include <masterclient.h>
Abstract base for all MasterClients.
This is expected to fetch a list of IP addresses which will be turned into Servers.
Definition at line 49 of file masterclient.h.
Produce contents of server list request packet that is sent to the master server.
Implemented in CustomServers.
Clears the server list.
Definition at line 110 of file masterclient.cpp.
Extracts engine name from pluginInfo() if available.
Definition at line 119 of file masterclient.cpp.
Returns true if the passed address:port is the same as this master server's.
Definition at line 92 of file masterclient.cpp.
Serves as an informative role for MasterManager. If the master client is disabled, master manager will omit it during the refresh.
Definition at line 128 of file masterclient.cpp.
Indicates that the server has timeouted recently.
This is reset to false by refresh() and set to true by timeoutRefresh(). If you reimplement refresh() please remember to set this to false.
Definition at line 133 of file masterclient.cpp.
[Virtual] Help message displayed to the user when ban is detected.
Doomseeker displays a "you're banned from this master server" message when RESPONSE_BANNED is returned by readResponse(). By redefining this method, your plugin may show additional help message next to the usual one. Normally, you'd have this return some kind of staff contact info. Basic HTML is supported in the display.
Default implementation returns an empty string..
This is supposed to return the plugin this MasterClient belongs to. If it doesn't belong to any plugin then return NULL. New instances of EnginePlugin shouldn't be created here. Instead each plugin should keep a global instance of EnginePlugin (singleton?) and a pointer to this instance should be returned.
Implemented in CustomServers, and MasterManager.
Called to read and analyze the response from the MasterServer.
Implemented in CustomServers.
Calls readMasterResponse and handles packet caching.
Definition at line 241 of file masterclient.cpp.
Requests an updated server list from the master.
This function is virtual since MasterManager overrides it.
Reimplemented in CustomServers.
Definition at line 319 of file masterclient.cpp.
Registers new server with this MasterClient.
Definition at line 304 of file masterclient.cpp.
Sends request packet through socket.
Definition at line 326 of file masterclient.cpp.
Definition at line 344 of file masterclient.cpp.
Times the refreshing process out.
This calls timeoutRefreshEx() and then emits listUpdated() signal.
Definition at line 354 of file masterclient.cpp.
Reimplement this for clean up purposes.
Definition at line 369 of file masterclient.cpp. | https://doomseeker.drdteam.org/docs/doomseeker_1.0/classMasterClient.php | CC-MAIN-2021-25 | refinedweb | 422 | 54.69 |
C and C++ accept pointers in a way that most other programming languages do not. References are supported by other languages such as C++, Java, Python, Ruby, Perl, and PHP.
Both references and pointers seem to be very similar on the surface; both are used to allow one variable provide access to another. For both having much of the same capabilities, it is often unclear what distinguishes these two systems. In this post, we will discuss the difference between pointers and references.
Pointer vs Reference
1)Pointers
A variable that holds the memory address of another variable is known as a pointer. To access the memory location that a pointer points to, it must be dereferenced with the * operator.
2)Reference
A reference variable is an alias, or another name for a variable that already exists. A reference, like a pointer, is implemented by storing an object’s address.
A reference can be thought of as a constant pointer (not to be confused with a constant value pointer!). The compiler can apply the * operator for you if you use automatic indirection.
3)Differences
1)A reference is a type of const pointer that automatically de-references itself. Yes, it is similar to a const pointer in that once a reference is attached to a variable or entity, it cannot be changed to point to anyone else.
If you attempt to point an already initialised reference to another variable, it will not change its reference point instead, this type of assignment will only change the value of the variable to which the reference was pointing.
In contrast, you can adjust the value of a pointer i.e, force a pointer to point to a new memory location at run time.
Below is the implementation:
#include <iostream> using namespace std; int main() { int first_element = 50; int second_element = 100; // First, set Reference ref1 to point to a variable // first_element int& ref1 = first_element; cout << "first element = " << first_element << endl; cout << "second element = " << second_element << endl; cout << "reference 1 = " << ref1 << endl; /* If you attempt to point the reference ref 1 to another variable, say second_element, it will not change its reference point instead, this type of assignment will only change the value of the variable to which the reference was pointing.*/ ref1 = second_element; cout << "After modifying the reference 1 value , ref1 = " << ref1 << endl; cout << "first element = " << first_element << endl; cout << "second element = " << second_element << endl; // initializing a pointer that points to first value int* ptr = &first_element; cout << "pointer = " << ptr << " :: *ptr = " << (*ptr) << endl; // modifying the value of second element second_element = 200; ptr = &second_element; cout << "pointer = " << ptr << " :: *ptr = " << (*ptr) << endl; return 0; }
Output:
first element = 50 second element = 100 reference 1 = 50 After modifying the reference 1 value , ref1 = 100 first element = 100 second element = 100 pointer = 0x7ffc457fec50 :: *ptr = 100 pointer = 0x7ffc457fec54 :: *ptr = 200
2)It is needed to initialise a reference while declaring it, i.e. A pointer, on the other hand, may be declared without being initialised. As a result, pointer may also be set to NULL. In contrast, it is not possible with a Reference.
Example:
int value = 100; int& reference = value; // correct way to initialize int& var; // it is wrong and it won't compile int* pointer; // correct way pointer = NULL; // Correct way reference = NULL; // it is wrong and it won't compile
3)You cannot have a reference to a reference, but you can have a pointer to a pointer.
4)A pointer’s value can be incremented and decremented, and it can be used for random indexing, but this is not possible with a reference.
Example:
int* pointer = new int[100]; *(pointer + 5) = 100;
5)If you take a reference’s address, it will be identical to the address of the variable to which it is referring. In the case of a pointer, though, the situation is different.
6)If pointers are allocated on heap, there is always a chance and extra effort to delete them. There may be issues such as memory leaks and hanging pointers. In the case of references, however, it is fine, and you do not need to be concerned with such issues.
7)A pointer on the stack has its own memory address and size, while a reference on the stack has the same memory address (as the original variable) but takes up some stack space.
8)Pointers can perform a variety of arithmetic operations, but there is no such thing as Reference Arithmetic. (However, as in &obj + 12, you can take the address of an object pointed by a reference and perform pointer arithmetic on it.)
Related Programs:
- compare and get differences between two lists in python
- python program to generate a dictionary that contains numbers between 1 and n in the form x xx
- how to code a scraping bot with selenium and python
- how to create and initialize a list of lists in python
- python how to create a list and initialize with same values
- how to create a navigation bar and sidebar using react
- what is the difference between final and immutable in java | https://btechgeeks.com/differences-between-a-pointer-and-reference/ | CC-MAIN-2022-27 | refinedweb | 838 | 53.95 |
) with a functioning anydbm module. Download the latest version from. It is highly recommended that users install the latest patch version of python as these contain many fixes to serious bugs.
Some variants of Linux will need an additional “python dev” package installed for Roundup installation to work. Debian and derivatives, are known to require this.
The Xapian full-text indexer is also supported and will be used by default if it is available. This is strongly recommended if you are anticipating a large number of issues (> 5000).
You may install Xapian at any time, even after a tracker has been installed and used. You will need to run the “roundup-admin reindex” command if the tracker has existing data.
Roundup requires Xapian
To install the Roundup support code into your Python tree and Roundup scripts into /usr/bin (substitute that path for whatever is appropriate on your system). You need to have write permissions for these locations, eg. being root on unix:
python setup.py install
If you would like to place the Roundup scripts in a directory other than /usr/bin, then specify the preferred location with --install-scripts. For example, to install them in /opt/roundup/bin:
python setup.py install --install-scripts=/opt/roundup/bin
You can also use the --prefix option to use a completely different base directory, if you do not want to use administrator rights. If you choose to do this, you may have to change Python’s search path (sys.path) yourself.
Configuring your first tracker
To create a Roundup tracker (necessary to do before you can use the software in any real fashion), you need to set up a “tracker home”:
(Optional) If you intend to keep your roundup trackers under one top level directory which does not exist yet, you should create that directory now. Example:
mkdir /opt/roundup/trackers
Either add the Roundup script location to your PATH environment variable or specify the full path to the command in the next step.
Install a new tracker with the command roundup-admin install. You will be asked a series of questions. Descriptions of the provided templates can be found in choosing your template below. Descriptions of the available backends can be found in choosing your backend below. The questions will be something like (you may have more templates or backends available):
Enter tracker home: /opt/roundup/trackers/support Templates: classic Select template [classic]: classic Back ends: anydbm, mysql, sqlite Select backend [anydbm]: anydbm
Note: “Back ends” selection list depends on availability of third-party database modules. Standard python distribution includes anydbm module only.
The “support” part of the tracker name can be anything you want - it is going to be used as the directory that the tracker information will be stored in.
You will now be directed to edit the tracker configuration and initial schema. At a minimum, you must set “main :: admin_email” (that’s the “admin_email” option in the “main” section) “mail :: host”, “tracker :: web” and “mail :: domain”. If you get stuck, and get configuration file errors, then see the tracker configuration section of the customisation documentation.
If you just want to get set up to test things quickly (and follow the instructions in step 3 below), you can even just set the “tracker :: web” variable to:
web =
The URL must end in a ‘/’, or your web interface will not work. See Customising Roundup for details on configuration and schema changes. You may change any of the configuration after you’ve initialised the tracker - it’s just better to have valid values for this stuff now.
Initialise the tracker database with roundup-admin initialise. You will need to supply an admin password at this step. You will be prompted:
Admin Password: Confirm:
Note: running this command will destroy any existing data in the database. In the case of MySQL and PostgreSQL, any existing database will be dropped and re-created.
Once this is done, the tracker has been created. See the note in the user_guide on how to initialise a tracker without being prompted for the password or exposing the password on the command line.
At this point, your tracker is set up, but doesn’t have a nice user interface. To set that up, we need to configure a web interface and optionally configure an email interface. If you want to try your new tracker out, assuming “tracker :: web” is set to '', run:
roundup-server support=/opt/roundup/trackers/support
then direct your web browser at:
and you should see the tracker interface.
This uses the embedded database engine PySQLite to provide a very fast backend. This is not suitable for trackers which will have many simultaneous users, but requires much less installation and maintenance effort than more scalable postgresql and mysql backends.
SQLite is supported via PySQLite versions 1.1.7, 2.1.0 and sqlite3 (the last being bundled with Python 2.5+)
Installed SQLite should be the latest version available (3.3.8 is known to work, 3.1.3 is known to have problems).
-
You may defer your decision by setting your tracker up with the anydbm backend (which is guaranteed to be available) and switching to one of the other backends at any time using the instructions in the administration guide.
Regardless of which backend you choose, Roundup will attempt to initialise a new database for you when you run the roundup-admin “initialise” command. In the case of MySQL and PostgreSQL you will need to have the appropriate privileges to create databases.
A benefit of using the cgi-bin approach is that it’s the easiest way to restrict access to your tracker to only use HTTPS. Access will be slower than through the stand-alone web server though.
If your Python isn’t installed as “python” then you’ll need to edit the roundup.cgi script to fix the first line.
If you’re using IIS on a Windows platform, you’ll need to run this command for the cgi to work (it turns on the PATH_INFO cgi variable):
adsutil.vbs set w3svc/AllowPathInfoForScriptMappings TRUE
The adsutil.vbs file can be found in either c:\inetpub\adminscripts or c:\winnt\system32\inetsrv\adminsamples\ or c:\winnt\system32\inetsrv\adminscripts\ depending on your installation.
More information about ISS setup may be found at:
Copy the frontends/roundup.cgi file to your web server’s cgi-bin directory. You will need to configure it to tell it where your tracker home is. You can do this either:
-'
The “name” part of the configuration will appear in the URL and identifies the tracker (so you may have more than one tracker per cgi-bin script). Make sure there are no spaces or other illegal characters in it (to be safe, stick to letters and numbers). The “name” forms part of the URL that appears in the tracker config “tracker :: web” variable, so make sure they match. The “home” part of the configuration is the tracker home directory.
If you’re using Apache, you can use an additional trick to hide the .cgi extension of the cgi script. Place the roundup.cgi script wherever you want it to be, rename it to just roundup, and add a couple lines to your Apache configuration:
<Location /path/to/roundup> SetHandler cgi-script </Location>
This approach will give you faster response than cgi-bin. You may investigate using ProxyPass or similar configuration in apache to have your tracker accessed through the same URL as other systems.
The stand-alone web server is started with the command roundup-server. It has several options - display them with roundup-server -h.
The tracker home configuration is similar to the cgi-bin - you may either edit the script to change the TRACKER_HOMES variable or you may supply the name=home values on the command-line after all the other options.
To make the server run in the background, use the “-d” option, specifying the name of a file to write the server process id (pid) to.
Zope Product - ZRoundup
ZRoundup installs as a regular Zope product. Copy the ZRoundup directory to your Products directory either in INSTANCE_HOME/Products or the Zope code tree lib/python/Products.
When you next (re)start up Zope, you will be able to add a ZRoundup object that interfaces to your new tracker.
Apache HTTP Server with mod_python
Mod_python is an Apache module that embeds the Python interpreter within the server. Running Roundup this way is much faster than all above options and, like web server cgi-bin, allows you to use HTTPS protocol. The drawback is that this setup is more complicated.
The following instructions were tested on apache 2.0 with mod_python 3.1. If you are using older versions, your mileage may vary.
Mod_python uses OS threads. If your apache was built without threads (quite commonly), you must load the threading library to run mod_python. This is done by setting LD_PRELOAD to your threading library path in apache envvars file. Example for gentoo linux (envvars file is located in /usr/lib/apache2/build/):
LD_PRELOAD=/lib/libpthread.so.0 export LD_PRELOAD
Example for FreeBSD (envvars is in /usr/local/sbin/):
LD_PRELOAD=/usr/lib/libc_r.so export LD_PRELOAD
Next, you have to add Roundup trackers configuration to apache config. Roundup apache interface uses the following options specified with PythonOption directives:
- TrackerHome:
- defines the tracker home directory - the directory that was specified when you did roundup-admin init. This option is required.
- TrackerLanguage:
- defines web user interface language. mod_python applications do not receive OS environment variables in the same way as command-line programs, so the language cannot be selected by setting commonly used variables like LANG or LC_ALL. TrackerLanguage value has the same syntax as values of these environment variables. This option may be omitted.
- TrackerDebug:
- run the tracker in debug mode. Setting this option to yes or true has the same effect as running roundup-server -t debug: the database schema and used html templates are rebuilt for each HTTP request. Values no or false mean that all html templates for the tracker are compiled and the database schema is checked once at startup. This is the default behaviour.
- TrackerTiming:
- has nearly the same effect as environment variable CGI_SHOW_TIMING for standalone roundup server. The difference is that setting this option to no or false disables timings display. Value comment writes request handling times in html comment, and any other non-empty value makes timing report visible. By default, timing display is disabled.
In the following example we have two trackers set up in /var/db/roundup/support and /var/db/roundup/devel and accessed as and respectively (provided Apache has been set up for SSL of course). Having them share same parent directory allows us to reduce the number of configuration directives. Support tracker has russian user interface. The other tracker (devel) has english user interface (default).
Static files from html directory are served by apache itself - this is quicker and generally more robust than doing that from python. Everything else is aliased to dummy (non-existing) py file, which is handled by mod_python and our roundup module.
Example mod_python configuration:
################################################# # Roundup Issue tracker ################################################# # enable Python optimizations (like 'python -O') PythonOptimize On # let apache handle static files from 'html' directories AliasMatch /roundup/(.+)/@@file/(.*) /var/db/roundup/$1/html/$2 # everything else is handled by roundup web UI AliasMatch /roundup/([^/]+)/(?!@@file/)(.*) /var/db/roundup/$1/dummy.py/$2 # roundup requires a slash after tracker name - add it if missing RedirectMatch permanent ^/roundup/([^/]+)$ /roundup/$1/ # common settings for all roundup trackers <Directory /var/db/roundup/*> Order allow,deny Allow from all AllowOverride None Options None AddHandler python-program .py PythonHandler roundup.cgi.apache # uncomment the following line to see tracebacks in the browser # (note that *some* tracebacks will be displayed anyway) #PythonDebug On </Directory> # roundup tracker homes <Directory /var/db/roundup/support> PythonOption TrackerHome /var/db/roundup/support PythonOption TrackerLanguage ru </Directory> <Directory /var/db/roundup/devel> PythonOption TrackerHome /var/db/roundup/devel </Directory>
Notice that the /var/db/roundup path shown above refers to the directory in which the tracker homes are stored. The actual value will thus depend on your system.
On Windows the corresponding lines will look similar to these:
AliasMatch /roundup/(.+)/@@file/(.*) C:/DATA/roundup/$1/html/$2 AliasMatch /roundup/([^/]+)/(?!@@file/)(.*) C:/DATA/roundup/$1/dummy.py/$2 <Directory C:/DATA/roundup/*> <Directory C:/DATA/roundup/support> <Directory C:/DATA/roundup/devel>
In this example the directory hosting all of the tracker homes is C:\DATA\roundup. (Notice that you must use forward slashes in paths inside the httpd.conf file!)
The URL for accessing these trackers then become: http://<roundupserver>/roundup/support/` and http://<roundupserver>/roundup/devel/
Note that in order to use https connections you must set up Apache for secure serving with SSL.
WSGI Handler
The WSGI handler is quite simple. The following sample code shows how to use it:
from wsgiref.simple_server import make_server # obtain the WSGI request dispatcher from roundup.cgi.wsgi_handler import RequestDispatcher tracker_home = 'demo' app = RequestDispatcher(tracker_home) httpd = make_server('', 8917, app) httpd.serve_forever()
To test the above you should create a demo tracker with python demo.py. Edit the config.ini to change the web URL to “”.
Configure an Email Interface
If you don’t want to use the email component of Roundup, then remove the “nosyreaction.py” module from your tracker “detectors” directory.
See platform-specific notes for steps that may be needed on your system.
There are five supported ways to get emailed issues into the Roundup tracker. You should pick ONE of the following, all of which will continue my example setup from above:
As a mail alias pipe process
Set up a mail alias called “issue_tracker” as (include the quote marks): “|/usr/bin/python /usr/bin/roundup-mailgw <tracker_home>” (substitute /usr/bin for wherever roundup-mailgw is installed).
In some installations (e.g. RedHat Linux and Fedora Core) you’ll need to set up smrsh so sendmail will accept the pipe command. In that case, symlink /etc/smrsh/roundup-mailgw to “/usr/bin/roundup-mailgw” and change the command to:
|roundup-mailgw /opt/roundup/trackers/support
To test the mail gateway on unix systems, try:
echo test |mail -s '[issue] test' support@YOUR_DOMAIN_HERE
Be careful that some mail systems (postfix for example) will impost a limits on processes they spawn. In particular postfix can set a file size limit. This can cause your Roundup database to become corrupted.
As a custom router/transport using a pipe process (Exim4 specific)
The following configuration snippets for Exim 4 configuration implement a custom router & transport to accomplish mail delivery to roundup-mailgw. A configuration for Exim3 is similar but not included, since Exim3 is considered obsolete.
This configuration is similar to the previous section, in that it uses a pipe process. However, there are advantages to using a custom router/transport process, if you are using Exim.
-).
The matching is done in the line:
require_files = /usr/bin/roundup-mailgw:ROUNDUP_HOME/$local_part/schema.py
The following configuration has been tested on Debian Sarge with Exim4.
Note
Note that the Debian Exim4 packages don’t allow pipes in alias files by default, so the method described in the section As a mail alias pipe process will not work with the default configuration. However, the method described in this section does. See the discussion in /usr/share/doc/exim4-config/README.system_aliases on any Debian system with Exim4 installed.
For more Debian-specific information, see suggested addition to README.Debian in, which will hopefully be merged into the Debian package eventually.
This config makes a few assumptions:
-).
Macros for Roundup router/transport. Should be placed in the macros section of the Exim4 config:
# Home dir for your Roundup installation ROUNDUP_HOME=/var/lib/roundup/trackers # User and group for Roundup. ROUNDUP_USER=roundup ROUNDUP_GROUP=roundup
Custom router for Roundup. This will (probably) work if placed at the beginning of the router section of the Exim4 config:
Custom transport for Roundup. This will (probably) work if placed at the beginning of the router section of the Exim4 config:
roundup_transport: driver = pipe command = /usr/bin/python /usr/bin/roundup-mailgw ROUNDUP_HOME/$local_part/ current_directory = ROUNDUP_HOME home_directory = ROUNDUP_HOME user = ROUNDUP_USER group = ROUNDUP_GROUP
As a regular job using a mailbox source
Set roundup-mailgw up to run every 10 minutes or so. For example (substitute /usr/bin for wherever roundup-mailgw is installed):
0,10,20,30,40,50 * * * * /usr/bin/roundup-mailgw /opt/roundup/trackers/support mailbox <mail_spool_file>
Where the mail_spool_file argument is the location of the roundup submission user’s mail spool. On most systems, the spool for a user “issue_tracker” will be “/var/mail/issue_tracker”.
As a regular job using a POP source
To retrieve from a POP mailbox, use a cron entry similar to the mailbox one (substitute /usr/bin for wherever roundup-mailgw is installed):
0,10,20,30,40,50 * * * * /usr/bin/roundup-mailgw /opt/roundup/trackers/support pop <pop_spec>
where pop_spec is “username:password@server” that specifies the roundup submission user’s POP account name, password and server.
On windows, you would set up the command using the windows scheduler.
As a regular job using an IMAP source
To retrieve from an IMAP mailbox, use a cron entry similar to the POP one (substitute /usr/bin for wherever roundup-mailgw is installed):
0,10,20,30,40,50 * * * * /usr/bin/roundup-mailgw /opt/roundup/trackers/support imap <imap_spec>
where imap_spec is “username:password@server” that specifies the roundup submission user’s IMAP account name, password and server. You may optionally include a mailbox to use other than the default INBOX with “imap username:password@server mailbox”.
If you have a secure (ie. HTTPS) IMAP server then you may use imaps in place of imap in the command to use a secure connection.
As with the POP job, on windows, you would set up the command using the windows scheduler.’ users, the Roundup email gateway will need to have permissions to this area as well, so add the user your mail service runs as to the group (typically “mail” or “daemon”). The UNIX group might then look like:
support:*:1002:jblaine,samh,geezer,mail
If you intend to use the web interface (as most people do), you should also add the username your web server runs as to the group. My group now looks like this:
support:*:1002:jblaine,samh,geezer,mail,apache
The tracker “db” directory should be chmod’ed g+sw so that the group can write to the database, and any new files created in the database will be owned by the group.
If you’re using the mysql or postgresql backend then you’ll need to ensure that the tracker user has appropriate permissions to create/modify the database. If you’re using roundup.cgi, the apache user needs permissions to modify the database. Alternatively, explicitly specify a database login in rdbms -> user and password in config.ini.
An alternative to the above is to create a new user who has the sole responsibility of running roundup. This user:
- runs the CGI interface daemon
- runs regular polls for email
- runs regular checks (using cron) to ensure the daemon is up
- optionally has no login password so that nobody but the “root” user may actually login and play with the roundup setup.
If you’re using a Linux system (e.g. Fedora Core) with SELinux enabled, you will need to ensure that the db directory has a context that permits the web server to modify and create files. If you’re using the mysql or postgresql backend you may also need to update your policy to allow the web server to access the database socket..
Where <dir> in 7) is the root directory (e.g., C:\Python22\Scripts) of your Python installation.
I understand that in XP, 2) above is not needed as “Control Panel” is directly accessible from “Start”.
I do not believe this is possible to do in previous versions of Windows.
Windows Server
To have the Roundup web server start up when your machine boots up, there are two different methods, the scheduler and installing the service.
1. Using the Windows scheduler
Set up the following in Scheduled Tasks (note, the following is for a cygwin setup):
Run
c:\cygwin\bin\bash.exe -c "roundup-server TheProject=/opt/roundup/trackers/support"
Start In
C:\cygwin\opt\roundup\bin
Schedule
At System Startup
To have the Roundup mail gateway run periodically to poll a POP email address, set up the following in Scheduled Tasks:
Run
c:\cygwin\bin\bash.exe -c "roundup-mailgw /opt/roundup/trackers/support pop roundup:roundup@mail-server"
Start In
C:\cygwin\opt\roundup\bin
Schedule
Every 10 minutes from 5:00AM for 24 hours every day
Stop the task if it runs for 8 minutes
2. Installing the roundup server as a Windows service
This is more Windows oriented and will make the Roundup server run as soon as the PC starts up without any need for a login or such. It will also be available in the normal Windows Administrative Tools.
For this you need first to create a service ini file containing the relevant settings.
It is created if you execute the following command from within the scripts directory (notice the use of backslashes):
roundup-server -S -C <trackersdir>\server.ini -n <servername> -p 8080 -l <trackersdir>\trackerlog.log software=<trackersdir>\Software
where the item <trackersdir> is replaced with the physical directory that hosts all of your trackers. The <servername> item is the name of your roundup server PC, such as w2003srv or similar.
Next open the now created file C:\DATA\roundup\server.ini file (if your <trackersdir> is C:\DATA\roundup). Check the entries for correctness, especially this one:
[trackers] software = C:\DATA\Roundup\Software
(this is an example where the tracker is named software and its home is C:\DATA\Roundup\Software)
Next give the commands that actually installs and starts the service:
roundup-server -C C:\DATA\Roundup\server.ini -c install roundup-server -c start
Finally open the AdministrativeTools/Services applet and locate the Roundup service entry. Open its properties and change it to start automatically instead of manually.
If you are using Apache as the webserver you might want to use it with mod_python instead to serve out Roundup. In that case see the mod_python instructions above for details..
Once you’ve unpacked roundup’s source, run python run_tests.py in the source directory and make sure there are no errors. If there are errors, please let us know!
If the above fails, you may be using the wrong version of python. Try python2 run_tests.py. | http://roundup.sourceforge.net/docs/installation.html | CC-MAIN-2016-07 | refinedweb | 3,775 | 54.42 |
I am analyzing counting example in python presented by Codility
I don't understand the logic used in the last loop (5 last rows) of this algorithm.
Can anybody help please?
The problem:
You are given an integer((
m) and two non-empty,) and two non-empty,
1 < m < 1000000
zero-indexed arraysandand
Aofof
Bintegers,integers,
n,,
a0, ... ,, ... ,
a1
andand
an−1,,
b0, ... ,, ... ,
b1respectively (respectively (
bn−1,,
0 < ai).).
bi < m
The goal is to check whether there is a swap operation which can be
performed on these arrays in such a way that the sum of elements in
arrayequals the sum of elements in arrayequals the sum of elements in array
Aafter the swap. Byafter the swap. By
B
swap operation we mean picking one element from arrayand oneand one
A
element from arrayand exchanging them.and exchanging them.
B
def counting(A, m):
n = len(A)
count = [0] * (m + 1)
for k in xrange(n):
count[A[k]] += 1
return count
def fast_solution(A, B, m):
n = len(A)
sum_a = sum(A)
sum_b = sum(B)
d = sum_b - sum_a
if d % 2 == 1:
return False
d //= 2
count = counting(A, m)
for i in xrange(n):
if 0 <= B[i] - d and B[i] - d <= m and count[B[i] - d] > 0:
return True
return False
What I would recommend you is read again the explanations given in the exercise. It already explains what how the algorithm works. However, if you still have problems with it, then take a piece of paper, and some very simple example arrays and go through the solution step by step.
For example, let
A = [6, 6, 1, 2, 3] and
B = [1, 5, 3, 2, 1].
Now let's go through the algorithm.
I assume you understand how this method works:
def counting(A, m): n = len(A) count = [0] * (m + 1) for k in xrange(n): count[A[k]] += 1 return count
It just returns a list with counts as explained in the exercise. For list A and m = 10 it will return:
[0, 1, 1, 1, 0, 0, 2, 0, 0, 0, 0]
Then we go through the main method
fast_solution(A, B, m):
n = 11 (this will be used in the loop)
The sum of A equals
18 and the sum of B equals
12.
The difference
d is
-6 (sum_b - sum_a), it is even. Note that if difference is odd, then no swap is available and the result is False.
Then
d is divided by
2. It becomes
-3.
For A we get count
[0, 1, 1, 1, 0, 0, 2, 0, 0, 0, 0] (as already mentioned before).
Then we just iterate though the list B using
xrange and check the conditions (The loop goes from 0 and up to but not including 11). Let's check it step by step:
i = 0,
B[0] - (-3) is
1 + 3 = 4. 4 is greater than or equal to 0 and less than or equal to 10 (remember, we have chosen
m to be
10). However,
count[4] is 0 and it's not greater than 0 (Note the list
count starts from index
0). The condition fails, we go further.
i = 1,
B[1] - (-3) is
5 + 3 = 8. 8 is greater than or equal to 0 and less than or equal to 10. However,
count[8] is 0 and the condition fails.
i = 2,
B[2] - (-3) is
3 + 3 = 6. 6 is greater than 0 and less than 10. Also
count[6] is 2 and it is greater than 0. So we found the number. The loop stops, True is returned. It means that there is such a number in B which can be swapped with a number in A, so that sum of A becomes equal to the sum of B. Indeed, if we swap 6 in A with 3 in B, then their sum become equal to 15.
Hope this helps. | https://codedump.io/share/HuHSotLxDpUe/1/python-algorithm-for-swapping-elements-between-two-arrays | CC-MAIN-2017-26 | refinedweb | 656 | 79.9 |
Timeline
Mar 8, 2007:
- 4:48 PM TracNotification created by
-
- 4:48 PM TracStandalone created by
-
- 4:48 PM TracUnicode created by
-
- 4:48 PM TracLinks created by
-
- 4:48 PM TracInstall created by
-
- 4:48 PM RecentChanges created by
-
- 4:48 PM TracQuery created by
-
- 4:48 PM TracRss created by
-
- 4:48 PM TracTickets created by
-
- 4:48 PM TracEnvironment created by
-
- 4:48 PM WikiRestructuredText created by
-
- 4:48 PM TracBackup created by
-
- 4:48 PM InterTrac created by
-
- 4:48 PM TracBrowser created by
-
- 4:48 PM TracUpgrade created by
-
- 4:48 PM TracSupport created by
-
- 4:48 PM TracInterfaceCustomization created by
-
- 4:48 PM WikiStart created by
-
- 4:48 PM TracPlugins created by
-
- 4:48 PM TracFastCgi created by
-
- 4:48 PM WikiPageNames created by
-
- 4:48 PM TracChangeset created by
-
- 4:48 PM TracCgi created by
-
- 4:48 PM WikiProcessors created by
-
- 4:48 PM TracSyntaxColoring created by
-
- 4:48 PM TracLogging created by
-
- 4:48 PM SandBox created by
-
- 4:48 PM TracTicketsCustomFields created by
-
- 4:48 PM WikiRestructuredTextLinks created by
-
- 4:48 PM TracImport created by
-
- 4:48 PM TracIni created by
-
- 4:48 PM TracAccessibility created by
-
- 4:48 PM InterMapTxt created by
-
- 4:48 PM TracSearch created by
-
- 4:48 PM TitleIndex created by
-
- 4:48 PM WikiFormatting created by
-
- 4:48 PM TracWiki created by
-
- 4:48 PM TracTimeline created by
-
- 4:48 PM TracRoadmap created by
-
- 4:48 PM TracRevisionLog created by
-
- 4:48 PM WikiHtml created by
-
- 4:48 PM WikiNewPage created by
-
- 4:48 PM WikiMacros created by
-
- 4:48 PM CamelCase created by
-
- 4:48 PM TracGuide created by
-
- 4:48 PM TracPermissions created by
-
- 4:48 PM InterWiki created by
-
- 4:48 PM TracAdmin created by
-
- 4:48 PM TracModPython created by
-
- 4:48 PM TracReports created by
-
- 4:48 PM WikiDeletePage created by
-
- 4:07 PM Changeset [10903] by
-
- 3:49 PM Changeset [10902] by
- libtool support
- 3:13 PM Changeset [10901] by
- libtool build support
- 1:20 PM Changeset [10900] by
- Using the enumerated types in the sample apps.
- 1:19 PM Changeset [10899] by
- Changed the namespace names
- 1:17 PM Changeset [10898] by
- Added enums for SWIG C# Dataset ReadRaster/WriteRaster?
- 1:13 PM Changeset [10897] by
- Added enums for SWIG C# Renamed the module names Dataset …
- 8:10 AM Changeset [10896] by
- credit the Geological Survey
- 8:04 AM Changeset [10895] by
- close <b>
- 8:01 AM Changeset [10894] by
- Credit the Geological Survey for supporting the development of the …
Mar 7, 2007:
- 5:17 PM Changeset [10893] by
- don't leak colortables
- 4:49 PM Changeset [10892] by
- apply Nowak's patch for reading 1 and 4 bit data
- 1:49 PM Changeset [10891] by
- clean up some warnings. Still complains about line 416/417, but I …
- 1:42 PM Changeset [10890] by
- clean up some leaks and undo the r10886 stuff
- 1:40 PM Changeset [10889] by
- Added ers registration.
- 1:36 PM Changeset [10888] by
- Cleanup up papsztokens leak.
- 1:21 PM Changeset [10887] by
- Added Peng Gao, email for Hannah.
- 12:43 PM Changeset [10886] by
- it's amazing what msvc lets you get away with ;) Clean up the heap …
- 10:49 AM Ticket #1513 (gdal.GetLastErrorMsg() function does not functioning) created by
- […]
- 10:28 AM Changeset [10885] by
- ImportFromESRI takes a list, unlike all of the other ImportFrom?* …
- 9:10 AM Changeset [10884] by
- be less dumb with overview support :)
- 8:19 AM Ticket #1512 (osr.ImportFromESRI() method crashes on valid input) created by
- […]
- 8:09 AM Ticket #1511 (GDAL doesn't write out PROJ metadata for Krovak to GeoTIFF) created by
- […]
Mar 6, 2007:
- 10:30 PM Changeset [10883] by
- Cache the stream per-dataset rather than per-band. Attempt to cache …
- 5:37 PM Changeset [10882] by
- updated based on ArcGIS 9.2 datum definitions
- 3:47 PM Changeset [10881] by
- test commit
- 11:02 AM Changeset [10880] by
- Remove outdated credits, and references to I
- 7:15 AM Changeset [10879] by
- Link to J2000 home page replaced with link to OpenJPEG homepage.
- 6:59 AM Changeset [10878] by
- Link to modified JasPEr library updated.
- 6:58 AM Changeset [10877] by
- Link to modified JasPer library updated.
- 4:58 AM Changeset [10876] by
- Removed extra formatter from sample code in ogr_apitut.dox.
Mar 5, 2007:
- 8:32 PM Ticket #1510 (new feature: OGRDataSource::DeleteLayer() for SHP data format) created by
- […]
- 7:33 AM Ticket #1509 (GetPaletteInterpretation returning invalid data) created by
- […]
Mar 4, 2007:
- 9:34 PM Changeset [10875] by
- Configured ENABLE_SEQSCAN=ON for PostGIS >= 0.8 (Bug 1472). Changes …
- 9:26 PM Changeset [10874] by
- Increased value of CURSOR_PAGE from 1 to 500 (Bug 1474). Changes …
- 6:17 PM Changeset [10873] by
- Added Id keyword to ogr/index.dox as a last update indicator.
- 6:16 PM Changeset [10872] by
- Fixed URL to sfcdump.c file.
Mar 3, 2007:
- 11:59 PM Changeset [10871] by
- Increased value of CURSOR_PAGE from 1 to 500 (Bug 1474). Further …
- 11:50 PM Changeset [10870] by
- Removed unused CURSOR_PAGE constant from ogrpgtablelayer.cpp.
- 3:39 PM Changeset [10869] by
- Configured ENABLE_SEQSCAN=ON for PostGIS >= 0.8 (Bug 1472).
- 2:31 PM Changeset [10868] by
- Updated svn:ignore property. Testing after SVN transition.
Mar 2, 2007:
- 10:30 PM Changeset [10867] by
- Added copyright header.
- 10:27 PM Changeset [10866] by
- test commit
- 10:24 PM Changeset [10865] by
- test commit
- 10:33 AM Changeset [10864] by
- Moved nodata value handling in PNG to band level for RGB, gray and …
Mar 1, 2007:
- 4:27 PM Ticket #1508 (configure should check for Python.h before enabling Python) created by
- I have a system here on which GDAL's configure decides to enable the …
- 11:06 AM Ticket #1507 (GDALRasterIO crashes for width values higher than 2048 with LZW enabled) created by
- Env : x86 32 bits - Linux Gdal 1.3.1 with width > 2048 and LZW …
- 10:19 AM Changeset [10863] by
- Made improvements so that arrays larger than 4GB work (bug 1503)
- 10:16 AM Changeset [10862] by
- Made improvements so that arrays larger than 4GB work (bug 1503).
- 4:36 AM Changeset [10861] by
- Use correct EPSG code for the Pulkovo 42 coordinate system.
Feb 28, 2007:
- 5:39 PM Ticket #1506 (gdalinfo on a netCDF file returns incorrect coordinates) created by
- The attached netCDF file was generated using NCO (ncra -- see …
- 5:30 PM Ticket #1505 (gdal_translate misinterprets netCDF dimensions and cellsize) created by
- This issue was initially posted on the gdal-dev mailing list using …
- 4:44 PM Ticket #1504 (dstalpha outputs thin borders around edge of source image in gdalwarp) created by
- When warping an image with bilinear or cubic convolution resampling …
- 3:56 PM Ticket #1503 (MEM Driver does not support images larger than 4GB) created by
- […]
- 11:21 AM Changeset [10860] by
- Fixed small typo in MEM driver docs.
- 10:14 AM Changeset [10859] by
- Removed some extra literal from comment of CPL_SWAP64 macro.
- 6:22 AM Changeset [10858] by
- Added support for false easting/false norting and scaling factor to …
- 6:11 AM Changeset [10857] by
- Added support for scaling factor when reading projection.
- 6:10 AM Changeset [10856] by
- Added support for scaling factor in import/export functions.
Feb 27, 2007:
- 6:48 PM Changeset [10855] by
- Added GetExtent?() method to the table layer.
- 6:46 PM Changeset [10854] by
- Added GetExtent?() method to the table layer.
- 10:12 AM Changeset [10853] by
- Addition of sensor type and band number to hdf4 eos swath and grid …
- 7:51 AM Ticket #1502 (Kakadu 5.2 suggested changes) created by
- On Windows, I link against Kakadu DLLs. I set KAKDIR to an invalid …
- 5:57 AM Changeset [10852] by
- Added support for false easting/northing parameters when fetching or …
- 5:53 AM Changeset [10851] by
- Added support for false easting/northing parameters in …
Feb 26, 2007:
- 1:47 PM Ticket #1501 (JP2ECW, creation options PROJ and DATUM ineffective) created by
- When trying to assign a specific ERMapper projection/datum string to a …
- 10:35 AM Changeset [10850] by
- fixed use of non-threadsafe filename (bug 1500)
- 10:34 AM Changeset [10849] by
- fixed use of non-threadsafe filename (bug 1500)
- 9:28 AM Ticket #1500 (Thread safety broken in GTIF driver) created by
- […]
Feb 25, 2007:
- 8:41 PM Changeset [10848] by
- a note about OGR_SDE_GETLAYERTYPE
Note: See TracTimeline for information about the timeline view. | http://trac.osgeo.org/gdal/timeline?from=2007-03-25T17%3A28%3A37-0700&precision=second | CC-MAIN-2016-30 | refinedweb | 1,405 | 50.5 |
Tally Approximations of Phylogenetic Informativeness Rapidly (TAPIR)
Purpose
tapir contains programs to estimate and plot phylogenetic informativeness for large datasets.
Citing tapir.
Dependencies
Installation
For ALL platforms, you must download a hyphy binary for your platform (osx or linux) and place that within your $PATH:
wget gunzip hyphy2.*.gz chmod 0700 hyphy2.* mv hyphy2.* ~/Bin/hyphy2
To install the other dependencies (numpy, scipy), you may need to install a Fortran compiler on linux/osx:
Linux
On linux (ubuntu/debian), use:
apt-get install gfortran libatlas-base-dev liblapack-dev
Install tapir and dependencies, which include numpy and scipy (the reason we installed the dependencies above):
pip install tapir
To plot results, you will also need to:
apt-get install r-base r-base-dev pip install rpy2
OSX
It is easiest just to install the scipy superpack. This will install the dependencies that tapir needs. After installing the superpack, using pip, install tapir:
pip install tapir
Alternatively, you can simply try to install tapir using:
pip install tapir
To plot results, you need to install R and then install rpy2:
pip install rpy2
Other OSs
Install numpy, scipy, and dendropy for your platform. Then:
wget tar -xzvf tapir-1.0.tar.gz cd tapir* python setup.py build python setup.py test python setup.py install
Plotting
Plotting is optional. To install the plotting dependencies, see Installation, above.
Testing
If you didn’t run the tests using python setup.py test above, you can also:
import tapir tapir.test()
Use
The estimate_p_i.py code calls a batch file for hyphy that is in templates/. This file needs to be in the same position relative to wherever you put estimate_p_i.py. If you install thins as above, you’ll be fine, for the moment.
To run:
cd /path/to/tapir/ python tapir_compute.py Input_Folder_of_Nexus_Files/ Input.tree \ --output Output_Directory \ --epochs=32-42,88-98,95-105,164-174 \ --times=37,93,100,170 \ --multiprocessing
–multiprocessing is optional, without it, each locus will be run consecutively.
If you have already run the above and saved results to your output folder (see below), you can use the pre-existing site-rate records rather than estimating those again with:
python tapir_compute.py Input_Folder_of_Site_Rate_JSON_Files/ Input.tree \ --output Output_Directory \ --epochs=32-42,88-98,95-105,164-174 \ --times=37,93,100,170 \ --multiprocessing \ --site-rates
Results
tapir writes results to a sqlite database in the output directory of your choosing. This directory also holds site rate files in JSON format for each locus passed through tapir_compute.py.
You can access the results in the database as follows. For more examples, including plotting, see the documentation
crank up sqlite:
sqlite3 Output_Directory/phylogenetic-informativeness.sqlite
get integral data for all epochs:
select locus, interval, pi from loci, interval where loci.id = interval.id
get integral data for a specific epoch:
select locus, interval, pi from loci, interval where interval = '95-105' and loci.id = interval.id;
get the count of loci having max(PI) at different epochs:
create temporary table max as select id, max(pi) as max from interval group by id; create temporary table t as select interval.id, interval, max from interval, max where interval.pi = max.max; select interval, count(*) from t group by interval;
Plotting Results
tapir contains plotting scripts to help you plot data within a results database and compare data between different databases. tapir uses RPY and R to do this. You can also plot data directly in R. Until we finish the documentation, please see the wiki for examples.
Acknowledgements
BCF thanks SP Hubbell, PA Gowaty, RT Brumfield, TC Glenn, NG Crawford, JE McCormack, and M Reasel. JHLC and MEA thank J Eastman and J Brown for thoughtful comments about PI. We thank Francesc Lopez-Giraldez and Jeffrey Townsend for providing us with a copy of their web-application source code and helpful discussion.
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/tapir/ | CC-MAIN-2017-51 | refinedweb | 665 | 56.45 |
Write a program that accepts temperatures from the user, and also whether the temperature is in Fahrenheit,
Celsius or Kelvin (use the following screen shots as a guide). Keep track of the total temperature in Kelvin
and report the total after each user entry as shown below. When the user decides to stop entering information,
display the message "Goodbye!" as shown. You will need to know the following conversions:
[K] = ([F] + 459.67) 5D 9 [K] = [C] + 273.15.
I cannot figure this out for the life of me. Please help me with the code, not just a tip on what the function or whatever is called to fix it, I am very lost. Thanks.
#include <iostream> #include <string> using namespace std; int main() { double temperature; int m,cont; int counter=0,temp,measurement; do { counter=counter+temperature; if (temperature="") cout<<"Please enter a temperature: "; cin>>temperature; if (m="") cout<<"(F)ahrenheit, (C)elsius, or (K)elvin? "; cin>>m; cout<<"Your current total temperature is "<<temperature<< "degrees Kelvin."<<endl; if (cont="") cout<<"Do you want to continue (Y/N)?"; getline(cin, cont); if ((temp=='F')||(temp=='C')||(temp=='K')) m=temp; else cout<<"Please enter a temperature: "; }while ((cont!='n')||(cont!='N'); cout<<"Goodbye!"; switch(measurement) { case 'F': case 'f': temperature=(temperature+459.67)*(5/9); break; case 'C': case 'c': temperature=temperature+273.15; break; case 'K': case 'k': temperature=temperature; } } | http://www.dreamincode.net/forums/topic/102485-do-while-loop-and-switch-case/ | CC-MAIN-2016-40 | refinedweb | 232 | 57.67 |
Many organizations use separate development, staging, and production environments to maintain the quality of their websites. Here’s how the environments look when ArcGIS Server is involved:
- Development—This is a sandbox ArcGIS Server site where you can freely test your applications and services. Typically, the development site runs on a small machine using an Esri Developer Network (EDN) license for ArcGIS Server. Once changes are validated on the development site, they are applied to the staging site.
- Staging—This ArcGIS Server site is a clone of the production site. Testing at this level results in a decision to apply the changes on the production site, or reject the changes and wait for a new iteration from the development site. The staging site is not used for development, just performance and functional testing. Esri provides staging licenses for ArcGIS Server users at a lower cost than production licenses.
- Production—This is the site that actually supports business workflows, the site accessed by real users. Absolutely no development or testing occurs on this site. Only changes that have passed the scrutiny of testing on the staging site are applied to the production site.
The development, staging, and production environments ideally use different databases and infrastructures. Each organization has its own rules for how changes are tested and approved across the sites.
Moving a change from site to site can present logistical challenges. This help topic provides patterns and scripts to guide you through the process.
Configuring each environment
In each environment, install ArcGIS Server, create a site, and configure security, server object extensions (SOEs), and other settings. Most of these tasks are faster if performed manually although you can use a script like Example: Create users and roles from two text files.
Get your development site working first and create the staging site, followed by the production site.
Deploying services
The key to deploying services in multiple environments is to register your folders and databases correctly with ArcGIS Server and use service definitions (SDs) for publishing.
Registering folders and databases with ArcGIS Server
When you register a folder or database with ArcGIS Server, you provide the publisher’s path to the data and the server’s path.
- The publisher’s path is the data path on the machine you’ll use to make the SD files. The publisher’s path is always the same when you register an item on the development, staging, and production servers.
- The server’s path is the data path on the server. This path can vary when you register an item on the development, staging, and production servers.
If you have many data folders or databases to register, you may consider using scripts. Example: Register folders and databases listed in a text file uses the ArcPy AddDataStoreItem function to register a list of folders and database connections supplied in a text file. You modify the text file for each environment.
Publishing services
Use SD files when deploying your services in multiple environments. The SD takes the information needed to publish a service and packages it into one convenient file. Although it’s possible to package the GIS data within the SD, you’ll probably find it easier to preload the data in each environment and use replication to keep it in sync.
Create connection-neutral SD files (choose the No available connection option in the Save a Service Definition wizard) so they are flexible enough to be published on any server. When you publish an SD file, ArcGIS Server automatically corrects the paths written in the SD so that your server paths are used. Careful data registration allows you to deploy the same SD file in multiple environments.
Publishing services is a task well-suited for scripting. Example: Publish service definitions listed in a text file reads a text file and publishes all SDs listed. The script uses the ArcPy function Upload Service Definition to publish each SD.
After deploying your services from the SDs, enable any extensions required by the services. This can be done manually or through scripting.
Applying permissions is another task that can be scripted. Example: Apply permissions from a text file uses the ArcGIS REST API to apply permissions to various services as listed in a text file.
Updating services
Sometimes you might want to update a service to use new properties or reflect changes in the source document, such as a set of permanent symbology edits in an ArcMap document (MXD). The recommended way to update a service in multiple environments is to save a new SD file, delete the service, then publish the updated SD.
When you take this approach, the same example script used above for publishing can also perform service updates. Just modify the input file to include only the services you want to update. If an existing service is found, the script deletes it before uploading the SD.
After you update a service in this way, reenable any SOEs used by the service.
You can alternatively script updates to service properties (but not the map or source document) using the Edit Service operation in the ArcGIS REST API.
Keeping data in sync
Ensure your data is kept in sync across your multiple environments. Geodatabase replication can help you with this. Alternatively, you can completely replace the old dataset with a new dataset. For example, you might delete a file geodatabase and replace it with an updated file geodatabase.
If you decide to entirely replace tables or file geodatabases, remember that ArcGIS Server services lock the schemas of the underlying datasets by default. If the schema is locked, stop your service before you can replace the data. With some degree of caution you can disable schema locking for map services, but you can’t disable it for other service types.
Updating applications
To move an application between the development, staging, and production environments, copy the application files from one site to the other and update any web service URLs in your code so they point at the new site. Use configuration files to define the URLs for your services.
The script below helps you update the URLs in your code. The code recursively looks for files within a folder you provide, searches for a particular string such as, and replaces it with the location of your staging or production site, such as.
Before you start this script, make a backup copy of the original application files. Also note that the script allows you to specify the extension of the text files you want to process, for example, .js and .html for your ArcGIS API for JavaScript files.
Once you’ve replaced the URLs using the script, copy the application files onto the next server in the workflow (staging or production).
import os import sys import shutil import traceback def dirEntries(dir_name, subdir, *args): '''Return a list of file names found in directory 'dir_name' If 'subdir' is True, recursively access subdirectories under 'dir_name'. Additional arguments, if any, are file extensions to match filenames. Matched file names are added to the list. If there are no additional arguments, all files found in the directory are added to the list. Example usage: fileList = dirEntries(r'H:\TEMP', False, 'txt', 'py') Only files with 'txt' and 'py' extensions will be added to the list. Example usage: fileList = dirEntries(r'H:\TEMP', True) All files and all the files in subdirectories under H:\TEMP will be added to the list. ''' fileList = [] for file in os.listdir(dir_name): dirfile = os.path.join(dir_name, file) if os.path.isfile(dirfile): if not args: fileList.append(dirfile) else: if os.path.splitext(dirfile)[1][1:] in args: fileList.append(dirfile) # recursively access file names in subdirectories elif os.path.isdir(dirfile) and subdir: print "Accessing directory:", dirfile fileList.extend(dirEntries(dirfile, subdir, *args)) return fileList def updateString(infileName, srchString,rplString): bakFileName = os.path.splitext(infileName)[0] + ".bak" if not os.path.exists(bakFileName): # copy the original file shutil.copy(infileName, bakFileName) # Open the backup (= original) file to read inFileHndl = open(bakFileName,"r") outFileHndl = open(infileName,"w") for line in inFileHndl: if line.find(searchString) > 0: line = line.replace(searchString, replaceString) outFileHndl.write(line) outFileHndl.close() inFileHndl.close() # remove the backup (=original content file) os.remove(bakFileName) if __name__ == '__main__': try: inFolder = r"C:\inetpub\wwwroot\viewer" # path to search searchString = "" # string to find replaceString = "" # string - replace searchString with replaceString fList = dirEntries(inFolder, True, 'xml') for f in fList: updateString(f, searchString, replaceString) print '\n\n\n' + 'Process Complete' except: # Return any python specific errors as well as any errors from the geoprocessor # tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n " + \ str(sys.exc_type)+ ": " + str(sys.exc_value) + "\n" print '\n\n\n' + pymsg | https://enterprise.arcgis.com/en/server/10.5/administer/windows/arcgis-server-in-development-staging-and-production-environments.htm | CC-MAIN-2022-33 | refinedweb | 1,458 | 55.54 |
securecookie alternatives and similar packages
Based on the "Authentication and OAuth" category.
Alternatively, view securecookie alternatives based on common mentions on social networks and blogs.
scs7.7 7.9 securecookie VS scsHTTP Session Management for Go
paseto6.8 0.0 securecookie VS pasetoPlatform-Agnostic Security Tokens implementation in GO (Golang)
go-guardian6.2 3.3 securecookie VS go-guardianGo-Guardian is a golang library that provides a simple, clean, and idiomatic way to create powerful modern API and web authentication.
jeff5.4 1.0 securecookie VS jeff🍍Jeff provides the simplest way to manage web sessions in Go.
branca5.1 0.0 securecookie VS branca:key: Secure alternative to JWT. Authenticated Encrypted API Tokens for Go.
sessionup4.5 1.5 securecookie VS sessionupStraightforward HTTP session management
otpgen4.4 1.8 securecookie VS otpgenLibrary to generate TOTP/HOTP codes
sjwt4.1 0.0 securecookie VS sjwtSimple JWT Golang
go-email-normalizerGolang library for providing a canonical representation of email address.
otpgo2.4 0.0 securecookie VS otpgoTime-Based One-Time Password (TOTP) and HMAC-Based One-Time Password (HOTP) library for Go.
scope2.1 0.0 securecookie VS scopeEasily Manage OAuth2 Scopes In Go
cookiestxt1.6 0.0 securecookie VS cookiestxtcookiestxt implement parser of cookies txt format
sessiongate-go1.5 0.0 securecookie VS sessiongate-goA driver for the SessionGate Redis module - easy session management using the Go language.
signedvalue1.2 0.0 securecookie VS signedvalueCompatibility layer for tornado's signed values (and secure cookies consequently)
Less time debugging, more time building
Do you think we are missing an alternative of securecookie or a related project?
README
Encode and Decode secure cookies
This package provides functions to encode and decode secure cookie values.
A secure cookie has its value ciphered and signed with a message authentication code. This prevents the remote cookie owner from knowing what information is stored in the cookie or modifying it. It also prevents an attacker from forging a fake cookie.
This package differs from the Gorilla secure cookie in that its encoding and decoding is 3 times faster and needs no heap allocation with an equivalent security strength. Both use AES128 and SHA256 to secure the value.
Note: This package uses its own secure cookie value encoding. It is thus incompatible with the Gorilla secure cookie package and the ones provided with other language frameworks. This encoding is simpler and more efficient, and adds a version number to support evolution with backwards compatibility.
Warning: Because this package impacts security of web applications, it is a critical functionality. Review feedbacks are always welcome.
Content
Installation
To install or update this secure cookie package use the instruction:
go get -u "github.com/chmike/securecookie"
Usage examples
To use this cookie package in your server, add the following import.
import "github.com/chmike/securecookie"
Generating a random key
It is strongly recommended to generate the random key with the following function.
Save the key in a file using
hex.EncodeToString() and restrict access to that file.
var key []byte = securecookie.MustGenerateRandomKey()
To mitigate the risk of an attacker getting the saved key, you might store a second key in another place and use the xor of both keys as secure cookie key. The attacker will have to get both keys to reconstruct the effective key which should be more difficult.
Instantiating a cookie object
A secure cookie is instantiated with the
New function. It returns an error if an
argument is invalid.
obj, err := securecookie.New( }) if err != nil { // ... }
It is also possible to instantiate a secure cookie object without returning an
error and panic if an argument is invalid. To do this, use
securecookie.MustNew(). In the following example,
session is the cookie name
and the Path is
/sec. A secured value may be stored in the remote browser by
calling the
SetValue() method. After that, every subsequent request from that
browser with a URL starting with
/sec will have the cookie sent along. Calling
the method
GetValue() will extract the secure value from the request. A
request to delete the cookie may be sent to the remote browser by calling the
method
Delete().
var obj = securecookie.MustNew( }
Remember that the key should not be stored in the source code or in a repository.
Adding a secure cookie to a server response
var val = []byte("some value") // with w as the if err := obj.SetValue(w, val); err != nil { // ... }
Decoding a secure cookie value
The value is appended to the given buffer. If buf is
nil a new buffer
(
[]byte) is allocated. If buf is too small it is grown.
// with r as the * val, err := obj.GetValue(buf, r) if err != nil { // ... }
The returned value is of type []byte.
Deleting a cookie
// with w as the if err := obj.Delete(w); err != nil { // ... }
Note: don't rely on the assumption that the remote user agent (browser) will effectively delete the cookie. Evil users will try anything to break your site.
Complete example
An complete example is provided [here](example/main.go).
Follow these steps to test the example:
- create a directory in /tmp and set it as the working directory: "mkdir /tmp/sctest; cd /tmp/sctest"
- create a file named
main.goand copy the example code referenced above into it
- create a go.mod file: "go mod init example.com"
- get the latest version of the securecookie packaqe: "go get github.com/chmike/[email protected]"
- run the server: "go run main.go"
- with your browser, request " to set the secure cookie value
- with your browser, request " to retriev the secure cookie value
Benchmarking
Encoding the cookie named "test" with value "some value". See benchmark functions are at the bottom of cookie_test.go file. The ns/op values were obtained by running the benchmark 10 times and taking the minimal value. These values were obtained with go1.14 (27-Feb-2020) on an Ubuntu OS with an i5-7400 3GHz processor.
The secure cookie value encoding and decoding functions of this package need 0 heap allocations.
The benchmarks were obtained with release v0.4. Subsequent release may alter the benchmark results.
Qualitative comparison
The latest version was updated to put the security in line with the Gorilla secure cookie.
- We both use CTR-AES-128 encryption with a 16 byte nonce, and HMAC-SHA-256.
- We both encrypt first then compute the MAC over the cipher text.
- A time stamp is added to the encoded value.
- The hmac is computed over the cookie value name, the ciphered time stamp and value.
- Both packages don't take special measures to secure the secret key.
- Both packages don't effectively conceal the value byte length.
The differences between the Gorilla secure cookie and this implementation are:
- This code is more efficient, and there is still room for improvement.
- This secure value encoding is more compact without weakening the security.
- This secure cookie encoding is incompatible with other secure cookie encoding. I don't know the status of Gorilla's encoding.
- This encoding adds an encoding version number allowing to change or add new encoding without breaking backwards compatibility. Gorilla doesn't have this.
- This package provides a Delete cookie method.
This package and Gorilla both provide equivalently secure cookies if we discard the fact that no special measure is taken to conceal the key in memory and the value length. This package is quite new and needs more reviews to validate the security of the implementation.
Feedback and contributions are welcome.
Value encoding
A clear text message is first assembled as follow:
[tag][nonce][stamp][value][padding]
- The tag is 1 byte. The 6 most significant bits encode the version number of the encoding (currently 0). The 2 less significant bits encode the number of padding bytes (0, 1 or 2). 3 is an invalid padding length. The number is picked so that the total length including the MAC is a multiple of 3. This simplifies base64 encoding by avoiding its padding.
- The nonce is 16 bytes long (AES block length) and contains cryptographically secure pseudorandom bytes.
- The stamp is the unix time subtracted by an epochOffset value (1505230500), and encoded using the LEB128 encoding.
- The value is a copy of the user provided value to secure.
- The padding bytes are cryptographically secure pseudorandom bytes. There may be 0 to 2 padding bytes. The number is picked so that the total length including the MAC is a multiple of 3. This simplifies base64 encoding by avoiding its padding.
The stamp, value and padding bytes are ciphered using CTR-AES with the 16 last bytes of the key as ciphering key. The nonce is used as iv and counter initialization value. The tag and nonce are left unciphered.
An HMAC-SHA-256 is computed over (1) the cookie name and (2) the bytes sequence obtained after step 2. The 32 byte long MAC is appended after the padding.
The whole byte sequence, from the tag to the last byte of the MAC is encoded in Base64 using the URL encoding. There is no padding since the byte length is a multiple of 3 bytes.
The tag which provides an encoding version allows completely changing the encoding while preserving backwards compatibility if required.
Contributors
- lstokeworth (reddit):
- suggest to replace
copywith
append,
- remove the Expires Params field and use only the MaxAge,
- provide a constant date in the past for Delete.
- cstockton (github):
- critical bug report,
- suggest simpler API.
- flowonyx (github):
- fix many typos in the README and comments.
Usage advise
It is very important to understand that the security is limited to the cookie content. Nothing proves that the other data received by the server with a secure cookie has been created by the user's request.
When you have properly set the domain path, and HTTPOnly with the Secure flag, and use HTTPS, only the user's browser can send the cookie. But it is still possible for an attacker to trick your browser to send a request to the site without the user's knowledge and consent. This is known as a CSRF attack.
Consider this scenario with a Pizza ordering web site. First let's see what happens when everything goes as expected.
The user has to login to the site to be allowed to order pizzas. During the login transaction a secure cookie is added into the user's browser. The user is then shown a form with the number of pizzas to order. When the user clicks the Order button, his browser will make a request to an URL provided with the form. It will join the field values and the secure cookie since the URL path and domain match the one specified at the login transaction.
When the server receives this request, it checks the cookie validity to determine who that client is and if he is legitimate. All is fine. The order is then forwarded to the pizza chef. The pizza is later delivered to the user.
Now comes the villain. He sets up some random site with a form and a validation button that the victim will very likely click (e.g., "Subscribe to spam" with a Please no button as validation button). The villain has set up the form so that the URL associated to the validation button is the URL to order pizzas. He will have added a hidden field with the number of pizzas to order set to 10!
When the user clicks that validation button, his browser will send a request to the pizza ordering site with the field value and the secure cookie since the URL matches the cookie path and domain.
The pizza ordering site checks the secure cookie and it will be authenticated. It will assume that the user issued that order. When the delivery man rings at the user's door with 10 pizzas in his hand, there will be a conflict and no way to know to know who's fault it is. Notice how the value 10 associated with the cookie in the ordering request was not signed by the user's browser.
To avoid this, the solution is to add a way to authenticate the form response. This is done by adding a hidden field in the form with a random byte sequence, and set a secure cookie with that byte sequence as value and a validity date limit. When the user fills that form, the server will receive back the secure cookie and the hidden field value. The server then checks that they match to validate the response.
An attacker can forge a random byte sequence, but can't forge the secure cookie that goes with it.
Note that this protection is void in case of XSS attack (script injection).
The above method works with forms, not with REST API like requests because the server can't send the random token to the client that can be used as a challenge. For REST API like authenticated transactions, the client and server have to both know a secret byte sequence they use to compute a hmac value over the URI, the method, the data and a message sequence number. They can then authenticate the message and the source.
The secret byte sequence can be determined in the authentication transaction with public and private keys. There is no need for TLS to securely authenticate the client and server. A secret cookie is no help here. | https://go.libhunt.com/securecookie-alternatives | CC-MAIN-2022-21 | refinedweb | 2,231 | 57.27 |
Note: MySQL currently does not support user-defined types. MySQL and Java DB currently do not support structured types, or the
DISTINCT SQL data type. No JDBC tutorial example is available to demonstrate the features described in this section.
With business booming, the owner of The Coffee Break is regularly adding new stores and making changes to the database. The owner has decided to use a custom mapping for the structured type
ADDRESS. This enables the owner to make changes to the Java class that maps the
ADDRESS type. The Java class will have a field for each attribute of
ADDRESS. The name of the class and the names of its fields can be any valid Java identifier.
The following topics are covered:
The first thing required for a custom mapping is to create a class that implements the interface
SQLData.
The SQL definition of the structured type
ADDRESS looks like this:
CREATE TYPE ADDRESS ( NUM INTEGER, STREET VARCHAR(40), CITY VARCHAR(40), STATE CHAR(2), ZIP CHAR(5) );
A class that implements the
SQLData interface for the custom mapping of the
ADDRESS type might look like this:
public class Address implements SQLData { public int num; public String street; public String city; public String state; public String zip; private String sql_type; public String getSQLTypeName() { return sql_type; } public void readSQL(SQLInput stream, String type) throws SQLException { sql_type = type; num = stream.readInt(); street = stream.readString(); city = stream.readString(); state = stream.readString(); zip = stream.readString(); } public void writeSQL(SQLOutput stream) throws SQLException { stream.writeInt(num); stream.writeString(street); stream.writeString(city); stream.writeString(state); stream.writeString(zip); } }
After writing a class that implements the interface
SQLData, the only other thing you have to do to set up a custom mapping is to make an entry in a type map. For the example, this means entering the fully qualified SQL name for the
ADDRESS type and the
Class object for the class
Address. A type map, an instance of the
java.util.Map interface, is associated with every new connection when it is created, so you use that one. Assuming that
con is the active connection, the following code fragment adds an entry for the UDT
ADDRESS to the type map associated with
con.
java.util.Map map = con.getTypeMap(); map.put("SchemaName.ADDRESS", Class.forName("Address")); con.setTypeMap(map);
Whenever you call the
getObject method to retrieve an instance of the
ADDRESS type, the driver will check the type map associated with the connection and see that it has an entry for
ADDRESS. The driver will note the
Class object for the
Address class, create an instance of it, and do many other things in the background to map
ADDRESS to
Address. You do not have to do anything more than generate the class for the mapping and then make an entry in a type map to let the driver know that there is a custom mapping. The driver will do all the rest.
The situation is similar for storing a structured type that has a custom mapping. When you call the method
setObject, the driver will check to see if the value to be set is an instance of a class that implements the interface
SQLData. If it is (meaning that there is a custom mapping), the driver will use the custom mapping to convert the value to its SQL counterpart before returning it to the database. Again, the driver does the custom mapping behind the scenes; all you need to do is supply the method
setObject with a parameter that has a custom mapping. You will see an example of this later in this section.
Look at the difference between working with the standard mapping, a
Struct object, and the custom mapping, a class in the Java programming language. The following code fragment shows the standard mapping to a
Struct object, which is the mapping the driver uses when there is no entry in the connection's type map.
ResultSet rs = stmt.executeQuery( "SELECT LOCATION " + "WHERE STORE_NO = 100003"); rs.next(); Struct address = (Struct)rs.getObject("LOCATION");
The variable
address contains the following attribute values:
4344,
"First_Street",
"Verona",
"CA",
"94545".
The following code fragment shows what happens when there is an entry for the structured type
ADDRESS in the connection's type map. Remember that the column
LOCATION stores values of type
ADDRESS.
ResultSet rs = stmt.executeQuery( "SELECT LOCATION " + "WHERE STORE_NO = 100003"); rs.next(); Address store_3 = (Address)rs.getObject("LOCATION");
The variable
store_3 is now an instance of the class
Address, with each attribute value being the current value of one of the fields of
Address. Note that you must remember to convert the object retrieved by the
getObject method to an
Address object before assigning it to
store_3. Note also that
store_3 must be an
Address object.
Compare working with the
Struct object to working with the instance of the
Address class. Suppose the store moved to a better location in the neighboring town and therefore you must update the database. With the custom mapping, reset the fields of
store_3, as in the following code fragment:
ResultSet rs = stmt.executeQuery( "SELECT LOCATION " + "WHERE STORE_NO = 100003"); rs.next(); Address store_3 = (Address)rs.getObject("LOCATION"); store_3.num = 1800; store_3.street = "Artsy_Alley"; store_3.city = "Arden"; store_3.state = "CA"; store_3.zip = "94546"; PreparedStatement pstmt = con.prepareStatement( "UPDATE STORES " + "SET LOCATION = ? " + "WHERE STORE_NO = 100003"); pstmt.setObject(1, store_3); pstmt.executeUpdate();
Values in the column
LOCATION are instances of the
ADDRESS type. The driver checks the connection's type map and sees that there is an entry linking
ADDRESS with the class
Address and consequently uses the custom mapping indicated in
Address. When the code calls the method
setObject with the variable
store_3 as the second parameter, the driver checks and sees that
store_3 represents an instance of the class
Address, which implements the interface
SQLData for the structured type
ADDRESS, and again automatically uses the custom mapping.
Without a custom mapping for
ADDRESS, the update would look more like this:
PreparedStatement pstmt = con.prepareStatement( "UPDATE STORES " + "SET LOCATION.NUM = 1800, " + "LOCATION.STREET = 'Artsy_Alley', " + "LOCATION.CITY = 'Arden', " + "LOCATION.STATE = 'CA', " + "LOCATION.ZIP = '94546' " + "WHERE STORE_NO = 100003"); pstmt.executeUpdate;
Up to this point, you have used only the type map associated with a connection for custom mapping. Ordinarily, that is the only type map most programmers will use. However, it is also possible to create a type map and pass it to certain methods so that the driver will use that type map instead of the one associated with the connection. This allows two different mappings for the same user-defined type (UDT). In fact, it is possible to have multiple custom mappings for the same UDT, just as long as each mapping is set up with a class implementing the
SQLData interface and an entry in a type map. If you do not pass a type map to a method that can accept one, the driver will by default use the type map associated with the connection.
There are very few situations that call for using a type map other than the one associated with a connection. It could be necessary to supply a method with a type map if, for instance, several programmers working on a JDBC application brought their components together and were using the same connection. If two or more programmers had created their own custom mappings for the same SQL UDT, each would need to supply his or her own type map, thus overriding the connection's type map. | http://docs.oracle.com/javase/tutorial/jdbc/basics/sqlcustommapping.html | CC-MAIN-2014-23 | refinedweb | 1,246 | 64.2 |
Hi, Hope you will be fine and good. Following is a snippet of python code i am using for a regression testing. def StartProc(dir, parm): global proc proc_log = open(dir + os.sep + "MyLog.txt","w") #new path for each file if parm: proc = subprocess.Popen(path, 0, None, subprocess.PIPE, proc_log, None) else: MyReset(proc) #reset the process(proc) to its default values proc.stdout = proc_log #no effect print "fptr ", proc.stdout #endif #enddef prm = True for i in range(0, 5): StartProc(i, prm) prm = False #endfor What I want to do is to start an executable only once, but on each iteration I want to redirect the process output to a different file. What is happening, is that files are created in the different path, but output is redirected to the file that is created first time. Note: MyReset() initializes the process (executable) to its default values after the first iteration. Will the following line change the process stdout to new file? proc.stdout = proc_log If no, than can you kindly guide me to the right way * Note: In the StartProc() if i create a new process everytime **StartProc**() is called. Output is correctly redirected to proper file.* Waiting for you kind reply. Warm Regards, -------------- next part -------------- An HTML attachment was scrubbed... URL: <> | https://mail.python.org/pipermail/tutor/2010-February/074274.html | CC-MAIN-2016-40 | refinedweb | 216 | 74.79 |
This tutorial is the final of a three-part series by Brad Westfall. We'll learn how to manage state across an entire application efficiently and in a way that can scale without dangerous complexity. We've come so far in our React journey, it's worth making it across the finish line here and getting the full bang-for-our-buck out of this development approach.
Article Series:
- React Router
- Container Components
- Redux (You are here!)
Redux is a tool for managing both data-state and UI-state in JavaScript applications. It's ideal for Single Page Applications (SPAs) where managing state over time can be complex. It's also framework-agnostic, so while it was written with React in mind, it can even be used with Angular or a jQuery application.
Plus, it was conceived from an experiment with "time travel" — true fact, we'll get to that later!
As seen in our previous tutorial, React "flows" data through components. More specifically, this is called "unidirectional data flow" — data flows in one direction from parent to child. With this characteristic, it's not obvious how two non parent-child components would communicate in React:
React doesn't recommend direct component-to-component communication this way. Even if it did have features to support this approach, it's considered poor practice by many because direct component-to-component communication is error prone and leads to spaghetti code — an old term for code that is hard to follow.
React does offer a suggestion, but they expect you to implement it on your own. Here's a section from the React docs:
For communication between two components that don't have a parent-child relationship, you can set up your own global event system. ... Flux pattern is one of the possible ways to arrange this.
This is where Redux comes in handy. Redux offers a solution between each other, but rather all state changes must go through the single source of truth, the store.
This is much different from other strategies where parts of the application communicate directly between each other. Sometimes, those strategies are argued to be error prone and confusing to reason about:
With Redux, it's clear that all components get their state from the store. It's also clear where components should send their state changes — also the store. The component initiating the change is only concerned with dispatching the change to the store and doesn't have to worry about a list of other components that need the state change. This is how Redux makes data flow easier to reason about.
The general concept of using store(s) to coordinate application state is a pattern known as the Flux pattern. It's a design pattern that compliments unidirectional data flow architectures like React. Redux resembles Flux, but how close are they?
Redux is "Flux-like"
Flux is a pattern, not a tool like Redux, so it's not something you can download. Redux though, is a tool which was inspired by the Flux pattern, among other things like Elm. There are plenty of guides out there that compare Redux to Flux. Most of them will conclude that Redux is Flux or is Flux-like, depending on how strict one defines the rules of Flux. Ultimately, it doesn't really matter. Facebook likes and supports Redux so much that they hired it's primary developer, Dan Abramov.
This article assumes you're not familiar with the Flux pattern at all. But if you are, you will notice some small differences, especially considering Redux's three guiding principals:
1. Single Source of Truth
Redux uses only one store for all its application state. Since all state resides in one place, Redux calls this the single source of truth.
The data structure of the store is ultimately up to you, but it's typically a deeply nested object for a real application.
This one-store approach of Redux is one of the primary differences between it and Flux's multiple store approach.
2. State is Read-Only
According to Redux docs, "The only way to mutate the state is to emit an action, an object describing what happened."
This means the application cannot modify the state directly. Instead, "actions" are dispatched to express an intent to change the state in the store.
The store object itself has a very small API with only four methods:
store.dispatch(action)
store.subscribe(listener)
store.getState()
replaceReducer(nextReducer)
So as you can see, there's no method for setting state. Therefore, dispatching an action is the only way for the application code to express a state change:
var action = { type: 'ADD_USER', user: {name: 'Dan'} }; // Assuming a store object has been created already store.dispatch(action);
The
dispatch() method sends an object to Redux, known as an action. The action can be described as a "payload" that carries a
type and all other data that could be used to update the state — a user in this case. Keep in mind that after the
type property, the design of an action object is up to you.
3. Changes are made with Pure Functions
As just described, Redux doesn't allow the application to make direct changes to the state. Instead, the dispatched action "describes" the state change and an intent to change state. Reducers are functions that you write which handle dispatched actions and can actually change the state.
A reducer takes in current state as an argument and can only modify the state by returning new state:
// Reducer Function var someReducer = function(state, action) { ... return state; }
Reducers should be written as "pure" functions, a term that describes a function with the following characteristics:
- It does not make outside network or database calls.
- Its return value depends solely on the values of its parameters.
- Its arguments should be considered "immutable", meaning they should not be changed.
- Calling a pure function with the same set of arguments will always return the same value.
These are called "pure" because they do nothing but return a value based on their parameters. They have no side effects into any other part of the system.
Our first Redux Store
To start, create a store with
Redux.createStore() and pass all reducers in as arguments. Let's look at a small example with only one reducer:
// Note that using .push() in this way isn't the // best approach. It's just the easiest to show // for this example. We'll explain why in the next section. // The Reducer Function var userReducer = function(state, action) { if (state === undefined) { state = []; } if (action.type === 'ADD_USER') { state.push(action.user); } return state; } // Create a store by passing in the reducer var store = Redux.createStore(userReducer); // Dispatch our first action to express an intent to change the state store.dispatch({ type: 'ADD_USER', user: {name: 'Dan'} });
Here's a brief summary of what's happening:
- The store is created with one reducer.
- The reducer establishes that the initial state of the application is an empty array. *
- A dispatch is made with a new user in the action itself
- The reducer adds the new user to the state and returns it, which updates the store.
* The reducer is actually called twice in the example — once when the store is created and then again after the dispatch.
When the store is created, Redux immediately calls the reducers and uses their return values as initial state. This first call to the reducer sends
undefined for the state. The reducer code anticipates this and returns an empty array to start the initial state of the store.
Reducers are also called each time actions are dispatched. Since the returned state from a reducer will become our new state in the store, Redux always expects reducers to return state.
In the example, the second call to our reducer comes after the dispatch. Remember, a dispatched action describes an intent to change state, and often times carries the data for the new state. This time, Redux passes the current state (still an empty array) along with the action object to the reducer. The action object, now with a type property of
'ADD_USER', allows the reducer to know how to change the state.
It's easy to think of reducers as funnels that allow state to pass through them. This is because reducers always receive and return state to update the store:
Based on the example, our store will now be an array with one user object:
store.getState(); // => [{name: 'Dan'}]
Don't Mutate State, Copy It
While the reducer in our example technically works, it mutates state which is poor practice. Even though reducers are responsible for changing state, they should never mutate the "current state" argument directly. This is why we shouldn't use
.push(), a mutation method, on the state argument of the reducer.
Arguments passed to the reducer should be considered immutable. In other words, they shouldn't be directly changed. Instead of a direct mutation, we can use non-mutating methods like
.concat() to essentially make a copy of the array, and then we'll change and return the copy:
var userReducer = function(state = [], action) { if (action.type === 'ADD_USER') { var newState = state.concat([action.user]); return newState; } return state; }
With this update to the reducer, adding a new user results in a copy of the state argument being changed and returned. When not adding a new user, notice the original state is returned instead of creating a copy.
There's a whole section below on Immutable Data Structures which sheds more light on these types of best practices.
Multiple Reducers
The last example was a nice primer, but most applications will need more complex state for the entire application. Since Redux uses just one store, we'll need to use nested objects to organize state into different sections. Let's imagine we want our store to resemble this object:
{ userState: { ... }, widgetState: { ... } }
It's still "one store = one object" for the entire application, but it has nested objects for
userState and
widgetState that can contain all kinds of data. This might seem overly simplistic, but it's actually not that far from resembling a real Redux store.
In order to create a store with nested objects, we'll need to define each section with a reducer:
import { createStore, combineReducers } from 'redux'; // The User Reducer const userReducer = function(state = {}, action) { return state; } // The Widget Reducer const widgetReducer = function(state = {}, action) { return state; } // Combine Reducers const reducers = combineReducers({ userState: userReducer, widgetState: widgetReducer }); const store = createStore(reducers);
The use of
combineReducers() allows us to describe our store in terms of different logical sections and assign reducers to each section. Now, when each reducer returns initial state, that state will go into it's respective
userState or
widgetState section of the store.
Something very important to note is that now, each reducer gets passed its respective subsection of the overall state, not the whole store's worth of state like with the one-reducer example. Then the state returned from each reducer applies to its subsection.
Which Reducer is Called After a Dispatch?
All of them. Comparing reducers to funnels is even more apparent when we consider that each time an action is dispatched, all reducers will be called and will have an opportunity to update their respective state:
I say "their" state carefully because the reducer's "current state" argument and its returned "updated" state only affect that reducer's section of the store. Remember, as stated in the previous section though, each reducer only gets passed its respective state, not the whole state.
Action Strategies
There are actually quite a few strategies for creating and managing actions and action types. While they are very good to know, they aren't as critical as some of the other information in this article. To keep the article smaller, we've documented the basic action strategies you should be aware of in the GitHub repo that goes along with this series.
Immutable Data Structures
The shape of the state is up to you: it can be a primitive, an array, an object, or even an Immutable.js data structure. The only important part is that you should not mutate the state object, but return a new object if the state changes." - Redux docs
That statement says a lot, and we've already alluded to this point in this tutorial. If we were to start discussing the ins and outs and pros and cons of what it means to be immutable vs mutable, we could go on for a whole blog article's worth of information. So instead I'm only going to highlight some main points.
To start:
- JavaScript's primitive data types (Number, String, Boolean, Undefined, and Null) are already immutable.
- Objects, arrays, and functions are mutable.
It's been said that mutability on data structures is prone to bugs. Since our store will be made up of state objects and arrays, we will need to implement a strategy to keep the state immutable.
Let's imagine a
state object in which we need to change a property. Here are three ways:
// Example One state.foo = '123'; // Example Two Object.assign(state, { foo: 123 }); // Example Three var newState = Object.assign({}, state, { foo: 123 });
The first and second examples mutate the state object. The second example mutates because
Object.assign() merges all its arguments into the first argument. But this reason is also why the third example doesn't mutate the state.
The third example merges the contents of
state and
{foo: 123} into a whole new blank object. This is a common trick that allows us to essentially create a copy of the state and mutate the copy without affecting the original
state.
The object "spread operator" is another way to keep the state immutable:
const newState = { ...state, foo: 123 };
For a very detailed explanation of what's going on and how this is nice for Redux, see their docs on this subject.
Object.assign() and spread operators are both ES2015.
In summary, there are many ways to explicitly keep objects and arrays immutable. Many devs use libraries like seamless-immutable, Mori, or even Facebook's own Immutable.js.
Initial State and Time Travel
If you read the docs, you may notice a second argument for
createStore() which is for "initial state". This might seem like an alternative to reducers creating initial state. However, this initial state should only be used for "state hydration".
Imagine a user does a refresh on your SPA and the store's state is reset to the reducer initial states. This might not be desired.
Instead, imagine you could have been using a strategy to persist the store and then you can re-hydrate it into Redux on the refresh. This is the reason for sending initial state into
createStore().
This brings up an interesting concept though. If it's so cheap and easy to rehydrate old state, one could imagine the equivalent of state "time travel" in their app. This can be useful for debugging or even undo/redo features. Having all your state in one store makes a lot of sense for these and many reasons! This is just one reason why immutable state helps us.
In an interview, Dan Abramov was asked "Why did you develop Redux?"
I didn't mean to create a Flux framework. When React Europe was first announced, I proposed a talk on 'hot reloading and time travel' but to be honest I had no idea how to implement time travel.
Redux with React
As we've already discussed, Redux is framework-agnostic. Understanding Redux's core concepts first is important before you even think about how it works with React. But now we're ready to take a Container Component from the last article and apply Redux to it.
First, here is the original component without Redux:
import React from 'react'; import axios from 'axios'; import UserList from '../views/list-user'; const UserListContainer = React.createClass({ getInitialState: function() { return { users: [] }; }, componentDidMount: function() { axios.get('/path/to/user-api').then(response => { this.setState({users: response.data}); }); }, render: function() { return <UserList users={this.state.users} />; } }); export default UserListContainer;
Sure, it does its Ajax request and updates its own local state. But if other areas in the application need to change based on the newly acquired user list, this strategy won't suffice.
With the Redux strategy, we can dispatch an action when the Ajax request returns instead of doing
this.setState(). Then this component and others can subscribe to the state change. But this actually brings us to a question of how do we setup the
store.subscribe() to update the component's state?
I suppose I could provide several examples of manually wiring up components to the Redux store. You can probably even imagine how that might look with your own approach. But ultimately, at the end of those examples I would explain that there's a better way, and to forget the manual examples. I would then introduce the official React/Redux binding module called react-redux. So let's just jump straight to that.
Connecting with
react-redux
Just to be clear,
react,
redux, and
react-redux are three separate modules on npm. The
react-redux module allows us to "connect" React components to Redux in a more convenient way.
Here's what it looks like:
import React from 'react'; import { connect } from 'react-redux'; import store from '../path/to/store'; import axios from 'axios'; import UserList from '../views/list-user'; const UserListContainer = React.createClass({ componentDidMount: function() { axios.get('/path/to/user-api').then(response => { store.dispatch({ type: 'USER_LIST_SUCCESS', users: response.data }); }); }, render: function() { return <UserList users={this.props.users} />; } }); const mapStateToProps = function(store) { return { users: store.userState.users }; } export default connect(mapStateToProps)(UserListContainer);
There are a lot of new things going on:
- We've imported the
connectfunction from
react-redux.
- This code might be easier to follow from the bottom-up starting with the connection. The
connect()function actually takes two arguments, but we're only showing one for
mapStateToProps().
It might look weird to see the extra set of parenthesis for
connect()(). This is actually two function calls. The first, to
connect()returns another function. I suppose we could have assigned that function to a name and then called it, but why do that when we can just call it immediately with the second set of parenthesis? Besides, we wouldn't need that second function name to exist for any reason after it's called anyways. The second function though needs you to pass a React component. In this case it's our Container Component.
I understand if you're thinking "why make it look more complex than it has to be?", but this is actually a common "functional programming" paradigm, so it's good to learn it.
- The first argument to
connect()is a function that should return an object. The object's properties will become "props" on the component. You can see their values come from the state. Now, I hope the function name "mapStateToProps" makes more sense. Also notice that
mapStateToProps()will receive an argument which is the entire Redux store. The main idea of
mapStateToProps()is to isolate which parts of the overall state this component needs as its props.
- For reasons mentioned in #3, we no longer need
getInitialState()to exist. Also notice that we refer to
this.props.usersinstead of
this.state.userssince the
usersarray is now a prop and not local component state.
- The Ajax return now dispatches an action instead of updating local component state. For brevity, we're not using action creators or action type constants.
The code example makes an assumption about how the user reducer works which may not be apparent. Notice how the store has
userState property. But where did that name come from?
const mapStateToProps = function(store) { return { users: store.userState.users }; }
That name came from when we combined our reducers:
const reducers = combineReducers({ userState: userReducer, widgetState: widgetReducer });
What about the
.users property of
userState? Where did that come from?
While we didn't show an actual reducer for the example (because it would be in another file), it's the reducer which determines the sub properties of its respective state. To ensure
.users is a property of
userState, the reducer for these examples might look like this:
const initialUserState = { users: [] } const userReducer = function(state = initialUserState, action) { switch(action.type) { case 'USER_LIST_SUCCESS': return Object.assign({}, state, { users: action.users }); } return state; }
Ajax Lifecycle Dispatches
In our Ajax example, we only dispatched one action. It was called
'USER_LIST_SUCCESS' on purpose because we may want to also dispatch
'USER_LIST_REQUEST' before the Ajax starts and
'USER_LIST_FAILED' on an Ajax failure. Be sure to read the docs on Asynchronous Actions.
Dispatching from Events
In the previous article, we saw that events should be passed down from Container to Presentational Components. It turns out
react-redux helps with that too in cases where an event simply needs to dispatch an action:
... const mapDispatchToProps = function(dispatch, ownProps) { return { toggleActive: function() { dispatch({ ... }); } } } export default connect( mapStateToProps, mapDispatchToProps )(UserListContainer);
In the Presentation Component, we can do
onClick={this.props.toggleActive} just as we did before but this time we didn't have to write the event itself.
Container Component Omission
Sometimes, a Container Component only needs to subscribe to the store and it doesn't need any methods like
componentDidMount() to kick off Ajax requests. It may only need a
render() method to pass state down to the Presentational Component. In this case, we can make a Container Component this way:
import React from 'react'; import { connect } from 'react-redux'; import UserList from '../views/list-user'; const mapStateToProps = function(store) { return { users: store.userState.users }; } export default connect(mapStateToProps)(UserList);
Yes folks, that's the whole file for our new Container Component. But wait, where's the Container Component? And why don't we have any use of
React.createClass() here?
As it turns out, the
connect() creates a Container Component for us. Notice this time we're passing in the Presentational Component directly instead of creating our own Container Component to pass in. If you really think about what Container Components do, remember they exist to allow the Presentational Component to focus on just the view and not state. They also pass state into the child view as props. And that's exactly what
connect() does — it passes state (via props) into our Presentational Component and actually returns a React component that wraps the Presentational one. In essence, that wrapper is a Container Component.
So does that mean the examples from before are actually two Container Components wrapping a Presentational one? Sure, you can think of it that way. But that's not a problem, it's just only necessary when our Container Component needs more React methods besides
render().
Think of the two Container Components as serving different but related roles:
Hmm, maybe that's why the React logo looks like an atom!
Provider
In order for any of this
react-redux code to work, you'll need to let your app know how to use
react-redux with a
<Provider /> component. This component wraps your entire React application. If you're using React Router, it would look like this:
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './store'; import router from './router'; ReactDOM.render( <Provider store={store}>{router}</Provider>, document.getElementById('root') );
The
store being attached to Provider is what really "connects" React and Redux via
react-redux. This file is an example of what you're main entry-point might look like.
Redux with React Router
It's not required, but there is another npm project called react-router-redux. Since routes are technically a part of UI-state and React Router doesn't know about Redux, this project helps link the two.
Do you see what I did there? We went full circle and we're back to the first article!
Final Project
The final project guide for this series allows you to make a small "Users and Widgets" Single Page App:
As with the other articles in this series, each comes with a guide that has even more documentation on how the guide works at GitHub.
Summary
I really hope you've enjoyed this series as much as I have writing it. I realize there are many topics on React we didn't cover (forms for one), but I tried to stay true to the premise that I wanted to give new users to React a sense of how to get past the basics, and what it feels like to make a Single Page Application.
While many helped, a special thanks goes to Lynn Fisher for the amazing graphics she provided for the tutorials!
Article Series:
- React Router
- Container Components
- Redux (You are here!)
Outstanding article.
Great article!
Spotted a typo, btw:
That was just there to see if you were paying attention. jk Thanks Jeremy
Got it!
Thanks for writing this series. I recently starting learning various NodeJS related technologies. After going through a number of tutorials, I can say hands down…you articles are the most helpful introduction I have found. Thanks again!
Wooow! Now that’s a CSSfuckingtrick!
These were brilliant, thanks a million Brad!
Another fun article to read, but not a fan of Redux at all. String constants holding action type identifiers paired with switch-case statements for the actual logic feels like C or C++ to me, not idiomatic JavaScript. When JavaScript looks like C or C++, something isn’t right, lol. Would love to see an example that looks more like JavaScript :)
I’m not a fan of the string constant strategy either, but it’s just the most common I see so I thought I’d go along with it. I think it teaches the basics of what we’re trying to do. I’m a huge fan of
redux-actwhich is a different approach. It’s a project that eases the pain of the boilerplate stuff with action types and action creators. And it doesn’t use the string constant approach, in fact it abstracts that whole process away from you which is nice. I wouldn’t blame Redux for that one strategy. It’s just one of many strategies that could be used that has little to do with what Redux is offering. The main idea, I need to dispatch something and have the correct reducer know of it – any strategy that you can invent that does that is fine.
awesome! A lot for my brain to process, but I will start a test project and try to apply these concepts. Thanks for taking the time to write such a good article!
Thanks Victor, and also Mike, Balazs, and Darrly
Hi. Why for call // Dispatch our first action to express an intent to change the state in the #Our first Redux Store you using keyword VAR
var store.dispatch({
type: ‘ADD_USER’,
user: {name: ‘Dan’}
});
Hi Tim, I’m sorry but I don’t understand the question
Sorry for my english.
in the example code that was writing for part #Our first Redux Store
in the end of that is writing
var store.dispatch({
type: ‘ADD_USER’,
user: {name: ‘Dan’}
});
so i’m just try to understand why “var” stay before calling a function store.dispatch
I accidentally made a whole new comment instead of a reply. See below
Oh! That’s a typo, I’ll see if Chris can remove it. I can see why that would be confusing, it’s not right. You’re the first one to point it out, out of all who reviewed it :)
Oh Thanks. Now i get it )
Actually I’m so confused with Redux. In the second image shown tree of the components. How to call or initiate changing store from the lowest dump component without throwing it through the whole tree? Or is it better not to do it? And if it is, so why not?
I’ll say “presentational” instead of “dumb” since that’s mostly how the industry wants to refer to it. But let’s say the presentational component wants to initiate change. Usually a need to change state is due to an event. So based on the last article, remember we can pass events from the container component down to the presentational one. So while the presentational one is actually handling the
onClick, it’s calling a function that resides in the container component. The container is dealing with state, so the function called by the
onClick(in the container) is doing the
store.dispatch(...)
The demo code at GitHub shows this. Here is the presentational “view” component that handles a click Example Here
Here is it’s container component where
deleteUserreferences a function which is an API call: Example Here
This container component could have been written like this:
I didn’t do this though in my code because I want to conduct an XHR call before I dispatch which is why the real code calls the
userApi.deleteUser, so that it can do the XHR then dispatch on the successful return. From what I’ve seen there are different strategies for doing XHR and store dispatches. This is just one simple way. But hopefully the code will give you some more context that the article only glosses over
Don’t understand why I need to wrap the presentational component in the container. May i ask you please explain it again?
And one more question
I have for example a big tree components with 10 levels, and for example, with the action button is only in the last component of all levels only show the state. In that case, do I need to flow down an event action from the top of the tree where I connected to store or what? Thank you very much for your helping with this. Your posts about react is a big deal for me.
Can I assume you read the previous article on container components? The premise is that we want the presentational ones (the views) to not be aware of state. This makes them more re-usuable. Imagine the presentational view might be a confirmation prompt. If it’s stateless and only gets state from containers, then it can be reused with multiple container components for different state contexts. So as a good practice, we always want to keep the presentational components state free.
With your second question, if I’ve understanding, you could have 10 defendants like you mention where the bottom one is capturing the actual event, and the most parented component is the container in control of state – then I guess you could pass the event handler down the line. In this case, be sure to look up spread attributes, they make it easy to pass props from parent to child to child to child etc. – OR – I’m not really sure why you have 10 nested components, but just know that you generally speaking, most presentational view components have a container that goes with them. So you don’t have to have just one at the top of this long descendant list of views. You could have a container that has a view, then that view has a child component that is a container, that has a view. So for my style of writing React, it would be unusual to have tons of nested views with no container components in the mix. Then keep in mind, any container component can communicate with state. I really hope that makes sense :)
I think you might be to the point where you have achitectual questions, which you probably won’t find strait forward answers to in articles. When I was at that state – still am – I found it nice to look at tons of example code or boilerplate react projects on github to see how they did it. I would make sure you checkout the github code I posted for this article too.
Oh reusable!!! Of course!!! This explain a lot!
But second, in this case better without Redux, I can just keep all state in one main container and that’s all, app well be faster on clear React. Probably I have not grown enough for the Redux.
Thank you for the articles, for me it was a big help. Especially about components.
Hi Brad…Great article. May I know, what is the tool you are using to create the diagrams? Thanks.
A friend made them for me. She’s credited at the very end in the summary.
One of the best articles i’ve read so far on the subject! Really well explained, thank you!
This is probably the best article to start learning React. Thank you for the great articles.
I totally agree i have been reading for days trying to make sense out of the Redux concept. This explanation is simplistic and right on target.Now everything make sense and really made me love Redux
Hi Brad,
Thanks for these awesome series.
I’ve a question that if a build a website without redux, what problems i may face?
Is redux a must use tool?
I need to complete the website asap. Thanks in advance!
Hi Brad,
First of all, Great articles. This is the first and only place I could find a bigger application in reactjs and react-router.
I’m using react and react-router as in first 2 tutorials.
Do I need to use redux also for my website?
I need to build a SPA asap, so if I do it without redux, what problems I may face?
Thanks in advance!
Well Redux certainly isn’t required for a React app, but some form of state-management is for any size app. Using local state management (React’s built-in state stuff for each component) is nice, but for me I find that using Redux for a bigger application is even nicer because all components can share state. If you’re not using Redux (or something similar), how are you managing state on an app-wide basis?
Really thanks Brad,
Nice article, nice pictures, nice css … nice all.
But i’d like go a little bit forward.
Just to ask if it will be a next article on porting your stuff to mdl (material design little) (this web is css-tricks!), or any other material design css frameworks.
I am really frustrated on my own work to merge this article and the react-router with the mdl framework.
I have setup the
index.htmllike the example on index and on
main-layout.jsi translated some of the samples like this, but i don’t know how to link the menu with the
Linkcomponent of react-router, and show the result in the ‘container page’
Thanks in advance
Hi Santi, actually Material Design with React isn’t something I have experience with. This series from me is pretty much wrapped up with this last article. But I wonder if Chris can find someone to do an article on what you’re talking about. Sorry I couldn’t help more
This blog post was featured in The React Newsletter #25. | https://css-tricks.com/learning-react-redux/ | CC-MAIN-2020-05 | refinedweb | 5,876 | 64.3 |
I followed the instruction of
Alamofire
cocoapods-test
pod init
source ''
platform :ios, '8.0'
use_frameworks!
pod 'Alamofire', '~> 3.0'
pod install
Updating local specs repositories
CocoaPods 1.0.0.beta.6 is available.
To update use: `gem install cocoapods --pre`
[!] This is a test version we'd love you to try.
For more information see
and the CHANGELOG for this version.
Analyzing dependencies
Downloading dependencies
Installing Alamofire (3.3.0)
Generating Pods project
Integrating client project
[!] Please close any current Xcode sessions and use `cocoapods-test.xcworkspace` for this project from now on.
Sending stats
Pod installation complete! There is 1 dependency from the Podfile and 1 total pod installed.
cocoapods-test.xcworkspace
ViewController
import Alamofire
No such module 'Alamofire'
XCode 7.2.1
Swift 2.1.1
Alamofire 3.3.0
import Alamofire
I was having this exact same problem. Please make sure that you are on Xcode 7.3 and using Swift 2.2.
You can check your Swift version using
xcrun swift -version. Updating Xcode to 7.3 should also automatically update Swift.
Updating Xcode resolved this issue for me. | https://codedump.io/share/5xxIcOuLIdQW/1/always-get-build-error--no-such-module-39alamofire39 | CC-MAIN-2017-43 | refinedweb | 184 | 64.37 |
On 01/10/2012 05:06 AM, Greg Weber wrote: > Some of your comments seem to not fully recognize the name-spacing (plus > simple type resolution) aspect of this proposal that I probably didn't > explain well enough. Or maybe I don't understand your comments. > > For record.field, field is under the record's namespace. A namespace (from > a module or under the new system a record), cannot export conflicting > names, and there this system prevents the importer from every having a > conflict with a record field name because the field is still under the > record's namespace when imported. The type system must resolve the type of > the record, and generally the field cannot contribute to this effort. (I have only used Haskell for several years, not implemented Haskell several times; apologies for my amateurish understanding of the type system.) So Type inference proceeds assuming that "record.field" is something equivalent to "undefined record" (using "undefined" as a function type), and the program is only correct if the type of "record" resolves to a concrete type? I don't know if "concrete type" is at all the right terminology; I mean a type-variable doesn't count (whether class-constrained, "Num a => a", or not, "a", or even "m Int" is not concrete). Is "forall a. Maybe a" okay (if Maybe were a record)? "forall a. Num a => Maybe a"? I'm guessing "yes".? Does this order of stages (regular scope selection, then type inference, then record scope) make as high a fraction of code work as Frege's left-to-right model (which I am guessing interleaves type inference and record scope selection as it proceeds left-to-right through the program)? Correct me if I got something wrong, -Isaac | http://www.haskell.org/pipermail/glasgow-haskell-users/2012-January/021517.html | CC-MAIN-2014-41 | refinedweb | 293 | 69.92 |
Hide Forgot
Description of problem:
In the Utilization card of the Bare Metal Host Dashboard, while checking the Popovers for the 'CPU Usage' / 'Memory Usage' / 'Filesystem usage', the Top consumers list is empty.
Also while clicking on 'View More', in the new page that opens, the query returns "No datapoints found".
In my case the query was:
topk(25, sort_desc(sum(container_memory_working_set_bytes{instance=~"172.22.0.98:.*",container="",pod!=""}) BY (pod, namespace)))
Version-Release number of selected component (if applicable):
4.3.0-0.ci-2019-11-15-015333
How reproducible:
Steps to Reproduce:
1. navigate to Compute > Bare Metal Hosts
2. select one bare metal host and check the Dashboard
3. on the Utilization card, click on the Usage for any of the 'CPU Usage' / 'Memory Usage' / 'Filesystem usage'
4. click in 'View More'
Actual results:
- list of Top Consumers is empty
- in the metrics window, the query returns 'No datapoints found'
Expected results:
- list of Top consumers and the details in the Metrics windows. | https://bugzilla.redhat.com/show_bug.cgi?id=1772874 | CC-MAIN-2020-29 | refinedweb | 166 | 54.93 |
~~~~~~~~~~~~~~~Index~~~~~~~~~~~~~~
Part 1.) Introduction
Part 2.) Basic Structure
Part 3.) Variables and Types
Part 4.) Simple Commands and Syntax
Part 5.) Logical Operators
Part 6.) Decision Structures
~~~~~~~~~~~~~~~Part 1~~~~~~~~~~~~~~~
Introduction:
Hi, thanks for reading my newest tutuorial. A lot of n00bs are asking about the most simplest of things, including syntax and such. The purpose of this tutorial is to give the very basics on Java, whether you're trying to get a head start on your class or as a little extra help in your class, so you can jump into Java with ease. Since Java is basically an intro course to other programming languages, such as C and C++, it is important to master the basic concepts of this simple language in order to move on. Note: this is not a replacement for a good old fashioned book or class, which I suggest doing. ....
Let's get started, shall we?
~~~~~~~~~~~~~~~Part 2~~~~~~~~~~~~~~~
Basic Structure:
If you look at a piece of Java code, you will notice that it has a very distinct structure. This is because its object oriented. Every thing takes place in classes, making it easier to reuse code. ((we programmers like to recycle.... because we're lazy >_>)) A class is an outer most shell of code, holding all the code associated inside. Every program has to has at least one class, a main class, or your program will not compile.
public class main { }
That's the outtermost shell of your program. Anywho, inside a class, you should have these components called methods. These babies is where all the magic happen. Every main class should have a main method. This main method is where your main code is run. You could run a program without using more than the main class with only the main method, but then it would take the charm outta object oriented.
So, basic structure:
Main class{ Main method { //code } Method 1 { //code } Method 2 { //code } }
Now, these {} (curly brackets) are important because they hold the code that fits inside. If you're missing one, your code my compile, but the program will not run the way you want. I would go into detail about how to set up classes, but that's a little complex for a n00b at the moment, so you can read a tutorial about that some other time. For now, we will look at a method.
public class main { public static void main(String[] args) { //code } }
The first word public means that any other class can see or use it (will cover in another tutorial). It could either be public, private, or protected. The static word means that it can be called within the same class. If the static is skipped, the compiler assumes it to be an instance method, meaning you have to created an instance of the class to use the method (will cover in another tutorial). Void, however, can't be skipped. This is the return type. For the main class, you usually are not returning anything, so leave it void. Next is the methods name. It should have the same rules as a variable when it comes to naming. The parenthesis are the parameters. Parameters are typed values that the method takes and manipulates, but we will cover that in another tutorial. The String[] args thing in complicated, but I think there's a tutorial on that if you're really interested. It has to do with calling your program in the command promt or something.
So, putting it simpler:
access (static) return name(type parameter) {}
For now, all you should know is the code I gave above. This is the basic structure of a program.
~~~~~~~~~~~~~~~~~Part 3~~~~~~~~~~~~~~~~~~~~
Variables and Types:
In Java, or any programming language for that matter, you need variables. Variables hold values for your program. It makes code a lot more clean if everything is clearly labeled, as opposed to a big jumble of numbers. You also use variables to catch input. Say you're making a program to determine how much money you will have in a savings account after the interest rate, and you want to say that the rate of interest is... 0.02% or something like that (I'd switch banks >=[ ). You could make a variable called interestRate, and set it equal to 0.02, so everytime you want to use that number as an interest rate, you'd use interestRate instead.
Why? you ask? Well, when you start a project, quit, then come back to it 3 months later, chances are you are not going to remember what those numbers are and what their significance to the program is. Programs can have as many variables as you want. Now, variables also have different types, which determine what kind of value goes in them.
Here are a list of common types:
int - integer (most common. no decimal)
long - holds a really big integer
float - accurate up to 7 decimal places
double - accurate up to 15 decimal places I do believe (at work and don't have a book)
boolean - false or true (also 1 = true, 0 = false)
String - anything from numbers to letters to whole sentences. It will take the input literately.
char - character, such as f or 6 or \. You can also use the decimal numbers to determine a character (130 = é)
These are the most common types you will deal with. Float isn't used that often, as double is way more accurate. Actually, if you use a float the compiler will probably tell you that you should use double due to loss of precision. Now to declare a new variable, all you have to do is state it's type and what it is to be called.
type name;
This is where the semi-colon starts to come into play. At the end of every statement, you use a ;. This tells the compiler that the command is over, and to start with the next command. You can also initialize the variable, meaning you can assign a value to it, in the same line or in 2 separate commands.
Next I guess I should explain the rules to naming things. Just like children, you are not allowed to name variables retarded names. Your variable should be descriptive and should leave no doubt what the meaning of the variable's contents. Also, you cannot start a variable name with numbers or any special characters other than _ and $, which are rare,and the variable cannot have spaces. It's also standard convention to make the first letter for normal variables lowercase, with the first letter of other word is uppercase. Lastly, the names cannot be reserved words, such as: int, true, in, out, class, ...etc.
Legal names:
-name
-file2
-_letter
-lastNameValue
Illigal names:
-2variable
-&name
-last name value
public class main { public static void main(String[] args) { int x = 5; int y; y = 10; } }
Now we have declared 2 variables, x and y. x's value is 5, and y is 10. Those variables will contain those values until changed by declaring it as something else, or until it goes out of scope (will explain in later tutorial). Easy enough? Let's try another.
public class main { public static void main(String[] args) { double d = 5.25; String greeting = "hello"; } }
Simple enough, right? Now lets figure out how to make programs that do stuff with those variables.
~~~~~~~~~~~~~~~~Part 4~~~~~~~~~~~~~~~~~~~~
Simple Commands and Syntax:
Okay, everybody's first program in ANY language is hello, world. That's classic. So I will show you how to do it.
public class main { public static void main(String[] args) { System.out.print("Hello, world"); } }
That's it. Wow. Kinda lame, huh? Yea, your first programs will be. Okay, to break this down, the System part means you're dealing with the console. I prefer to do stuff in the console because I'm too lazy to fool with GUI (graphic user interface - the pretty pop up windows), so most of the stuff in my tutorials will be console. Now, after the System you have to put a period here. This is an important part that will be explained in a later tutorial when we talk about classes and methods and instantiation and junk. Anywho, the out means that you're outputting something through the console (System). print is just the method used to return a String object to the screen.
Remember how I told you that methods have to have parenthesis, which may or may not hold parameters? Well here is an example. What you put inside those quotes are a type String object, which the print method takes and manipulates, which in this case just prints it to the console. Pretty simple stuff.
The thing with print is that is keeps going and going on the same line until you type a return character in the string. \n tells the compiler to make a new line. You could use this at the end of every line, or use:
System.out.println("");
"Hey, the print and println methods take Strings, right? Hey! I know how to make Strings!" That's right. Lets combine what we know.
public class main{ public static void main(String[] args) { String gretting = "Hello"; String comma = ','; String subject = " world!!!"; System.out.print(greeting); System.out.print(comma); System.out.print(subject); } }
Did I also mention that you can combine strings using a +? Example:
System.out.println(greeting + comma + subject);
Okay, now lets manipulate those variables. + and - signs work just as you expect them to when in an expression. 1 + 2 = 3. * and / are the same as well. 2 * 1 = 2. % (modulus) returns the remainder. This is expecially useful for searching for even/odd numbers or prime numbers. 4 % 2 = 0, 15 % 10 = 5. = is considered an assignment operater, meaning it assigns values to something, in this case, an answer to a variable. The variable comes first when doing math. Say z is the variable catching the answer, you put the z before the = sign. z = x + y; means that z is equal to the value of x plus the value of y. Lets do an example, shall we?
public class main { public static void main(String[] args) { int x = 3; int y = 2; int z; z = x + y; System.out.println(z); } }
Way easy, non? By the way, the z was magically transformed into a String by the compiler.
If you're trying to, say, add up a list of numbers into a variable int sum, you are probably going to say
sum = sum + num;
That is a legal statement, but you could also condense it to just
sum += num;
This takes sum, adds num, then assigns it to sum. These are great ways to add values in an array, like say adding scores or something. You can do this for all 5 of those operations I showed.
+=
-=
*=
/=
%=
Also, you will want to increment or decrement a number as well. ++ or -- will either add 1 or minus 1 from the current variable. You've probably already looked at some code and saw a for loop. For loops are perfect examples when showing incrementation.
for(int i = 0; i < 5, i++) {//do stuff}
After each iteration the i increments itself. This is an example of a postfix function, as it does the operation after it reads the value of i. You could also have ++i and --i, but the number will be increamented/decremented before showing, so the loop shown above would be shorter.
((You've probably also seen me do a // in some code blocks. These are comments. Everything after these is ignored by the compiler. I wrote a whole tutorial about this called Documentation for N00blets. You should check it out for a more in depth explanation))
~~~~~~~~~~~~~~~Part 5~~~~~~~~~~~~~~~~~~
Logical Operators:
Without these.... we really couldn't do anything. They are probably the most import thing when it comes to doing ANYTHING in programming. Collision detection in a game, printing things out in an array, checking for certain info, organizing data, etc. all depend on logical operators. You've already seen most of these before in math class. Remember those greater than and less than symbols? If you paid attention in class you already know how these work.
These determine conditions (relational operators):
< less than > greater than <= less than or equal to >= greater than or equal to == is equal to != not equal to
There are also the logic operators for determining truthfulness:
&& and || or (shift + backslash key) ! not
Now, there is a chart to help you get a feel for these little operations. Their called truth tables. You probably already learned about those in math. In order for an "and" statement to be true, all the conditions have to be true, or else it will return false. On the other hand, for an "or" statement to be true, at least one of the conditions has to be true
X Y && ---------------------------------- T T T T F F F T F F F F X Y Z && -------------------------------------------- T T T T T T F F T F T F T F F F F T T F F T F F F F T F F F F F X Y || ----------------------------- T T T T F T F T T F F F X Y Z || ---------------------------------------- T T T T T T F T T F T T T F F T F T T T F T F T F F T T F F F F
That should clear things up a bit. Not basically negates anything. If x = true, then !x = false, and vice versa. Simple enough. Now lets put those things into context.
~~~~~~~~~~~~~~~Part 6~~~~~~~~~~~~~~~~
Decision Structures:
if statements are very helpful when making conditions, and they are easy to use. NOTICE!!!! Because I am lazy, I'm shortening System.out.println to sout. If you type sout in Netbeans and hit tab, it will automatically expand into System.out.println("");. Pretty nifty.
if(x > y) sout(x);
This just basically says that if the value of x is greater than the value of y, then print x to the screen. The basic format for an if statement is:
if(variable condition variable) {
do stuff
}
Because I only had one line in the above example, I had no need for curly brackets. If you have more than one command to go in that if statement, you need to enlose them in the curly brackets. I use curly brackets all the time for clarity's sake (and I like to be better safe than sorry).
else statements are what happens when an if statement fails. These aren't exactly necessary unless you have to have something happen depending on the variables. They don't need parenthsis as they are like the worst case scenarios.
if(x > y) { sout(x); } else { sout(y); }
else if are kinda like what I call "plan b" conditions. If situation a doesn't work out, and situation 2 does, then do this, else do this. That's those 3 put in a nutshell.
if(x > y) { sout("x is greater than y"); } else if(x < y) { sout("x is less than y"); } else if(x == y) { sout("x is equal to y"); } else { sout("I have no clue what in the hell happend :(/> "); }
for loops we sorta glanced at above. They state a loop control variable, usually an i or x, put a conditional in place, then increment i, and it does all the stuff in the brackets while that condition is true. These are very powerful tools and are used very very very often. Be careful though, as your computer starts to count at zero.
for(int controlVariable; condition including controlVariable; controlVariable++) {do stuff}
((Make sure those are semi-colons in between, as they are basically mini-statements))
Say we want to ... find a factoral of number x. We could say:
int factoral = 5; int x = 1; for(int i = 0; i < 5; i++) { x *= factoral; factoral--; System.out.println(x); }
This code basically finds the 5! by using a for loop. We set a max (factoral decreases, so we can't put that as i < factoral) at 5, then for each of the five steps it multiplies x by factoral then factoral decreases by 1. If we look at the values, just like a step through debugger we would see:
i = 0
x = 1
factoral = 5
i = 1
x = 5
factoral = 4
i = 2
x = 20
factoral = 3
i = 2
x = 60
factoral = 2
i = 4
x = 120
factoral = 1
i = 5
x = 120
factoral = 0
Very useful arent they. Instead of going through step by step and doing those steps, you could just use for loops to handle it. I mean, if you want to write it all out, fine, but if you're trying to calculate 573!, you'll be wanting to use that loop.
((Actually, I'm curious as to what that would be... *reruns program* Oh yea, I should mention that there are limits to how many numbers an int can hold. >_> For to find 573!, you'd probably need to make x a long. Actually, that number is so big, it just goes to zero's after a while due to the number restraints on the variables. :\ Even my calculator gives an overflow error, but 17! = 355687428096000
Okay, while loops are very useful for doing a certain task while a certain condition is true.
while(variable condition variable) {do stuff}
while(x < y) { sout(x); }
Very easy. This checks to make sure the condition is true before doing what's inside the brackets. You could also to a post check operation, meaning
doing the action and then checking to make sure the conditional is true, by using do while loops.
do { sout(x); } while (x < y);
do {statements} while(condition);
Okay, with this little knowledge, you should be able to do quite a bit in Java. Believe it or not, this simple basic stuff you just learned is about 90% of the meat in a Java program. You're half way to becoming a decent programmer.
tuned for more.
Next tutorial:
Java For N00blets Part 2
This post has been edited by macosxnerd101: 25 May 2012 - 02:51 PM
Reason for edit:: Added link to next tutorial | http://www.dreamincode.net/forums/topic/108528-basic-java-for-n00blets/ | CC-MAIN-2017-26 | refinedweb | 3,059 | 73.07 |
For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:
I am a developer and I would like extend feed to use the BITMEX api. Can I contribute?
I am creating a new feed to Bitmex similar as the Yahoo Api (that is not working anymore).
Here is the docs:.
What's guidelines I can adopt to contribute?
- backtrader administrators last edited by
@dedeco said in I am a developer and I would like extend feed to use the BITMEX api. Can I contribute?:
What's guidelines I can adopt to contribute?
- Create your data feed
- Upload it to pypi with the name of your choosing, for example: bitmex_backtrader
- Let users know in your docs they can do something like this
import backtrader as bt from bitmex_backtrader import BitmexBacktrader data = BitmexBacktrader(dataname=...) cerebro = bt.Cerebro() cerebro.addata(data) ...
@backtrader Thanks!
I will let know when I finished!
Hi @dedeco ,
I'm looking as well for a bitmex broker to be able to do live trade. Is they are anything I can help you ? | https://community.backtrader.com/topic/1273/i-am-a-developer-and-i-would-like-extend-feed-to-use-the-bitmex-api-can-i-contribute | CC-MAIN-2020-10 | refinedweb | 183 | 66.23 |
CodePlexProject Hosting for Open Source Software
I've added a Models folder in Themes/TheThemeMachine and created a few classes inside. Tried a few different namespaces and no namespace, but there's always a compilation error when those classes are referenced in a Razor view:
Description:
An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0234: The type or namespace name 'TheThemeMachine' does not exist in the namespace 'Orchard.Themes' (are you missing an assembly reference?)
Source Error:
Line 1: @using Orchard.Themes.TheThemeMachine.Models
Line 2: <div id="useful_links">
Line 3: <div class="underlined_title" id="links_title">
Line 1: @using Orchard.Themes.TheThemeMachine.Models
Line 2: <div id="useful_links">
Line 3: <div class="underlined_title" id="links_title">
I think you need to open the TheThemeMachine.csproj and add your code to that project instead of adding it to the Themes project.
Thanks sfmskywalker, unfortunately here is no TheThemeMachine.csproj in source download. I've added the classes in `Orchard.Source.1.5.1\src\Orchard.Web\Themes\TheThemeMachine\Models` .
Ok, assuming the model classes live in the correct namespace, maybe build the Themes project? Alternatively, you could generate a new custom theme and have it inherot from TheThemeMachine. Put your classes in your custom theme.
The first thing to ask yourself is whether you really should put that code into the theme. In 99% of cases you should not.
Then, if you determine that yes, you need code in the theme, you need the theme to have a csproj file. If there isn't one, you'll have to create it.
And then there's that, yes :)
You guys are AMAZING. Works perfectly well now.
Generally my idea for this Orchard site is to build the headers, footers, left and right sections in Visual Studio and leave the center with the main content editable by admins. All the parts, except the center change very rarely, so 99.9% of the time users
won't need my help. The code I'm adding is for stuff like retrieving an RSS feed and displaying it on a side bar. It seems natural to put all my code in a theme. I'm open to suggestions and critique, so if this doesn't make sense please do say.
That is definitely not something I would put in the theme. Widgets come to mind.
Never put anything in a theme that isn't within the role of a theme, which is to transform plain data into HTML. In particular do not put anything in there that fetches data. This is extremely wrong ;)
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/389994 | CC-MAIN-2016-50 | refinedweb | 484 | 75.5 |
Spencer Piontkowski
@piontkowski on WordPress.org and Slack
- Member Since: September 18th, 2013
- Location: San Diego, CA
- Website:
Bio
ContributionsSpencer Piontkowski’s badges:
- Core Contributor Core Contributor
- Theme Review Team Theme Review Team
- Plugin Developer Plugin Developer
Committed [1054771] to Plugins Trac:
Updating readme to support 4.1
4 years ago
Committed [996941] to Plugins Trac:
Tested WP Version to 4.0.
4 years ago
Committed [996642] to Plugins Trac:
Tested WP Version to 4.0.
4 years ago
Committed [899746] to Plugins Trac:
Push version 0.6.0. Remote files should not fail with "Remote server did ...
4 years ago
Committed [890348] to Plugins Trac:
Fix invalid file types to not throw fatal errors.
5 years ago
Committed [871492] to Plugins Trac:
Add overall progress bar. Improve how program responds to events like ...
5 years ago
Committed [863750] to Plugins Trac:
Fix issue with namespaces in import file that caused program nto to work ...
5 years ago
Committed [860655] to Plugins Trac:
Add option to delay time between images. Fixed readme.
5 years ago
Committed [858755] to Plugins Trac:
Change readme
5 years ago
Committed [858752] to Plugins Trac:
Adding to repository.
5 years ago
Closed ticket #16107, in Themes Trac:
THEME: GenoFourtheen - 1.0
5 years ago
Closed ticket #16094, in Themes Trac:
THEME: MilkChocolate - 1.2
5 years ago
Closed ticket #16080, in Themes Trac:
THEME: Manatee - 1.0
5 years ago
Closed ticket #16029, in Themes Trac:
THEME: Kimono - 1.0.7
5 years ago
Created a new ticket, #26532, in Core Trac:
Hook Docs: wp-includes/feed-atom-comments.php
5 years ago
Created a new ticket, #26351, in Core Trac:
Hook Docs: wp-includes/plugin.php
5 years ago
Created a new ticket, #26075, in Core Trac:
Hook Docs: wp-admin/media-upload.php
5 years ago
Created a new ticket, #26051, in Core Trac:
Hook Docs: wp-admin/menu-header.php
5 years ago
Attachment Importer
Active Installs: 4,000+ | https://profiles.wordpress.org/piontkowski | CC-MAIN-2018-43 | refinedweb | 327 | 65.52 |
PART 2-NOTIFICATIONS:
In part 1, Connor and I presented our three foundational blocks of Home Automation: Notification, Environmental Awareness, and Actuation. We recommend you read Part 1 before diving into this blog so you have your head around our approach to home automation. You can view it here: Home Automation Mojo You Must Know Part 1
In this blog, we will focus on our preferred IoT Notification tools. It only takes a three to meet every need: Push Bullet, IFTTT, and Alexa. Feel free to use any of this code for the Home Automation challenge! You could win a $100 shopping spree!
PUSH BULLET
Since folks from 5 to 95 years old have a phone in their hand or pocket these days, Push Bullet is the sure fire way to notify a home owner. Push Bullet ( ) is a cross platform internet based notification system. The beauty of it s that you can hit all your devices at once when you send it a notification either from their apps or using their API. So, no matter what device you have in your hand or are near, you will get the notification. Here is its capability:
- Send SMS Text Messages
- Smart Phone Notifications
- Share Links between devices
- Chat with friends
- File Sending
It works with Android, iOS, Chrome, Firefox, Safari, Opera, and Windows. We will use it when we need to urgently notify the home owner.
To use it, we use its API that is intended just for our purpose. We send a client web request with an access token, and it pushes the notification to all our devices. You get 500 notifications a month for free! That would work for home security even in Chicago!
Here is an example using the ESP8266 to send a Push Notification:
#include <ESP8266WiFi.h> #include <WiFiClientSecure.h> const char* ssid = "YOURSSID"; const char* password = "YOURPASSWORD"; const char* host = "api.pushbullet.com"; const int httpsPort = 443; const char* char*); }
On line 7, you see you need your own key. Visit pushbullet.com to get a free account, install the app, and get your key.
IFTTT
If This Then That. What a simple concept! IFTTT.com allows you to connect IoT devices both bought and made. We will primarily make use of the "This" end called Webhooks. Similar to Push Bullet, there is an API that allows you to send parameters as a trigger to the IFTTT service. The API coding is super easy because you are just sending a web client request - basically, just hitting a web page.
Using their web site, you set up custom Webhooks that then trigger other devices. You even can use it to send a Pushbullet notification if you wanted to just stick to the IFTTT API and use IFTTT as a middle man.
Using IFTTT gives you even further flexibility. For example, you could have it trigger a Webhook that turns on all your lights in your home should an intruder be detected. We used it to turn on lights in our home from our video game Son.Light.Sleepwalker in our recent blog 4D IoT Game Engine Blog.
The services have bloomed so much that it takes over a minute and a half to scroll through them all! Below is a video of me doing so:
To set up the trigger timer, we made a video a while back that walks you through creating the Webhooks:
Here is sample code for triggering IFTTT from the ESP8266:
#include "ESP8266WiFi.h" #include "WiFiClientSecure const char* fingerprint = "CF 05 98 89 CA FF 8E D8 5E 5C E0 C2 E4 F7 E6 C3 C7 50 DD 5C"; void setup(void) { } void loop(void) { ToggleLight(); delay(5000); }. client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "User-Agent: ESP8266\r\n" + "Connection: close\r\n\r\n"); // Send the hit to IFTTT.com at the above URL while (client.connected()) { String line = client.readStringUntil('\n'); if (line == "\r") { break; } } String line = client.readStringUntil('\n'); }
From a Raspberry Pi or PocketBeagle, it's even simpler because you can use a simple "curl" system command from C++, Python, or whatever language you choose:
curl -X POST{event}/with/key/{YOURKEY}
ALEXA
Voice is definitely the wave of the future. You can now have Alexa as an app on your phone as well. With it, you can create Routines, which somewhat work like IFTTT, but solely configured by the app. In turn, Alexa can notify you based on triggers of time, change of location, and certified Zigbee automation devices ( ). These triggers will allow Alexa to notify you at any Echo in your home and say what ever you would like it to say.
You can notify Alexa of your custom built IoT device's changed state, too. One approach is to have an ESP8266 to a device that Alexa is familiar with such as a WeMo switch or Phillips Hue bulb. Once added to Alexa's devices, you can update Alexa with the device state (ie, Turned On). You can use this information to in Alexa Skills. However, you can't simply trigger an Alexa routine like a WebHook in IFTTT, but you can do a hack with a speaker to simulate a voice command. Alexa does allow certified Zigbee automation devices trigger a routine, though, but
You could hack an Echo Button to be a detection device. Imagine your back door opening while you are away. Your Echo Button triggers on and tells Alexa. Alexa then says, "Freeze. I'm calling the police and Cuju is waking up!"
Here is example code that will make your ESP8266 emulate a WeMo plug:
Requires this Library:
#include <ESP8266WiFi.h> #include "WemoSwitch.h" #include "WemoManager.h" #include "CallbackFunction.h" // prototypes boolean connectWifi(); //on/off callbacks void lightOn(); void lightOff(); //------- Replace the following! ------ char ssid[] = "yourssid"; // your network SSID (name) char password[] = "yourpassword"; // your network key WemoManager wemoManager; WemoSwitch *light = NULL; const int ledPin = LED_BUILTIN; void setup() { Serial.begin(115200); // Set WiFi to station mode and disconnect from an AP if it was Previously // connected WiFi.mode(WIFI_STA); // Connect Serial.printf("[WIFI] Connecting to "); WiFi.begin(ssid,password); // Wait while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(100); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); IPAddress ip = WiFi.localIP(); Serial.println(ip); wemoManager.begin(); // Format: Alexa invocation name, local port no, on callback, off callback light = new WemoSwitch("test lights", 80, lightOn, lightOff); wemoManager.addDevice(*light); pinMode(ledPin, OUTPUT); // initialize digital ledPin as an output. delay(10); digitalWrite(ledPin, HIGH); // Wemos BUILTIN_LED is active Low, so high is off } void loop() { wemoManager.serverLoop(); } void lightOn() { Serial.print("Switch 1 turn on ..."); digitalWrite(ledPin, LOW); } void lightOff() { Serial.print("Switch 1 turn off ..."); digitalWrite(ledPin, HIGH); }
NEXT STEPS
You now have the code you need to send notifications to your phone from your custom built Home Automation devices. If you made a simple ESP8266 motion sensor and blog on it, there is a strong chance you'd place in the contest! Have fun and we will see you next time when we cover the Home Automation building block Environmental Awareness.
-Sean and Connor
Next: Home Automation Mojo You Must Know Part 3: Environmental Awareness | https://www.element14.com/community/community/project14/homeautomation/blog/2019/01/27/home-automation-mojo-you-must-know-part-2 | CC-MAIN-2020-34 | refinedweb | 1,202 | 65.52 |
What You Will Build
In this tutorial, you will build a public feed app using Django. The app will allow users to post a message that is visible by everyone who comes to the app. You will also learn how to use Auth0 for authentication in your Django application.
For this tutorial, I'll assume you have experience with Django and its standard patterns. For this reason, I won't go in depth about things like setting up a Django app, for example.
In addition to the public-facing part of the app, you will add some moderation utilities to allow mods to both block users and hide posts from the feed. You will use Auth0 to handle the authentication, and you will add the authorization handling within the app to distinguish between the actions that non-users, users, and moderators can take. You will use the default Django admin to allow admin users to promote regular users to be a moderator by adding them to a particular group.
You can find the final code in this GitHub repository.
Requirements
This app will use:
But any Python version greater than 3.6 should work (because of f-strings), and any version over Django 2 should work. If you want to work with an older version of Python, anything over three should work as long you use something other than f-strings for string interpolation.
Build the App
To start, create a directory for the project and create a virtual environment. Once the virtual environment is ready, you can activate it and install Django.
mkdir django-auth0 cd django-auth0 python -m venv env source env/bin/activate pip install django
Now with Django installed, you need to create a project using
django-admin and then you can create an app within that project that will have all the functionality you'll create in this tutorial.
django-admin startproject feed cd feed/ python manage.py startapp feedapp
Open up
feed/feed/settings.py, and add the
feedapp to the list of installed apps.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'feedapp', ]
Before doing anything else, it's a good idea to create a custom user model so you will have the most flexibility when changing the user model in the future. Even though there won't be any of those changes in this simple example, it's always a good idea to create the custom user model before running the first migration. You can place this user model in your
feedapp model because the project will be simple. In a more complicated app, you could place the user model in an app that handles only authentication.
In
feed/feedapp/models.py, add the following:
from django.db import models # ... from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass
Then you need to tell Django you want to use this as the user model. Add the following near the top of the
settings.py file:
AUTH_USER_MODEL = 'feedapp.User'
Now that you have the user model, you can migrate all the default tables. Then, create a super user so you can use the admin dashboard later.
python manage.py makemigrations python manage.py migrate python manage.py createsuperuser
Then you will need to register the user model you created on the admin dashboard. Inside of
feedapp/admin.py, you can register the model.
from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin)
Now that the user model is set up, it's time to move on to the models you will need for the app:
Report. The
Post model will contain the information needed for a post, and the
Report model will handle reports of users that moderators can respond to.
The
Post model will need the following data:
user— who created the post
text— the actual text content of the post
date_posted— tracks when it was created so you can order by posts
hidden— used only when a moderator decides to hide a post
date_hidden— used only when a moderator decides to hide a post
hidden_by— used only when a moderator decides to hide a post
Regarding the last three, moderators won't be allowed to delete any data. Instead, they will only be allowed to hide users, so hidden posts can be tracked and potentially unhidden.
You can go ahead and create that model now in
models.py:
class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.CharField(max_length=280) date_posted = models.DateTimeField(auto_now_add=True) hidden = models.BooleanField(default=False) date_hidden = models.DateTimeField(blank=True, null=True) hidden_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True, null=True, related_name='mod_who_hid') def __str__(self): return self.text
Everything here is normal. The only difference is for creating foreign keys to the user model, you need to use the
settings.AUTH_USER_MODEL to reference the user model instead of importing the model directly. You need to import settings from django.conf at the top of the file.
from django.conf import settings
The other model you need is for making reports. You only need two fields here:
reported_by, where
post refers to the post that got reported and
reported_by is the user who created the report. Like the post model, you will use the
settings.AUTH_USER_MODEL for the table in the foreign key for reported_by. The post's foreign key simply points to the
Post model you just created.
class Report(models.Model): reported_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE)
With the code for the models added, go ahead and make the migrations again and migrate them.
python manage.py makemigrations python manage.py migrate
Finally, add the models to the admin dashboard in
feed/feedapp/admin.py so you can view them on the admin dashboard later.
from .models import User, Post, Report admin.site.register(User, UserAdmin) admin.site.register(Post) admin.site.register(Report)
Now that you have the models done, you can start the scaffolding for the views and then add some templates. You will also create URLs that will connect to the views. Start with the two views that will return HTML, the index view and the reports view, which will allow moderators to see all the posts that have been reported.
First, in
views.py, you need to add the functions for those views. You can return a render function that will have template names passed to it. The templates haven't been created yet, but you can add their names anyway.
from django.shortcuts import render def index(request): return render(request, 'feedapp/index.html') def reports(request): return render(request, 'feedapp/reports.html')
Now that you have the views, add the two templates that you need. Create a template directory with a feedapp directory inside of your feedapp package and then create the two files:
feed/feedapp/templates/feedapp/index.html and
feedapp/templates/feedapp/reports.html. Also, you can create a
base.html template since both templates will have common elements.
Paste the following into base.html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href=""> </head> <body> <section class="hero is-info"> <div class="hero-head"> <nav class="navbar" role="navigation" aria- <div id="navbarBasicExample" class="navbar-menu"> <div class="navbar-start pl-2"> <a href="/" class="navbar-item">Home</a> </div> <div class="navbar-end pr-2"> <div class="navbar-item"> </div> </div> </div> </nav> <div class="hero-body"> <div class="container has-text-centered"> <p class="title">{% block main_title %}{% endblock %}</p> <p class="subtitle">{% block sub_title %}{% endblock %}</p> </div> </div> </div> </section> <section class="section"> <div class="container"> {% block content %}{% endblock %} </div> </section> </body> </html>
Note that you have both title blocks and a content block inside of the base template.
Next, you need the template code for the
index.html. For now, you will have just enough to display the titles. You will fill in the rest later as you add functionality.
{% extends 'feedapp/base.html' %} {% block title %}Home{% endblock %} {% block main_title %}Public Feed{% endblock %} {% block sub_title %}Leave a message for everyone to see!{% endblock %} {% block content %} {% endblock %}
For the reports in
feedapp/reports.py:
{% extends 'feedapp/base.html' %} {% block main_title %}Reported Posts{% endblock %} {% block content %} {% endblock %}
With the views created and the templates for them, the last thing you need to do is add URLs for the views.
You need to create a
urls.py in your
feedapp directory. And in it you need to give paths and combine them with the views.
Paste the following into
feed/feedapp/urls.py:
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('reports/', views.reports, name='reports'), ]
Finally, you will need to modify the existing
feed/feed/urls.py in the main project directory to include the urls from the file you just created.
from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('feedapp.urls')), ]
Now you have a chance to run the server and make sure you don't have any errors. Start the server and navigate to the two URLs you have to make sure you can see blank pages and see the titles in the title bar in the browser.
python manage.py runserver
View your app in the browser at. You'll find the reports page at.
Adding Authentication
Now that everything is working, you want to start adding some functionality to the app. Since you need users to create posts and make reports, you need to allow the concept of a user first. This is where Auth0 comes in. To continue, you will need an Auth0 account. You can sign up for a free Auth0 account here if you don't have one already.
Once you are in your Auth0 account, go to 'Accounts' from the dashboard. There, click on 'Create Application.' Give your app a name, and select "Regular Web Applications". With the app created, you can go to the "Settings" tab to see the information you will need soon to connect the Django app with Auth0. Also, this is the place where you can create some callback URLs so Auth0 can communicate with the app.
For the callback URLs, you can add and to cover both forms of localhost on your machine. For the logout URL, you can just add the base URL: or.
Save the changes once you are done.
With the URLs added, you can go back to the Django app and integrate Auth0. First, you need to install a couple of libraries that will handle the connection:
python-jose and [
social-auth-django](Social Django). You can install those now after stopping the app.
pip install python-jose social-auth-app-django
Social Django will have some URLs, so you need to include them in the project's
feed/url.py file.
path('', include('social_django.urls')),
Since social Django creates some new migration files, you need to migrate the app.
python manage.py migrate
After installing, you need to change some parts of the
settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'feedapp', 'social_django', ] # ..... AUTH_USER_MODEL = 'feedapp.User' # Auth0 settings SOCIAL_AUTH_TRAILING_SLASH = False # Remove trailing slash from routes SOCIAL_AUTH_AUTH0_DOMAIN = '<YOUR-AUTH0-DOMAIN>' SOCIAL_AUTH_AUTH0_KEY = '<YOUR-AUTH0-CLIENT-ID>' SOCIAL_AUTH_AUTH0_SECRET = '<YOUR-AUTH0-CLIENT-SECRET>' SOCIAL_AUTH_AUTH0_SCOPE = [ 'openid', 'profile', 'email' ] AUTHENTICATION_BACKENDS = { 'social_core.backends.auth0.Auth0OAuth2', 'django.contrib.auth.backends.ModelBackend' } LOGIN_URL = '/login/auth0' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/'
You will have to replace the Auth0 domain, key, and secret settings with the values from your Auth0 account. Because your Auth0 client secret should remain confidential, make sure you add this file to your
.gitignore if you plan to push your code to GitHub.
Once you have those settings, you are done with the Auth0 integration. Social Django will handle everything for you. When a user logs in through Auth0, a new record will be created in the user table. That user will then forever be associated with the person who logs in with Auth0 with the same credentials.
So to get the login working, you just need to add a link. You can add it to your homepage. First, you will have to check if the user is authenticated. If they are, you will show a logout link. If they aren't, then you will show the login link, which is the same one in your settings. Add the following to
feedapp/base.html inside the
navbar-end div:
<div class="navbar-end pr-2"> <div class="navbar-item"> <div class="buttons"> <AmpContent> <a class="button is-primary" href="/logout/">Logout</a> </AmpContent> <NonAmpContent> <a class="button is-primary" href="/login/auth0">Login</a> </NonAmpContent> </div> </div> </div>
When you start the server and go to the home page, you should see a single link. Since you are not authenticated yet, you should see the Login link. Click the link and it will take your to the Auth0 universal sign-in. From there, you can sign in with either a Google account by default or your Auth0 account.
If you want to change the methods of authentication, you can do it on the Auth0 dashboard and easily support things like Facebook login, GitHub login, passwordless login, and more without changing anything inside of your app. Auth0 will handle everything related to identity for you. After you sign in, you should be redirected to the index, and you should see the logout link instead of the login link because you are now authenticated.
Now take a look at what happened in the database. Go to the admin dashboard, sign in with your superuser account you created at the beginning, and check out the models. Look at the User model first.
You should see two users: your admin user and a user for the method you just authenticated as. Because you have the email scope, you will already have an email associated with the account. You should notice there is no password available, so this user can never login through the admin dashboard, for example, but that's OK because you want all of the users to authenticate through Auth0.
Now, go back and check out the "User social auths". There, you should see the user you created. This will have a relationship to the user in the User table you just looked at, and it will also list Auth0 as the provider and give you a UID and extra data associated with the service the user authenticated through. As you can see here, Auth0 and Social Django handled everything for you. And as you saw on the index, you have an authenticated user because the logout link is visible instead of the login link. From here, you can treat the user object the same as you would had you created a native Django authentication system.
For the user to log out, you need to create another view that handles logging out. It's more than you had to do to get the user to log in, but as you will see, it's still only a few lines of code. You need to both log out the user in Django itself, and then you need to tell Auth0 you want to log the user out by redirecting to a URL you will craft with some of the settings.
Add the following to
feedapp/views.py:
@login_required def logout(request): django_logout(request) domain = settings.SOCIAL_AUTH_AUTH0_DOMAIN client_id = settings.SOCIAL_AUTH_AUTH0_KEY return_to = '' # this can be current domain return redirect(f'https://{domain}/v2/logout?client_id={client_id}&returnTo={return_to}')
You need to import settings and the logout function to do this. Since the view is called
logout, create an alias called
django_logout for this.
from django.contrib.auth import logout as django_logout from django.conf import settings from django.contrib.auth.decorators import login_required
Finally, create a URL for the logout function in the app's
urls.py file.
path('logout/', views.logout, name='logout'),
You can test the logout link now. You will know it's working when you get redirected to the homepage and you see the login link again.
Now that you have an active user you can work with, start by allowing that user to add a post. In the
index template, between the content block tags, add a form with a textbox to allow the user to add a post. Since you only want authenticated users to add a post, you want to guard the form with a check if the user is authenticated.
<AmpContent> <form method="POST"> <article class="media"> <div class="media-content"> <div class="field"> <p class="control"> {% csrf_token %} <div class="field has-addons"> <div class="control is-expanded"> {{ form.text }} </div> <div class="control"> <button class="button is-info">Submit</button> </div> </div> </p> </div> </div> </article> </form> </NonAmpContent>
With the form created, you need to handle any data that the user submits. First, create a ModelForm for the
Post model. Create a
forms.py file in your
feedapp directory, add the following:
from django.forms import ModelForm, Textarea from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ['text'] widgets = { 'text': TextInput(attrs={'class' : 'input', 'placeholder' : 'Say something...'}), }
Then in the
views.py, in the
index function, you need to add the code to handle a
POST request. You can use the ModelForm to save the form to the database.
The only thing special you have to do here is associate the authenticated user with the post in the database. Don't commit the first save of the form. Instead, add the user first and then save it. After a successful save, you will redirect back to the index, which will use
GET instead of
So, in
views.py, replace the
index function with the following:
from django.shortcuts import render, redirect # update this # ... from .forms import PostForm # add this def index(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return redirect('index') else: form = PostForm() context = {'form' : form} return render(request, 'feedapp/index.html', context)
Be sure to import
PostForm and
redirect, as shown at the top.
Try submitting a few posts, and then go to the admin dashboard to make sure they made it into the database. You should see your user account associated with your Auth0 login associated with the post.
With the posts in the database, you can now add them to the homepage for the global feed. To do that, you need to modify the
index function again. You need to query for all the posts in the database that aren't hidden and then pass that to the template. From there, you can display them.
Update
views.py as follows:
from .models import Post else: form = PostForm() posts = Post.objects.filter(hidden=False).order_by('-date_posted').all() context = {'form' : form, 'posts' : posts}
And in
index.html, add the following:
{% load humanize %} <!-- at the top after extends --> <!-- ... --> <!-- form here --> <!-- ... --> <AmpContent> {% for post in posts %} <article class="media mt-5"> <div class="media-content"> <div class="content"> <p> <strong>{{ post.user.first_name }} {{ post.user.last_name }}</strong> <small>{{ post.date_posted|naturaltime }}</small> <br> {{ post.text }} </p> </div> </div> </article> {% endfor %} </AmpContent> <NonAmpContent> <article class="media"> <div class="media-content"> <div class="content has-text-centered"> <p>There are no posts.</p> </div> </div> </article> </NonAmpContent>
Since you are using humanize to display the date, you need to both load it at the top of the template and add it to the installed apps in
settings.py.
'django.contrib.humanize',
Notice that you are using the first name and last name associate with the user that logged in through Auth0.
If you log out, you will still see the posts, but you will no longer have the option to add a new post.
Now you want to allow the user to delete their own posts as well. To do this, you need another view.
Add the following in
views.py:
def delete_post(request, post_id): # check if post belongs to user post = Post.objects.get(id=post_id) if post.user == request.user: post.delete() # remove it from the database # redirect back to same page return redirect('index')
And then add a URL for it in
urls.py:
path('delete/<post_id>/', views.delete_post, name='delete_post'),
And then in the
index template, check if the post belongs to the user. If so, add a delete link. Add the following in
index.html right outside
<div class="media-content">:
<AmpContent> <div class="media-right"> <a href="{% url 'delete_post' post.id %}" class="delete"></a> </div> </NonAmpContent>
Try deleting one of your posts. If everything works, then it will redirect to the same page with the post you just deleted missing.
Now that you have posts on the site, you want the ability to moderate them. You will allow users to report posts made by other users, and you will then let moderators choose to block a user completely and/or hide their posts.
To get started with this, create a moderator group in the admin dashboard. The moderator group will be given access to change both posts and users and the ability to view reports.
You will use these permissions later in the code to make sure only moderators can perform the action. You can then go into the
users table and give one or more users the moderators group.
With that, add a permission required decorator on the reports view in
views.py. Be sure to also import
permission_required at the top.
from django.contrib.auth.decorators import login_required, permission_required @permission_required('feedapp.view_report', raise_exception=True) def reports(request): return render(request, 'feedapp/reports.html')
This will allow only members in the moderators group to see the reports.
Next, give the users the ability to report posts. You need to create a new view and an associated URL that will handle reporting a post. Then, put a link on each post by someone other than the logged-in user to let that user report post.
Start with the view in
views.py:
from .models import Post, Report def report_post(request, post_id): post = Post.objects.get(id=post_id) report, created = Report.objects.get_or_create(reported_by=request.user, post=post) if created: report.save() return redirect('index')
You don't want to allow a user to create multiple reports for the same post, so use getorcreate on the model.
Next, create a URL for this in
urls.py.
path('report_post/<post_id>/', views.report_post, name='report_post'),
And finally, add the links in the template in
index.html. You can check if the post belongs to the user and if the post has already been reported. Since you already have the
if block for checking a post belongs to a user, add an
else if to check if user is authenticated.
{% elif user.is_authenticated %} <div class="media-right"> <a href="{% url 'report_post' post.id %}"><span class="tag is-warning">report</span></a> </div> </NonAmpContent>
After you test reporting a post, you can check the report table in the admin dashboard to see if it appears. Under "Reports", you should see a Report object. If you click that, you'll see the post and who reported it.
Now go back to the reports view. Here you can list all of the posts in the database that have been reported at least once.
from django.db.models import Count
@permission_required('feedapp.view_report', raise_exception=True) def reports(request): reports = Post.objects.annotate(times_reported=Count('report')).filter(times_reported__gt=0).all() context = {'reports' : reports} return render(request, 'feedapp/reports.html', context)
Since you're about to modify the
reports template, now is a good time to update
feedapp/base.html with a link to the page with the appropriate template. Add the following below the existing link for home:
<div class="navbar-start pl-2"> <a href="/" class="navbar-item">Home</a> <AmpContent> <a href="{% url 'reports' %}" class="navbar-item">Reports</a> </NonAmpContent> </div>
And then in the
reports template, you can display all the reported posts. It will be similar to how the posts are displayed on the home page. But you will also show the number of times the post has been reported.
Replace
reports.html with the following:
{% extends 'feedapp/base.html' %} {% load humanize %} {% block title %}Reported Posts{% endblock %} {% block main_title %}Reported Posts{% endblock %} {% block content %} {% for post in reports %} <article class="media"> <div class="media-content"> <div class="content"> <p> <strong>{{ post.user.first_name }} {{ post.user.last_name }}</strong> <small>{{ post.date_posted|naturaltime }}</small> <AmpContent> <a href="{% url 'block_user' post.user.id %}"><span class="tag is-warning">Block</span></a> </NonAmpContent> <br> {{ post.text }} - Times reported: {{ post.times_reported }} </p> </div> </div> <AmpContent> <div class="media-right"> <a class="delete"></a> </div> </NonAmpContent> </article> {% endfor %} {% endblock %}
Now that the moderators can see reported posts, you want to allow the moderator to block users and hide posts. Start with hiding posts. You can create a view that requires a change post permission. From there, you will get the post and hide it by updating the
hidden,
date_hidden, and
hidden_by fields on the post. You will need the
datetime object to get the current date.
Add the following to
views.py:
@permission_required('feedapp.change_post', raise_exception=True) def hide_post(request, post_id): post = Post.objects.get(id=post_id) post.hidden = True post.date_hidden = datetime.now() post.hidden_by = request.user post.save() return redirect('reports')
Then you need a URL for this view in
urls.py.
path('hide_post/<post_id>/', views.hide_post, name='hide_post'),
Finally, add the link in the template at the bottom of
reports.html. Check if it has been hidden already so you don't hide it more than once.
<AmpContent> <div class="media-right"> <a href="{% url 'hide_post' post.id %}" class="delete"></a> </div> </NonAmpContent>
After hiding a post, you can verify by checking the homepage and seeing the post is no longer there because of the query you wrote earlier to check for
hidden=False.
The other thing you want a moderator to do is block a user. When you block a user, you want to both set a user to be inactive, and you want to hide all of their posts. Create the view for this in
views.py:
from .models import Post, Report, User # import User from django.contrib.auth import get_user_model # add to the imports @permission_required('feedapp.change_user') def block_user(request, user_id): User = get_user_model() user = User.objects.get(id=user_id) for post in user.post_set.all(): if not post.hidden: post.hidden = True post.hidden_by = request.user post.date_hidden = datetime.now() post.save() user.is_active = False user.save() return redirect('reports')
Then add a URL for this view:
path('block_user/<user_id>/', views.block_user, name='block_user'),
And finally you can add the link on the reports template. Make sure the user hasn't been deactivated before.
<AmpContent> <a href="{% url 'block_user' post.user.id %}"><span class="tag is-warning">Block</span></a> </NonAmpContent>
Then you can test blocking a user. You can verify all their posts are gone.
Django Authentication vs. Auth0
How does the default authentication for Django compare with Auth0? For one, the default authentication focuses on hashing passwords locally and only allowing a user to login with a username and password. For all the apps that use this type of authentication, it works fine, but Auth0 gives you some advantages over the default Django authentication.
Acts as the authorization server
Even though Auth0 handles the actual credentials for your users, the user data is still stored in your app's database. So your user table will still have a user for each person who signs up with Auth0. But in addition to the user table, you will have three extra tables from Python social auth:
associations,
nonces, and
user social auths. Only one table is primarily used:
user social auths. This stores both the provider information (Auth0) and the access token for the user.
Handles different social providers
So Auth0 will stand between your users and whatever social auth they choose to use. Then they will be redirected to sign in with the social platform of choice (so you don't have to support their choices), and then the auth token for that user will be passed back to the app. This allows you to ignore integrating access to every social provider because Auth0 has already handled it for you. Otherwise, you'd have to do things like get an Oauth token for each individual social platform you want to support for auth.
Handles login page
If you use the default process for Django authentication, you will need to customize the login. Even though Django gives you the tables in the database, a way to hash passwords, and a way to associate data with a user, you will have to write this yourself. You will need to create the views and templates for the login-associated pages. Also, if you want to implement alternative forms of authentication, like social login and passwordless login, you will need to add the code yourself.
With Auth0, you simply connect your account, and Auth0 will handle all of the authentication stuff for you. You just rely on Auth0 to identify your users through authentication. This obviously saves a ton of time because you don't need to write the same code over and over again. Login code is both common to every app yet easy to mess up, so by using Auth0, you will save a ton of time authenticating with your app. Also, you can change how your app handles authentication at any time through the Auth0 dashboard. For example, if you want to add a new social provider, you can do it within minutes on the dashboard instead of writing any code in your app to handle a new social login.
Easily integrates with Django
Even though Auth0 will handle the identity part of your app, you can still work with a user once they're identified, just as if they signed up and logged in with your Django app directly. Since each user becomes a regular user, you can do things like add that particular user to a group on the admin dashboard to authorize them to use more features within your app.
Even though you can use Auth0 to allow your users to authenticate in any way they wish, you can also continue the use the default Django authentication alongside. The end result is the same with both processes: a user is created in the database, and a cookie is created to represent that user. Though in this tutorial, you will use Auth0 exclusively for the app's users and keep the default authentication for the admin users.
Conclusion
That's everything we wanted for the app. You have the feed app that allows users to create posts and moderators to make sure things don't get out of hand. Here is what you covered:
- Set up Auth0 to handle Django authentication
- Use Python social apps to store your users' tokens and account information
- Create an authorization system for different user types through roles
Let me know if you have any questions in the comments below. | https://auth0.com/blog/django-authentication/ | CC-MAIN-2021-43 | refinedweb | 5,225 | 57.27 |
Created on 2008-12-08 21:27 by legerf, last changed 2009-07-02 23:57 by amaury.forgeotdarc. This issue is now closed.
Under Debian/Lenny, with Python3.0.final install from the tarball, any
user can't import lib-dynload, launch IDLE ... but local root can do them.
When I login in root and run "chmod -R o+rx /usr/lib/python3.0/*", users
can use normaly python3.0.
Install detail : "configure --with-pydebug --with-doc-strings
--enable-shared --enable-profiling --enable-ipv6 --with-threads
--with-tsc --prefix=/usr ; make ; make test" and after "make altinstall
> altinstall.log 2>&1". I join altinstall.log.
My root umask = 0027 (hardened system), so the altinstall/install script
don't manage umask parameter.
I'm able to reproduce the bug with umask set to 0027:
drwxr-x--- 2 root root 3072 déc 8 22:59
(...)/lib/python3.1/lib-dynload
With umask 0077, it's:
drwx------ 2 root root 3072 déc 8 22:59
(...)/lib/python3.1/lib-dynload
The problem is specific to this directory.
install() method of the install_lib command
(Lib/distutils/command/install_lib.py) calls self.copy_tree() which
calls copy_tree() from Lib/distutils/dir_util.py. By default, this
function preserve the modes (perserve_mode=1 by default). Or the build
created a directory with permissions "drwx------".
I wrote that only lib-dynload directory has a problem. But other files
are install with permissions -rw-------:
- .../lib/python?.?/*.{pyc,pyo}
- .../lib/python?.?/lib2to3/PatternGrammar*.pickle
- .../lib/python?.?/lib2to3/Grammar*.pickle
- .../lib/python?.?/lib-dynload/Python*.egg-info
With Python trunk, the directory has the right permission (drwxr-xr-x)
whereas build/lib.linux(...) has permission
drwx------.
But the problem is still open for listed files
(.pyc, .pyo, .picle, .egg-info).
Gotcha! os.path.walk() was replaced by os.walk() but walk() argument is
no more a callback because walk() is a generator! Here is a fix.
The patch is fine.
If it were me, I'd change os.walk to accept keyword-only arguments:
def walk(top, *, topdown=True, onerror=None, followlinks=False):
...
Hum, there is not fixer for 2to3. But I might be hard to write such
fixer because walk() generates (dirpath, dirnames, filenames) instead
of (dirpath, filenames).
Python2 prototype:
os.path.walk(path, visit, arg) -> None
with visit: callback(arg, dirpath, filenames)
Python3 prototype:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]]) ->
generator
with onerror: callback()
the generator produces (dirpath, dirnames, filenames)
Example:
os.path.walk('Lib/xml/', callback, 42)
can be replaced by
for dirpath, dirnames, filenames in os.walk('Lib/xml/'):
callback(42, dirpath, dirnames + filenames)
About the keyword only: +1 (or +2 :-)).
Index: Lib/os.py
===================================================================
--- Lib/os.py (révision 67652)
+++ Lib/os.py (copie de travail)
@@ -192,7 +192,7 @@
__all__.extend(["makedirs", "removedirs", "renames"])
-def walk(top, topdown=True, onerror=None, followlinks=False):
+def walk(top, *, topdown=True, onerror=None, followlinks=False):
"""Directory tree generator.
For each directory in the directory tree rooted at top (including
top
amaury> The patch is fine.
Cool :-) Anyone to commit the fix? Maybe, tarek?
amaury> If it were me, I'd change os.walk to accept
amaury> keyword-only arguments:
amaury> def walk(top, *, topdown=True, onerror=None,
amaury> followlinks=False):
amaury> ...
I like the idea but it should be proposed in a new issue :-) I
proposed an API change for open() (issue #4121) but it was rejected by
Guido:
"(...) Beyond 3.0, I'm still rather reluctant -- I expect most users
will be wise and use keyword args anyway; I'm not sure what we buy by
forcing this. (...)"
But walk() is a different case than open().
ping
Ok, fixed in r73788 and r73789. | http://bugs.python.org/issue4601 | CC-MAIN-2014-41 | refinedweb | 608 | 61.22 |
On Sep 9, 4:41 am, News123 <news1... at free.fr> wrote: > On 09/09/2010 12:29 AM, CM wrote: > > > On Sep 8, 1:09 pm, Stef Mientki <stef.mien... at gmail.com> > > > I do the same thing--good to hear from John that keeping it open is > > OK. > > > But another question that this provokes, at least for me is: what > > happens when you call .connect() on the same database multiple times > > from within different parts of the same app? Is that bad? And is it > > that there now multiple connections to the database, or one connection > > that has multiple names in different namespaces within the app? > > CM, > > Do you talk about a multithreaded environment? > or only about an environment with logically separate blocks (or with > generators), > and multiple objects each keeping their own connection. More the latter. My calls to make a connection to the database are from within different classes that serve different aspects of the GUI. I have something like an anti-MVC pattern here, like ravioli code, where each GUI element gets what it needs from the database. They are all running in the main GUI thread. There is also, though, a wxPython timer (wxTimer) that will occasionally initiate a read or write to the database, though it will already have an open connection. Why? How would this matter? > As far as I know sqlite can be compiled to be thread safe, but is not > necessarily be default. > No idea about the library used b python. I haven't dealt with the issue of thread safety before, haven't thought about it really. > I personally just started sqlite in one of my apps with multithrading > and in order to be safe I went for the conservative approach > connect, perform transactions, commit and close. > However this is probably overkill and later in time I might also ty to > keep connections open in order to increse performance. So far the "many calls to .connect() approach" has not seemed problematic for my app. But I have nothing to compare it to. Che | https://mail.python.org/pipermail/python-list/2010-September/587042.html | CC-MAIN-2016-36 | refinedweb | 344 | 73.78 |
I'm very new to Java and we have a project to calculate PI. Here is my prompt:
Determining π Experimentally:
Recall that π is the ratio of a circle's circumference to its
diameter and that we can calculate the area of a circle with the
formula A=πr2. Below is a circle enscribed within the unit
square.
What is the ratio of the areas of the enscribed circle to that of
the unit square?
If we pick a random point within the unit square what is the
probability that the point will also lie within the circle?
If we repeat this experiment an arbitrarily large number of times the
ratio of the number of points which lie within the circle to the number
of points within the unit square (all of them) will approach π/4.
Using the language structures we have discussed write a program that
will do the above experiment an arbitary (determined at run-time)
number of times and report back the approximate value of π.
---------------------------------------------------------------------------------
I did the program but for some reason, everytime I run it, I get a different value even if I type in the same number of repeats. Here is my code:
import java.util.*; public class PI { public static boolean isInside (double x1, double y1) { double distance = Math.sqrt((x1 * x1) + (y1 * y1)); return (distance < 1.0); } public static double computePI (int numRepeats) { Random randomGen = new Random (System.currentTimeMillis()); int repeats = 0; double PI = 0; for (int i = 1; i <= numRepeats; i++) { double x1 = (randomGen.nextDouble()) * 2 - 1.0; double y1 = (randomGen.nextDouble()) * 2 - 1.0; if (isInside(x1, y1)) { repeats++; } } double dRepeats = numRepeats; PI = (4.0 * (repeats/dRepeats)); return PI; } public static void main (String[] args) { Scanner scan = new Scanner (System.in); System.out.print("Please enter number of times you would like to run this program: "); int numRepeats = scan.nextInt(); double PI = computePI(numRepeats); System.out.println ("Computed PI = " + PI); } }
I'm really confused because I don't understand what I'm doing wrong. If someone could help me, I'd really appreciate it! | http://www.dreamincode.net/forums/topic/65095-calculating-pi-in-java/ | CC-MAIN-2017-39 | refinedweb | 347 | 56.76 |
The objective of this article series is to give a quick overview of Behaviors, Triggers and Actions in Silverlight and WPF. Together, they enable a great deal of design time interactivity for your UI. They also make possible re-use and re-distribution of interaction logic. This is the second article in the series, and I’ll explain about Triggers and Actions. Also, we’ll explore how to create custom triggers.
- Part I - Behaviors, Triggers and Actions in Silverlight And WPF Made Simple – Behaviors
- Part II - Behaviors, Triggers and Actions in Silverlight And WPF Made Simple – Triggers (this one)
Note: You need Expression Blend 4.0
The completed source code for this exercise is available
Triggers and Actions – Scratching the Surface
A Trigger can invoke a set of Actions, when it is fired. For example, you can nest few actions (like PropertyChangeAction to change a property of an element) in an EventTrigger, so that those actions will get executed when a specific Event occurs. You can attach more than one trigger to an element.
If you have some WPF background, you may quickly remember the DataTriggers, MultiDataTriggers etc.
There are various Triggers and Actions that comes ‘out of the box’, residing in System.Windows.Interactivity and Microsoft.Expression.Interactions
- Triggers – EventTrigger, TimerTrigger, StoryBoardCompletedTrigger, KeyTrigger etc.
- Actions - ChangePropertyAction, ControlStoryBoardAction, PlaySoundAction etc.
Let us start playing with some of the existing triggers and actions.
1. Set The Stage - Create a new Silverlight Application Project in Blend (as explained in my previous post). You’ll see the design surface of MainPage.xaml by default. This time, select the Ellipse tool from Blend toolbar, to draw a ball to the design surface. Give some nice color as well :)
Also, at this point, click View->Active Document View->Split View – So that you can view the Xaml along with the designer.
2. Attach a Trigger and Action to an object – Go to the Assets pane in Blend, and click the Behaviors link. Drag the ChangePropertyAction to the ellipse you added, and have a look at the XAML. You’ll find that Blend automatically added an EventTrigger for you with MouseLeftButtonDown as the default event, and sandwiched your ChangePropertyAction inside the same.
Select the ChangePropertyAction in the Xaml Editor or in the Object and Timelines window. Have a look at the properties Window in blend, to see the properties of your Trigger and Action (See the image below). By default the trigger will be fired for the MouseLeftButtonDown event of our ball. Also, you may note that presently we havn’t specified any parameters for the ChangePropertyAction.
3. Modifying ChangePropertyAction
Now let us squeeze our ellipse a bit by changing the Width property of our Ellipse - when the MouseLeftButtonDown happens. For this, go to the properties window, and
1. Change ‘PropertyName’ parameter of our ChangePropertyAction to ‘Width’.
2. Set the the value to 200 so that Width will increase to 200 when the Action is invoked
3. In the Animation Properties of ChangePropertyAction, set the duration to 4 seconds, and change the Ease property to Elastic Out.
We are done. Run the application, by pressing F5 and move click over the Ellipse. And you’ll see a bit of fun.
Play around with this a bit, to understand how the Triggers and Actions work together. And once you are back, scroll down to read further – about creating our very own Triggers and Actions
Creating a Custom Trigger
Time to go under the skin. Then, we’ll replace the ‘EventTrigger’ we used in our above example with the custom trigger we are creating, to stretch the ball!!.
First, let us create a minimal custom trigger – named KeyDownTrigger, that’ll be fired each time when a key is pressed. Let us continue from where we left our above project.
Step 1 – Create a Trigger: In Blend, right click your project in the Projects pane, and click ‘Add New Item’, to bring up the New Item dialog box. Select ‘Trigger’ from there, give the name ‘KeyDownTrigger’ and click OK.
Step 2 – Add some meat. Have a look at the New trigger class that got added to your project. You’ll find that our Trigger class is inherited from TriggerBase<T> in System.Windows.Interactivity. Also, have a look at the override methods, OnAttached and OnDetaching (and the comments below them). Let us add some meat to the code you already see there. Modify the code to this.
Tip: If you have Visual Studio 2010 Beta installed, you can right click on a file in Blend 4.0 project explorer, and click ‘Edit in Visual Studio’ at any point of time, if you prefer writing code in VS rather than in Blend.
public class KeyDownTrigger : TriggerBase<FrameworkElement> { protected override void OnAttached() { base.OnAttached(); // Insert code that you want to run when the Trigger is attached to an object. this.AssociatedObject.Loaded += (sender, args) => { Application.Current.RootVisual.KeyDown += new KeyEventHandler(Visual_KeyDown); }; } protected override void OnDetaching() { base.OnDetaching(); // Insert code that you would want run when the Trigger //is removed from an object. Application.Current.RootVisual.KeyDown -= new KeyEventHandler(Visual_KeyDown); } //A property for the trigger so that users can specify keys //as comma separated values public string Keys { get; set; } //Invoke the actions in this trigger, if a key is in the list void Visual_KeyDown(object sender, KeyEventArgs args) { var key = Enum.GetName(typeof(Key), args.Key); if (Keys.Split(',').Contains(key)) InvokeActions(key); } }
The code is self explanatory, but here is basically what we are doing there. When the Associated object is loaded, we hook up to the KeyDown event of the Root visual element. And when KeyDown is fired, we Invoke the Actions inside this trigger, if the key is entered by the user.
Step 3 – Associate the KeyDownTrigger to our Ball.
In Blend, click Project->Build Project menu. Now, go back to our MainPage.xaml where you have your ball. As we did earlier, Select the ChangePropertyAction in the Xaml Editor or in the Object and Timelines window, to bring up the Properties Window - as we did earlier. In the Properties window, Click the ‘New’ button against the TriggerType, in the Trigger Pane (see the image). In the resultant dialog box, select the ‘KeyDownTrigger’ we recently added, and click OK.
Now, you’ll see that the ‘EventTrigger’ we had there earlier, got replaced with the ‘KeyDownTrigger’. Note that the ‘Keys’ property we added to our Trigger class is visible in the Blend UI - so that some one who may use our trigger can enter the values there to specify what all keys should invoke the actions inside the trigger. Just enter few key names with out spaces (let us say A,B,C) to the Keys field.
Step 4 – Salvation
Cool, we are done. Press F5 and run your project. Click on the surface to bring focus, and press A,B or C to see the ball getting stretched. Woot!! We just created and implemented a minimal trigger. | http://www.amazedsaint.com/2010/01/behaviors-triggers-and-actions-in_24.html | CC-MAIN-2018-47 | refinedweb | 1,159 | 64.71 |
Virtual Consoles are a key feature of Linux (and FreeBSD etc) and possibly the most undersold feature of the whole operating system. You get the same effect as a screenful of xterms, without running up a X11 server!
When the any Unix system first boots up, you get a normal
Unix
login: prompt, so you can log in, and start X11 or do
whatever else you would do with a single Unix shell.
Linux is pretty much the same, except that instead of just
one such
login:, you get several. These are accessed using the
2-key combinations <ALT><F1>,
<ALT><F2>,
<ALT><F3> etc.
Each of the "screens" with you see is known as a "Virtual Console".
Apart from the fact that you use the same screen and keyboard, each virtual console is quite independant of the others. It's a lot like having several VT100-terminals connected (except that it's much easier to switch between them). This point is emphasised by the fact that each console has it's own CAPS LOCK, NUM LOCK and SCROLL LOCK states, and this is reflected in the LED's too.
Try it: if you set CAPS LOCK on in one console, and then switch to another, the led goes out, and you're back to lower case. When you switch back, presto, you're back in CAPS LOCK mode.
Virtual Consoles have one feature which you just can't get on a regular VT100 terminal: mouse support.
Most Linux systems come bundled with a program called gpm
This allows you to copy and paste text within a console, and even
between different consoles. By default, the buttons are usually
set up to mimic those of an Xterm.
(Left=select, Middle=paste, Right=adjust).
The gpm program used to be called "selection".
The problem with having a program like gpm which reads the mouse-device, is that you cannot have more than one such program running at a time. So if, for example, you are running gpm, and want to run X11 (which also reads the mouse device), you are in trouble. Or rather, you used to be in trouble.
The current release of gpm supports a Repeater Mode where it will write
mouse-data to a named pipe,
/dev/gpmdata in addition to
it's normal operation. Any other program, such as an X11 server,
can be read this pipe as if it were a regular mouse-device.
To utilise this feature, you should:
"Pointer"section your XF86config:
Protocol "MouseSystems" Device "/dev/gpmdata"
Gpm also gives you one more important feature: Multiple Mode
the -M parameter.
This lets you can merge input from multiple, different mouse devices.
This is particularly useful if you have a laptop computer with some exotic but frustrating pointing device, and want to connect a normal serial mouse whenever possible. Running gpm means you can do this without having to edit config files every time you change pointers.
The combination of gpm and virtual consoles is very much like having a X11-server and an number of xterms - so much so that you may not want to start up X11 at all!
The only problem with having a lot of virtual consoles is that you can get lost. There are two things I like to do to distinguish virtual consoles.
The login message consists of a banner which put up by the
getty program (or
mgetty or
agetty etc), plus the login-prompt supplied by the
login program.
The banner which is supplied by
getty consists of the
contents of the file
/etc/issue.
This file may also contain "escapes". These allow us to include
some variable-text in the
/etc/issue file, such
as the hostname, or (you guessed it) the tty name.
If you are using
agetty,
use
\l to insert the tty name.
If you are using
mgetty,
use
@L to insert the tty name.
For example, you /etc/issue file make look like this:
Welcome to \l on \n
See the man page for your getty program for details of
escapes which may be used in
/etc/issue
The linux console also supports escape sequences for rendering
color text. These are used by the command
ls --color
These escape sequences are common to both linux consoles and
(color) xterms, so we can use the same prompt for both environments.
The complete range of escape sequences supported by the console
is described in the man page
console_codes(4)
The following line, when included in, say,
/etc/csh.cshrc
will set a color-prompt for the tcsh:
set prompt = "%{\e[0;3${tty:s/tty//:s/p//}m%}%n@%m %C2 %\! %#%{\e[0;0m%} "However, for the sake of completeness, we'll include some provision for xterm-escapes, too.
if ( $?tcsh ) then if ($term == xterm ) then set xterm_hdr = '\e]2\;%m:%/\a\e]1\;%c\a' else set xterm_hdr endif set color_s = "\e[0;3${tty:s/tty//:s/p//}m" set color_e = '\e[0;0m' set prompt = "%{$xterm_hdr$color_s%}%n@%m %C2 %\! %#%{$color_e%} " unset xterm_hdr color_s color_e endif
Similarly, for bash, you can use the following in
~/.bashrc
if [ "$BASH" != "" ]; then if [ "$TERM" == "xterm" ]; then XTERM_HDR='\e]2;\h:\w\a\e]1;\W\a' else XTERM_HDR='' fi TTY="`tty`" COLOR_S="\e[0;3${TTY/*[^0-9]/}m" COLOR_E='\e[0;0m' PS1="\[$XTERM_HDR$COLOR_S\]\u@\h \w \\! \\$\[$COLOR_E\] " unset XTERM_HDR COLOR_S COLOR_E fi
So far, we've only considered virtual consoles as being additional login terminals. By default, this is the way they are setup. In fact, virtual consoles can be used for other things, too.
One of the best uses for spare virtual consoles is to display system messages. The Unix system generates quite an array of possible messages, most of which are sent to the syslog facility. These messages may be anything from a simple information message that a particular kernel-module is being loaded or unloaded, to important notices, such as "the system is going down".
The syslog is handled by a deamon,
syslogd which
controls the distribution of these messages based on their facility
and priority. The
syslogd reads the file
/etc/syslog.conf to determine how to distribute these messages.
The priority is an indication of the "urgency" of a message. The following eight priorities are defined (in order of priority):
emergor
panic
alert
crit
erroror
err
warningor
warn
notice
info
debug
syslogdgenerally treats priorities as meaning "equal or greater than" the stated priority. Consider the
/etc/syslog.confentry:
*.error /var/log/error.log
This will log messages from all facilities which have a priority of
error or greater to the file
/var/log/error.log
If we wanted only the messages with priority error (and not the higher priority messages), we could specify:
*.=error /var/log/error.log
The "facility" of a message is a means of categorising messages, so that we can divide them into "broad areas of interest". The following facilities are defined:
auth
authpriv
cron
daemon
kern
lpr
news
security
syslog
user
uucp
local0
local1
local2
local3
local4
local5
local6
local7
Facilities are specified explicity. There is no "heirarchy" of facilities, like there is for priorities. ie
mail.warning /dev/tty10
refers to messages of priority warning or higher,
but only for the facility
/etc/syslog.conffile
It is quite simple to divide our different syslog messages amongst a
number of different, otherwise unused, virtual consoles.
I like to use tty9-tty12 for this purpose, as it doesn't interfer
with my normal "login" consoles on tty1-tty6, or the default X11 console, tty7
Note also, that directing messages towards virtual consoles does not
divert these messages away from log files. The
syslogd lets you
direct messages as many (multiple) destinations as you ,like.
Here's an example of some useful additions to your default
/etc/syslog.conf:
daemon.info /dev/tty9 kern.info /dev/tty10 *.info;daemon.none;kern.none;auth.none;authpriv.none \ /dev/tty11
Don't forget to 'kill -1' your
syslogd after changing
syslog.conf
I have been told that, when directing syslog output directly to
a tty like this, that pressing
^S or
Scroll Lock
in the tty can "block" the syslog daemon, and any daemons which
subscribe to the syslog service. I haven't had the problem myself,
probably because I rarely use
Scroll Lock.
Caution is advised, particularly if your system is being used in a
multi-user role. Using
tail -f logfile may be preferable,
although it would be more complex to set up.
You may notice that, by default,
/var/log is not
world-readable. This is because log files can contain security-sensitive
information, especially if debugging is turned on.
One example of happens when you type an incorrect password during login.
This results is a message to the syslog, notifying of the bad login attempt,
and quoting the userid. If it just so happens that you've pressed
Enter
once too often, you may end up entering your password in the userid field.
Some versions of
login may log this faithfully - and your password inadvertently
ends up in a log file! Or, just as bad, in plain view on a virtual console!
So, convinient as it is to log messages to virtual consoles, it is important to be aware of what kind of information is openly visible on your virtual consoles. This applies particularly if your computer is being shared amongst several users, or is located anywhere other than a locked room.
Adding things like
auth.none;authpriv.none (in the above example) allows
us to keep sensitive information out of plain sight. Likewise, it's best
not to display
debug messages, unless you are actively debugging
your system.
Given that there are 8 "spare" facility categories (
local0-7),
it would be nice if we could, for example, devote one virtual console to
the tcpd messages, and another to ppp mesages, etc.
Unfortunately, most programs are hard-wired to report their
messages to a specific facility (eg daemon). This means that
you would need to recompile the program in question in order to make it
use a different syslog facility.
By default, most Linux systems are set up to run only
getty or xdm processes on virtual consoles. There
is no technical reason why you can't run something else.
For example, if you just want to run top, so that it's always "there",
right from boot-up, you just have to modify your
/etc/inittab
to include a line like this:
5:2345:respawn:/bin/open -c 5 -w -- /usr/bin/top -s
Which will run
top on tty5. Don't forget to 'kill -1'
the
init process after modifying
/etc/inittab.
Note in particular the use of the -s flag on top. This put top into "secure mode". This mode disables the interactive commands 'kill' and 'renice'. This makes it "safe" to run in this mode. Without the '-s' flag, anyone could walk up to the computer and use top to kill other people's processes.
The "secure mode" of top is just ideal for running top in this way.
The biggest problem starting processes from
init (as we did the
above example) is that the process runs with the userid root.
This is not a problem for programs like
getty, which are designed
to run as root, and
top, which has a special mode for this case.
But what do we do when we want to run something that wasn't designed for this kind of thing? There is a solution, though it's not a pretty one.
Let's say that we want to run a
lynx web-browser in the same way as we have done
with
top.
Lynx does not have a "secure-mode". It can write files to the disk, and can even
spawn shells (using the ! keystroke).
One solution is to run lynx as another user (other than root) by using:
6:23:respawn:/bin/open -c 5 -w -- /bin/su nobody --command="/usr/bin/lynx"
This runs lynx as user "nobody", by executing it via the su program.
Even this may be considered "insecure", as lynx is capable of "escaping"
to an
sh(1) shell (using the ! keystroke). Once an "unfriendly" has access to
a shell, they have a "foot in the door", and can hunt for any weak-spots in
your system's security.
The best solution is to isolate such "anonymous" users, in the same
way that the ftpd does with it's anonymous users. That is, by
using
chroot to isolate them in a subdirectory.
First, we create a minimal directory tree where our program can run:
mkdir /home/sandpit mkdir /home/sandpit/bin cp /usr/bin/lynx /home/sandpit/bin cp /bin/su /home/sandpit/bin mkdir /home/sandpit/etc cat <<EOF > /home/sandpit/etc/passwd root:*:0:0:root:/root:/bin/bash lynxuser:*:65534:65534:lynxuser:/:/bin/lynx EOF cat <<EOF > /home/sandpit/etc/group root:*:0:root EOF cat <<EOF > /home/sandpit/etc/hosts 127.0.0.1 localhost EOF cat <<EOF > /home/sandpit/etc/host.conf order hosts EOF mkdir -p /home/sandpit/usr/lib/terminfo/l cp /usr/lib/terminfo/l/linux /home/sandpit/usr/lib/terminfo/l
Next we copy the files needed to run our program into our newly created directory tree, and set up the most restrictive permissions we can.
cp /etc/lynx.cfg /home/sandpit/etc mkdir /home/sandpit/lib cp /lib/ld-linux.so.1 /lib/libc.so.5 /home/sandpit/lib cp /lib/libm.so.5 /usr/lib/libslang.so.0.99.34 /home/sandpit/lib chown -R root.root /home/sandpit chmod -R go= /home/sandpit chmod a+x /home/sandpit /home/sandpit/* /home/sandpit/bin/* chmod a+r /home/sandpit/etc/* /home/sandpit/lib/* chmod -R a+rX /home/sandpit/usr
Note: you may require slightly different runtime libraries
for your particular version of
lynx.
Now we can safely spawn a lynx browser from
init, without compromising
our system security. Our inittab entry would look like this:
6:23:respawn:/bin/open -c 6 -w -- /usr/sbin/chroot /home/sandpit /bin/su lynxuser
open(1)command
If you like the idea of virtual consoles, but do not like going through
the login process more than once, the
open command if for you.
The
open command starts a new shell on the next available
virtual console, without giving a login prompt first.
This is not a security risk, as you have to login before you can use the
open command in the first place.
The only complication arises from what is considered the "next available"
virtual console. If a getty is being run on a console, it is unavailable.
Likewise, if you are logging syslog messages to a console, it is also
unavailable. So, if you are using the
open command a lot,
you may wish to disable some of the getty processes in your
/etc/inittab file.
(Note: I had to start both
top and
lynx
by way of the
open command,
since they had a tendancy to use the wrong tty if I just ran them
directly from init)
A number of different fonts are available for virtual consoles, and these are to be found in the directory:
/usr/share/consolefonts -- or -- /usr/lib/kbd/consolefonts
and are invoked by the program:
setfont
Note that there some fonts have different pixel dimensions.
If you are running in EXTENDED VGA mode (ie by using the
boot paramter "
vga=2"), you will get an 8x8 font (which has quite
ugly descenders).
A better option is to use some of the SVGA modes that your video
card may support. First, you should boot your system, specifying
vga=ask. Then try the different modes one by one,
until you find one that suits you.
After booting up in a particular mode, you may want to "save" that mode by using the command:
restoretextmode -w COLSxROWS
This will save the parameters of the current video mode in the
file named
COLSxROWS, such that you can switch back to that mode
without rebooting, by using:
restoretextmode -r COLSxROWS
You will still have to go through the boot-it-and-see process at least once for each video mode.
Once you have a suitable set of video mode files, named according
to the
COLSxROWS convention, you can use the
command:
resizecons COLSxROWS
This will invoke
restoretextmode and
invoke the appropriate
stty command to ensure that the
tty driver is "aware" of the new size. (Try changing from an
80-column mode to an 132-column mode using just
restoretextmode,
and you'll see what I mean).
The default keyboard map in the Linux console is defined by the file:
/usr/src/linux/drivers/char/defkeymap.mapHowever, it is not necessary (or desirable) to edit this file directly.
If you want to load a completely new map (such as a dvorak keymap) you only have to use the command:
loadkeymap /usr/share/keytables/dvorak.map
There are numerous different keymaps already available, including
all the common European ones. Use the
dumpkeys command to view
the current keyboard map.
If you just want to change a few keys, you should use the command
loadkeys
For example, if you have a 104-key keyboard, you will have the special "windows" keys. You can put these to good use, by mapping them onto special functions.
loadkeys - << EOF keycode 125 = Decr_Console # Left ~# key keycode 126 = Incr_Console # Right ~# key EOF
This will remap the left and right "windows" keys, such that
they will step through the range of virtual consoles which
have been activated. To find out what the keycodes are for
any given key, use the command
showkey
The other situation you may encounter is that you have some keys on your keyboard which do not generate a keycode when pressed. For example, I have a "multimedia" keyboard, which has 12 rubber buttons in addition to the 104-keys. With the default keyboard mapping, these do not generate keycodes at all. We can assign them keycodes, but first we have to find out what codes the keyboard is sending out. This is done using the command:
showkey -s
This will tell us the "scancodes" generated by our unmapped keys. Each key generates a one- or two-byte scancode when it is pressed. When the key is released, it sends the same code, but with the most significant bit set (for two-byte codes, the MSB is set on the second byte).
Next, we have to assign the scancode to a keycode. This is done
using the command
setkeycodes. This requires some care,
as it is not obvious which keycodes are actually free for use.
You can get some idea by looking in the
defkeymap.map
file. All the keycodes up to 83 are in use. Above that, some are
used, some aren't.
For my multimedia keyboard, I use the following command to set up the keycodes:
#!/bin/sh # # front<->back www Calculator Xfer # alt-shift-tab e032 e021 e023 # 120 121 122 # # |<< |>|| [] >>| # e010 e022 e024 e019 # 92 93 94 95 # # Coffee Menu Mute Vol- Vol+ # e07a e026 e020 e02e e030 # 123 124 89 90 91 # setkeycodes e010 92 e019 95 e020 89 e021 121 \ e022 93 e023 122 e024 94 e026 124 \ e02e 90 e030 91 e032 120 e07a 123
Once I have assigned keycodes, I can map the keys to some of the special keyboard functions, or arbitrary characters or strings.
loadkeys - << EOF Alt ShiftL keycode 15 = Incr_Console Control Alt Shift keycode 15 = Decr_Console keycode 124 = Spawn_Console keycode 120 = Show_Memory keycode 121 = Show_State keycode 89 = F100 # Mute string F100 = " Mute " keycode 90 = Scroll_Forward # VolDown keycode 91 = Scroll_Backward # VolUp keycode 92 = Decr_Console # CdPrev keycode 93 = F104 # CdPlay string F104 = " CdPlay " keycode 94 = F105 # CdStop string F105 = " CdStop " keycode 90 = Scroll_Forward # VolDown keycode 91 = Scroll_Backward # VolUp keycode 92 = Decr_Console # CdPrev keycode 95 = Incr_Console # CdNext EOF
In this example, I have mapped some keys to special functions,
and some to strings. For a full description of the syntax, see the man page
keytables(5).
There is no convinient summary of what special keyboard functions are available. You need to look at:
spec_fn_table[]in the source file
/usr/src/linux/drivers/char/keyboard.c
dumpkeys
strings `which loadkeys`
This tells us the following special keyboard functions are available:
Bare_Num_Lock
Boot
Break
Caps_Lock
Caps_On
CapsShift
Shift, but also releases
Caps_Lock
Compose
Console_n
<ALT><F1> <ALT><F2>etc
Decr_Console
-1
Incr_Console
+1
KeyboardSignal
kb:line in
/etc/inittab
Last_Console
Num_Lock
SAK
/usr/src/linux/drivers/char/tty_io.c
Scroll_Backward
<SHIFT><PageUp>)
Scroll_Forward
<SHIFT><PageDown>)
Scroll_Lock
Scroll Lockkey
Shift_Lock
Caps_Lock, but more like the
Shift_Lockon a mechanical typewriter. It also shifts the numeric keys (where as
Caps_Lockdoesn't).
Shift_Lockshould be assigned to a shifted key. It is activated by pressing
<Shift><Shift_Lock>and is released by pressing
<Shift_Lock>
Show_Memory
Show_Registers
Show_State
Spawn_Console
KeyboardSignal
VoidSymbol
The above is not a comprehensive guide to all possible keyboard mappings. It just covers some of the more exotic ones.
I had some trouble making sense of
Shift_Lock.
There's probably more to it than the above brief note. I noticed
that
Shift_Lock and
Caps_Lock do not
co-operate: their results are additive.
Shift_Lock does not
affect the Caps_Lock LED.
Virtual consoles under Linux have one more feature which you
should be aware of:
- the ability to place the keyboard leds under software or kernel control.
By use of the
ioctl() calls
KDGETLED/KDSETLED
it is possible to arbitrarily control the keyboard leds
from within an application
Alternately, by use of the internal kernel function
register_leds() it is possible to use the keyboard leds
to monitor an arbitrary location in memory.
Unfortunately, direct manipulation of the keyboard leds by either of these methods defeats the normal operation of the leds in all of the virtual consoles.
Nevertheless, the benefits of this control may be worth the cost, especially if you rarely use CAPS_LOCK (like myself).
One example of such a program is the tleds program, which uses the keyboard leds to monitor network activity. The program comes in two flavors: tleds for running under the virtual consoles, and xtleds for running under X11 (additionally).
The tleds program is available from:
This document may be freely distributed.
The information contained in this document was correct at the time of writing, but may be out-of-date by the time you are reading it.
Author: George_Hansper@apana.org.au
Last modified: 8th July 1998 | https://luv.asn.au/overheads/virtualconsoles.html | CC-MAIN-2019-47 | refinedweb | 3,745 | 60.45 |
Support » Pololu 3pi Robot User’s Guide » 8. Example Project #2: Maze Solving »
8.b. Working with Multiple C Files in Atmel Studio
The C source code for an example line maze solver is available in the folder
examples\atmegaxx8\3pi-mazesolver.
Note: An Arduino-compatible version of this sample program can be downloaded as part of the Pololu Arduino Libraries (see Section 5.g) The Arduino sample sketch is all contained within a single file.
This program is much more complicated than the examples you have seen so far, so we have split it up into multiple files. Using multiple files makes it easier for you to keep track of your code. For example, the file
turn.c contains only a single function, used to make turns at the intersections:
#include <pololu/3pi.h> // Turns according to the parameter dir, which should be 'L', 'R', 'S' // (straight), or 'B' (back). void turn(char dir) { switch(dir) { case 'L': // Turn left. set_motors(-80,80); delay_ms(200); break; case 'R': // Turn right. set_motors(80,-80); delay_ms(200); break; case 'B': // Turn around. set_motors(80,-80); delay_ms(400); break; case 'S': // Don't do anything! break; } }
The first line of the file, like any C file that you will be writing for the 3pi, contains an include command that gives you access to the functions in the Pololu AVR Library. Within turn(), we then use the library functions delay_ms() and set_motors() to perform left turns, right turns, and U-turns. Straight “turns” are also handled by this function, though they don’t require us to take any action. The motor speeds and the timings for the turns are parameters that needed to be adjusted for the 3pi; as you work on making your maze solver faster, these are some of the numbers that you might need to adjust.
To access this function from other C files, we need a “header file”, which is called
turn.h. The header file just contains a single line:
void turn(char dir);
This line declares the turn() function without actually including a copy of its code. To access the declaration, each C file that needs to call turn() adds the following line:
#include "turn.h"
Note the double-quotes being used instead of angle brackets. This signifies to the C compiler that the header file is in the project directory, rather than being a system header file like
3pi.h. Always remember to put the code for your functions in the C file instead of the header file! If you do it the other way, you will be making a separate copy of the code in each file that includes the header.
The file
follow-segment.c also contains a single function, follow_segment(), which will drive 3pi straight along a line segment until it reaches an intersection or the end of the line. This is almost the same as the line following code discussed in Section 7, but with extra checks for intersections and the ends of lines. Here is the function:
void follow_segment() { int last_proportional = 0; long integral=0; while(1) { // Normally, we will be following a line. The code below is // similar to the 3pi-linefollower-pid example, but the maximum // speed is turned down to 60 for reliability. // Get the position of the line. unsigned int sensors[5]; unsigned int position = read_line(sensors,IR_EMITTERS_ON); // The "proportional" term should be 0 when we are on the line. int proportional = ((int)position) - 2000; // Compute the derivative (change) and integral (sum) of the // position. int derivative = proportional - last_proportional; integral += proportional; // Remember the last position. last_proportional = proportional; // Compute the difference between the two motor power settings, // m1 - m2. If this is a positive number the robot will turn // to the left. If it is a negative number, the robot will // turn to the right, and the magnitude of the number determines // the sharpness of the turn. int power_difference = proportional/20 + integral/10000 + derivative*3/2; // Compute the actual motor settings. We never set either motor // to a negative value. const int max = 60; // the maximum speed if(power_difference > max) power_difference = max; if(power_difference < -max) power_difference = -max; if(power_difference < 0) set_motors(max+power_difference,max); else set_motors(max,max-power_difference); // We use the inner three sensors (1, 2, and 3) for // determining whether there is a line straight ahead, and the // sensors 0 and 4 for detecting lines going to the left and // right. if(sensors[1] < 100 && sensors[2] < 100 && sensors[3] < 100) { // There is no line visible ahead, and we didn't see any // intersection. Must be a dead end. return; } else if(sensors[0] > 200 || sensors[4] > 200) { // Found an intersection. return; } } }
Between the PID code and the intersection detection, there are now about six more parameters that could be adjusted. We’ve picked values here that allow 3pi to solve the maze at a safe, controlled speed; try increasing the speed and you will quickly run in to lots of problems that you’ll have to handle with more complicated code.
Putting the C files and header files into your project is easy with Atmel Studio. On the right side of your screen, in the “Solution Explorer” pane, you should see a list of files in your project. Right click on the name of your project and you will have the option to add files to the list. When you build your project, Atmel Studio will automatically compile all C files in the project together to produce a single hex file. | https://www.pololu.com/docs/0J21/8.b | CC-MAIN-2017-22 | refinedweb | 916 | 62.27 |
Trivial, primitive, naive, and optimistic hook registry in Python
Project Description
It’s really simple. There are some events in the lifetime of your simple Python application that you want to hook into, and you don’t want to be overriding methods or writing conditional code to do that. What you do is you introduce hooks and register callbacks.
from hookery import HookRegistry hooks = HookRegistry() # It doesn't matter where you put the hook instance. # We set it as hooks attribute to keep things tidy. hooks.user_added = hooks.create_hook('user_added') _users = {} def create_user(username, password): _users[username] = password hooks.handle(hooks.user_added, username=username) @hooks.user_added def notify_me(): print('A new user has been added!') @hooks.user_added def say_hi(username): print('Hi, {}'.format(username))
>>> create_user('Bob', password='secret') A new user has been added! Hi, Bob | https://test.pypi.org/project/hookery/ | CC-MAIN-2018-09 | refinedweb | 136 | 59.7 |
A note on the 5.12-rc1 tag
From:
Linus Torvalds
Date:
Wed Mar 03 2021 - 19:07:17 EST ]..
Swapping still happened, but it happened to the wrong part of the
filesystem, with the obvious catastrophic end results.
Now, the good news is even if you do use swap (and hey, that's nowhere
near as common as it used to be), most people don't use a swap *file*,
but a separate swap *partition*. And the bug in question really only
happens for when you have a regular filesystem, and put a file on it
as a swap.
And, as far as I know, all the normal distributions set things up with
swap partitions, not files, because honestly, swapfiles tend to be
slower and have various other complexity issues.
The bad news is that the reason we support swapfiles in the first
place is that they do end up having some flexibility advantages, and
so some people do use them for that reason. If so, do not use rc1.
Thus the renaming of the tag.
Yes, this is very unfortunate, but that did get caught
and is fixed in the current tree.
But I want everybody to be aware of because _if_ it bites you, it
bites you hard, and you can end up with a filesystem that is
essentially overwritten by random swap data. This is what we in the
industry call "double ungood".
Now, there's a couple of additional reasons for me writing this note
other than just "don't run 5.12-rc1 if you use a swapfile". Because
it's more than just "ok, we all know the merge window is when all the
new scary code gets merged, and rc1 can be a bit scary and not work
for everybody". Yes, rc1 tends to be buggier than later rc's, we are
all used to that, but honestly, most of the time the bugs are much
smaller annoyances than this time.
And in fact, most of our rc1 releases have been so solid over the
years that people may have forgotten that "yeah, this is all the new
code that can have nasty bugs in it".
One additional reason for this note is that I want to not just warn
people to not run this if you have a swapfile - even if you are
personally not impacted (like I am, and probably most people are -
swap partitions all around) -.
And the *final* reason I want to just note this is a purely git
process one: if you already pulled my git tree, you will have that
"v5.12-rc1" tag, and the fact that it no longer exists in my public
tree under that name changes nothing at all for you. Git is
distributed, and me removing that tag and replacing it with another
name doesn't magically remove it from other copies unless you have
special mirroring code.
So if you have a kernel git tree (and I'm here assuming "origin"
points to my trees), and you do
git fetch --tags origin
you _will_ now see the new "v5.12-rc1-dontuse" tag. But git won't
remove the old v5.12-rc1 tag, because while git will see that it is
not upstream, git will just assume that that simply means that it's
your own local tag. Tags, unlike branch names, are a global namespace
in git.
So you should additionally do a "git tag -d v5.12-rc1" to actually get
rid of the original tag name.
Of course, having the old tag doesn't really do anything bad, so this
git process thing is entirely up to you. As long as you don't _use_
v5.12-rc1 for anything, having the tag around won't really matter, and
having both 'v5.12-rc1' _and_ 'v5.12-rc1-dontuse' doesn't hurt
anything either, and seeing both is hopefully already sufficient
warning of "let's not use that then".
Sorry for this mess,
Linus ] | http://lkml.iu.edu/hypermail/linux/kernel/2103.0/06524.html | CC-MAIN-2021-39 | refinedweb | 668 | 77.47 |
27 December 2012 11:29 [Source: ICIS news]
By Glynn Garlick
LONDON (ICIS)--The European oxo-alcohols market has ended 2012 with low but stable demand, and players expect little change in 2013.
Poor macroeconomic conditions have continued to affect domestic demand, and a major pick-up is not expected next year.
“For 2013, we see much the same as this year,” said a producer. “We have budgeted for little change in the oxo markets. We anticipate a pick-up in January and H1 [the first half of] 2013, but with a steady increase to year-end. Same oil prices and exchange rates, therefore very similar oxo pricing. Other than this, it is difficult to say.”
The seller added that it was looking to increase prices in January to improve margins.
The market for 2-ethyhexanol (2-EH) is generally described as tighter than for n-butanol (NBA) and isobutanol (IBA). Prices for 2-EH have therefore held up better than those for butanols in 2012, although values for all three have decreased as year-end approaches.
A 2-EH buyer said the downstream plasticizer market remains soft, and heading into 2013 there was noticeable destocking.
“If this is not reversed in Q1 [the first quarter], then demand in this market will remain fairly bearish,” said the buyer.
With ?xml:namespace>
“This is adding a little more length, and with prices at a lower level it will put pressure on EU producers to respond.
“Over the past few years, the balance has favoured the producers on the whole, but this may level things out. In general I think there will be more availability unless we see more FM [force majeure] situations.”
Producers have had little opportunity to use exports to offset poor domestic demand.
European competitiveness has been undermined by the high cost of propylene in the region and currency exchange volatility.
The NBA market is described as balanced, while IBA is said to be the longest, and this has put further downward pressure on IBA. | http://www.icis.com/Articles/2012/12/27/9624749/outlook-13-europe-oxo-alcohols-to-remain-stable.html | CC-MAIN-2013-20 | refinedweb | 336 | 61.77 |
07 June 2011 17:37 [Source: ICIS news]
LONDON (ICIS)--?xml:namespace>
The Bundesverband der Deutschen Industrie (BDI) said it raised the forecast from 7.5% after
However, despite the bullish forecast, BDI president Hans-Peter Keitel warned the country not to pursue energy policies that could put
He was referring to government plans to phase out nuclear power in the wake of March’s earthquake and tsunami disaster in
In the first quarter,
With €91bn in exports, March marked
Germany's first-quarter chemical and pharmaceutical industry exports were up 14% year on year, driven by exports to European countries, BDI said.
Despite strong year-on-year growth rates in exports to Asia, Europe remains the largest export market for
Going forward, BDI forecast strong growth in
The group also noted tough competition from South Korean firms in the market for chemical plant building and engineering.
While Germany’s chemical engineering firms still have a technological lead, South Korean firms are competing on price and are willing to take on more risks than competitors to win market share, BDI said.
Last month, Germany's chemical industry trade group, VCI, doubled its forecast for the country’s 2011 chemical production to 5.0% after a strong first quarter. VCI is a member of BDI. | http://www.icis.com/Articles/2011/06/07/9467245/german-industry-raises-2011-export-growth-forecast-to-11.html | CC-MAIN-2015-11 | refinedweb | 214 | 54.56 |
Hi,
I just put some highly experimental (but after all, that's what
alpha-dev versions are for, aren't they? ;-) ) code into the HEAD.
If it works out right (and it does for me by using Turbine and
AvalonComponentService), it should solve all the issues with
initialization from the static class. Simply by removing the static
variables. ;-)
I moved the whole class code into a Singleton (TorqueSingleton) and
replaced the method calls themselves with facade wrappers (just like
Turbine Services). Avalon, compared to that, accesses the singleton
directly and skips the Torque wrapper class.
As net result, you should be able to use Torque just as before
(standalone with Torque) or with an environment that loads and inits
Torque for you (Turbine with ComponentService or AvalonComponentService)
and as a "real" Avalon component, where you do
import org.apache.torque.avalon.Torque;
import org.apache.torque.avalon.TorqueComponent;
TorqueComponent tc = (TorqueComponent) manager.lookup(Torque.ROLE);
then you replace all Torque.<foo> method calls with doing
tc.<foo>
But the static peers should still work, because they access Torque
through the facade and end up in the same Singleton object as the
tc.<foo> method calls.
I did some preliminary testing and it seems to work. But this really
cries for more testing.
Regards
Henning
P.S.: Martin, I put some comments into the Torque class about the
Stratum deprecation. After we removed that code, can we please make
Torque an all static class by declaring it abstract? Thanks.
--: "Never argue with an idiot. They drag you down
to their level, then beat you with experience." --- | http://mail-archives.apache.org/mod_mbox/db-torque-dev/200306.mbox/%3Cbd1hhf$f22$2@tangens.hometree.net%3E | CC-MAIN-2015-18 | refinedweb | 265 | 67.35 |
hashids 1.2.0
Python implementation of hashids ().Compatible with python 2.6-3.
A python port of the JavaScript hashids implementation. It generates YouTube-like hashes from one or many numbers. Use hashids when you do not want to expose your database ids to the user. Website:
Compatibility
hashids is tested with python 2.6, 2.7, 3.2, 3.3 and 3.4. PyPy and PyPy 3 work as well.
Compatibility with the JavaScript implementation
The JavaScript implementation produces different hashes in versions 0.1.x and 0.3.x. For compatibility with the older 0.1.x version install hashids 0.8.4 from pip, otherwise the newest hashids.
Installation
Install the module from PyPI, e. g. with pip:
pip install hashids pip install hashids==0.8.4 # for compatibility with hashids.js 0.1.x
Run the tests
The tests are written with pytest. The pytest module has to be installed.
python -m pytest
Usage
Import the constructor from the hashids module:
from hashids import Hashids hashids = Hashids()
Basic Usage
Encode a single integer:
hashid = hashids.encode(123) # 'Mj3'
Decode a hash:
ints = hashids.decode('xoz') # (456,)
To encode several integers, pass them all at once:
hashid = hashids.encode(123, 456, 789) # 'El3fkRIo3'
Decoding is done the same way:
ints = hashids.decode('1B8UvJfXm') # (517, 729, 185)
Using A Custom Salt
Hashids supports salting hashes by accepting a salt value. If you don’t want others to decode your hashes, provide a unique string to the constructor.
hashids = Hashids(salt='this is my salt 1') hashid = hashids.encode(123) # 'nVB'
The generated hash changes whenever the salt is changed:
hashids = Hashids(salt='this is my salt 2') hashid = hashids.encode(123) # 'ojK'
A salt string between 6 and 32 characters provides decent randomization.
Controlling Hash Length
By default, hashes are going to be the shortest possible. One reason you might want to increase the hash length is to obfuscate how large the integer behind the hash is.
This is done by passing the minimum hash length to the constructor. Hashes are padded with extra characters to make them seem longer.
hashids = Hashids(min_length=16) hashid = hashids.encode(1) # '4q2VolejRejNmGQB'
Using A Custom Alphabet
It’s possible to set a custom alphabet for your hashes. The default alphabet is 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'.
To have only lowercase letters in your hashes, pass in the following custom alphabet:
hashids = Hashids(alphabet='abcdefghijklmnopqrstuvwxyz') hashid = hashids.encode(123456789) # 'kekmyzyk'
A custom alphabet must contain at least 16 characters.
Randomness
The primary purpose of hashids is to obfuscate ids. It’s not meant or tested to be used for security purposes or compression. Having said that, this algorithm does try to make these hashes unguessable and unpredictable:
Repeating numbers
There are no repeating patterns that might show that there are 4 identical numbers in the hash:
hashids = Hashids("this is my salt") hashids.encode(5, 5, 5, 5) # '1Wc8cwcE'
The same is valid for incremented numbers:
hashids.encode(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) # 'kRHnurhptKcjIDTWC3sx' hashids.encode(1) # 'NV' hashids.encode(2) # '6m' hashids.encode(3) # 'yD' hashids.encode(4) # '2l' hashids.encode(5) # 'rD'
Curses! #$%@
This code was written with the intent of placing generated hashes in visible places – like the URL. Which makes it unfortunate if generated hashes accidentally formed a bad word.
Therefore, the algorithm tries to avoid generating most common English curse words by never placing the following letters next to each other: c, C, s, S, f, F, h, H, u, U, i, I, t, T.
License
MIT license, see the LICENSE file. You can use hashids in open source projects and commercial products.
- Author: David Aurelio
- License: MIT License
- Categories
- Programming Language :: Python :: 2
- Programming Language :: Python :: 2.6
- Programming Language :: Python :: 2.7
- Programming Language :: Python :: 3
- Programming Language :: Python :: 3.2
- Programming Language :: Python :: 3.3
- Programming Language :: Python :: 3.4
- Programming Language :: Python :: 3.5
- Programming Language :: Python :: 3.6
- Package Index Owner: davidaurelio
- DOAP record: hashids-1.2.0.xml | https://pypi.python.org/pypi/hashids/ | CC-MAIN-2017-09 | refinedweb | 669 | 61.33 |
New features
From Nemerle Homepage
We list new language features for each release.
Version 0.9.1, Nov 4 2005
Full changelog in the blog post.
This version brings only one new feature: indentation-based syntax.
Version 0.9.0, Sep 14 2005
Full changelog in the blog post.
Generic specifier
You can specify parameters of:
- the generic type being created: Bar.[int] ();
- the generic type some static member is accessed from: Bar[int].foo ();
- the generic method: Bar.baz.[int] ();
With matching
Missing variables in matching branches can be now specified:
match (some_list) { // treat one element list as [x, x] | [x] with y = x | [x, y] => use x and y // can also set several things at once: | [] with (x = 7, y = 12) // and mix with 'when' | [x, _, z] when x == z with y = 17 | [x, y, _] => use x and y | _ => ... }
Partial application on steroids
In ML you could apply two argument function to a single argument and get another single argument function. We now support a similar, yet more powerful, feature:
some_fun (e1, _, e2, _)
is transformed to
fun (x, y) { some_fun (e1, x, e2, y) }
Partial application can be therefore written as f (x, _). It also works for member access:
_.foo
will be rewritten to:
fun (x) { x.foo }
The two rewrite rules can be combined:
_.foo (3, _)
will result in two argument function. Note that foo (3 + _) will probably not do what's expected (it will pass a functional value to foo). Use plain lambda expression for such cases.
Default parameters for local functions
This is mostly useful for accumulators, for example:
def rev (l, acc = []) { match (l) { | x :: xs => rev (xs, x :: acc) | [] => acc } } rev (l) // instead of rev (l, [])
as you can see the initial accumulator value is placed in a more intuitive place. Any expression is valid as a default parameter value for a local function, but beware that it is evaluated each time the function is called without this parameter.
#pragma warning
#pragma warning disable 10003 some_unused_function () : void {} #pragma warning restore 10003
You can also omit warning number to disable/enable all (numbered) warnings. You can also specify several warning numbers separating them by commas.
return, break and continue
Special implicit blocks are created around functions and loops. After using Nemerle.Imperative; it is possible to use break, continue and return. More details at the blocks page.
Version 0.3.2, Jun 1 2005
Omitting variant and enums names in matching
You can now omit prefixes of variants and enums in matching, for example:
variant Foo { | A | B } match (some_foo) { | A => ... | B => ... } enum Bar { | A | B } match (some_bar) { | A => ... | B => ... }
The restriction is that the type of some_foo need to be statically known to be Foo. If type inference cannot guess it at this point, you will have to match over (some_foo : Foo) or specify Foo.A in the first branch. Same goes to Bar. This feature is similar to switches on enums in Java 5.0.
Default parameters
public DoFoo (s : string, flag1 : bool = true, flag2 : bool = false) : void { }
For boolean, integer and string default value the type of parameter can be omitted:
public DoFoo (s : string, flag1 = true, flag2 = false) : void
Only other allowed default value is null:
public DoFoo (x : SomeClass = null) : void
Blocks
Blocks, it is possible to construct a block you can jump out of with a value. For example:
def has_negative = res: { foreach (x in collection) when (x < 0) res (true); false }
Please consult block wiki page for details.
Tuple indexing
Tuples can be now indexed with []. It is only supported with constant integer indexes. Indexing starts at 0, so pair[1] is Pair.Second (pair).
Top-level code
- Code can be entered at the top level, without a class and the Main method. So the classic example becomes:
System.Console.Write ("Hello marry world!\n");
That is, it put alone in the file will just compile. You can define classes, issue using declarations before the actual code. You can also define local functions with def (which gives you type inference). Yeah, we know this is only useful in write-once-run-once-throw-away kind of programs and testing, but it is nice anyway :-)
Several mutable definitions
mutable can now define more than one variable:
mutable (x, y) = (42, "kopytko"); x++; y = "ble"; mutable x = 3, y = "kopytko"; // the same
The second version does not work inside for (here;;).
Other changes
- Nemerle.English namespace now contains "and", "or" and "not" logical operators.
- Macros can now define textual infix and prefix operators (just like "and" above).
- Number literal can now contain _ for readability, for example def x = 1_000_000;
- Lazy value macros
- Automatic get/set accessor generation
- Arrays are no longer covariant. They haven't been in 0.2 days, and we have found it to be causing problems with type inference (see #442).
- Tuples and lists are now serializable. Variants are deserialized properly.
Version 0.3.1, May 2 2005
There is a single nice feature that sneaked into this release, it is now possible to match inside the foreach loop directly (#436), that is:
foreach (op in ops) { | Op.A => ... | Op.B => ... }
will now work as:
foreach (op in ops) { match (op) { | Op.A => ... | Op.B => ... } }
Version 0.3.0, Apr 29 2005
Implicit conversions.
'is' vs 'matches'
.
From the other cute new features department
- It is now possible to use pattern matching on properties, in addition to previous possibility of matching on fields.
- Another nice addition are the P/Invoke methods.
Version 0.2.10, Mar 31 2005
Yet incomplete support for new(), class() and struct() generic constraints.
Version 0.2.9, Mar 22 2005
The parser and the typer which constitute more then half of the compiler) have been replaced by entirely new implementations.
Nested variant options.
See also: omitting variant prefix in matching.
[] for generic types
Generic types use now [] instead of <>. That is there is 'list [int]' not 'list <int>'. This is the second (and hopefuly last ;-) time we change it. More details in this thread.
'is' in matching | _ => ... }
New type inference engine)
Other.
- Add 'repeat (times) body' language construct | http://nemerle.org/New_features | crawl-001 | refinedweb | 1,029 | 65.32 |
DNA Toolkit Part 1: Validating and counting nucleotides
In this article, we will start working on a DNA Toolkit. We will define a DNA nucleotide list and write our first two functions. The first couple of sections will deal with some very basic string/dictionary/lists processing as we build our biological sequence class and a set of functions to work with that class. We will build a powerful set of tools to analyze Genes and Genomes, to visualize and analyze the data.
By programming all of this ‘by hand’ in Python (or any other language of your choice), instead of using existing tools/services, will make sure that we have a good understanding of the bioinformatics fundamentals.
Tools I use for my work and research:
- Linux Manjaro/Debian 10.
- VSCodium (Free/Libre Open Source Software Binaries of VSCode).
- Python 3.7+, Bash.
I suggest using a good code editor like VSCode as it has a built-in, one-click Python debugger which will be super important for figuring out more complex algorithms we will tackle in later articles. A good code editor also has code completion, code tips, and auto-formatting functionality.
If you need more help setting up your programming environment in Windows or Mac, take a look at Cory Shafer’s amazing videos:
We are going to start with four files:
[jurisl@JurisLinuxPC dna-toolset]$ tree -l . ├── dna_toolkit.py ├── main.py ├── structures.py └── utilities.py 0 directories, 4 files
- dna_toolkit.py: Set of functions to process DNA/RNA/Codon data. It includes structures.py.
- structures.py: Set of structures like DNA, RNA, Codons, Proteins.
- main.py: File for testing our code. It includes dna_toolkit.py.
- utilities.py: Will contain helper functions like reading/writing files, accessing data bases etc.
We start by defining a Python List to store DNA nucleotides in strucutres.py file. That way we can reuse that list in all of our functions:
DNA_Nucleotides = ['A', 'C', 'G', 'T']
Now we include everything from structures.py into dna_toolkit.py and our first function does two things:
- Makes sure that the sequence (seq) passed to it is all upper case. In ASCII table ‘a’ = 97 and ‘A’ = 65. So 97 != 65 and ‘a’ != ‘A’. ASCII Table: Link.
- Checks if every character in that sequence is one of the characters in DNA_Nucleotides list and return all upper case sequence if it is.
from structures import * validate_seq(seq): """ Check the sequence to make sure it is a valid DNA string """ tmpseq = seq.upper() for nuc in tmpseq: if nuc not in DNA_Nucleotides: return False return tmpseq
Second function just counts individual nucleotides and stores the result in a Python Dictionary and returns that dictionary. This is probably the easiest, regular loop approach.
def nucleotide_frequency(seq): """ Count nucleotides in a given sequence. Return a dictionary """ tmpFreqDict = {"A": 0, "C": 0, "G": 0, "T": 0} for nuc in seq: tmpFreqDict[nuc] += 1 return tmpFreqDict
Below we use a more Pythonic way by importing Count method from the collections module.
from collections import Counter def nucleotide_frequency(seq): """ Count nucleotides in a given sequence. Return a dictionary """ # More Pythonic, using Counter return dict(Counter(seq))
Now our for loop turns into one line of code which is probably faster than a for loop. At this stage, it is not all that important. Use whatever you are more comfortable with at your stage of learning Python.
Let’s include our dna_toolkit.py into our main.py, create a random DNA sequence (randDNAStr), validate it, print out the validated version, it’s length and pass it on to nucleotide frequencies function and use f-strings to display results in a nicer, more structured way.
# DNA Toolset/Code testing file from dna_toolkit import * # Creating a random DNA sequence for testing: randDNAStr = "ATAGCTGACTAT" DNAStr = validate_seq(randDNAStr) print(f'\nSequence: {DNAStr}\n') print(f'[1] + Sequence Length: {len(DNAStr)}\n') print(f'[2] + Nucleotide Frequency: {nucleotide_frequency(DNAStr)}\n')
So now we can run our code to see the output (lines 9, 10 and 11):
Sequence: ATAGCTGACTAT [1] + Sequence Length: 12 [2] + Nucleotide Frequency: {'A': 4, 'T': 4, 'G': 2, 'C': 2}
We can also add a random DNA sequence generation to our main.py file. We do that by importing random module and using random.choice method. Basically we give it our nucleotide list and ask it to randomly pick one of the nucleotides, 50 times in our example below. We do so by using Python’s list comprehension. It returns a list, so we need to convert it to a string. We use join method to ‘glue’ all list elements into one string.
Here is how it looks:
import random # Creating a random DNA sequence for testing: randDNAStr = ''.join([random.choice(DNA_Nucleotides) for nuc in range(50)])
This is it for now. Now we have an entry point into a set of tools we will be writing in this series of articles.
You can access the code for this article via GitLab Link. Code in the repository might differ from this article as I am refactoring and updating it as this series progresses, but core functionality stays the same.
Video version of this article is also available here:
Until next time, rebelCoder, signing out.
2 Comments
ปั้มไลค์ · June 24, 2020 at 23:03
Like!! Thank you for publishing this awesome article.
Bioinformatics Tools Programming in Python with Qt. Part 1. - rebelScience · June 7, 2020 at 15:02
[…] adding a GUI (graphical user interface) to a class and a set of functions we developed in “DNA Toolkit” […] | https://rebelscience.club/2020/03/28/part-1-validating-and-counting-nucleotides/ | CC-MAIN-2021-39 | refinedweb | 921 | 63.49 |
Base64 is used to store binary data such as images as text. It can be used in web pages but is more commonly seen in email applications and in XML files.
The .NET Framework includes a base64 encoder in its Convert class. Since it represents a fair degree of bit manipulation and can be done in parallel, is it perhaps
a task that can be better handled by a graphics processing unit?
Convert
Base64 uses 64 characters as its base (decimal uses 10, hex uses 16). The 64 characters are A-Z, a-z, 0-9, and '+' and '/'. Three bytes can be represented
by four base64 digits. If the total number of bytes is not a multiple of three, then padding characters are used. The padding character is '='. The total length
of the base64 string for a given number of bytes n is 4 * (n/3). Per block of three bytes, we have in total 24-bits (3 * 8-bits). 64 different values can be represented
by 6-bits, so we need in total four 6-bit values to contain the 24-bits. Base64 encoding consists of this processing of blocks of three bytes and since each block
is independent of any other block, it would appear to be a suitable task for a GPU.
Though it is becoming more common, the use of GPUs for non-graphics, general purpose programming remains a niche. Typical business and web programming still rarely
makes use of GPUs and there are a number of good reasons for this. Finding suitable performance bottlenecks and then porting an algorithm or business logic to make use
of a GPU can be time consuming, and the pay-off can be uncertain. Furthermore, the target hardware platform may not have a suitable GPU. Despite this, GPUs can have,
given the right task, massive performance gains.
NVIDIA still leads the way with general purpose GPU (GPGPU). Their CUDA language and associated tools and libraries make it relatively easy to get started in C/C++.
In .NET, it is a different story, requiring the use of PInvoke and the so-called CUDA driver API. This is rather cumbersome. CUDA.NET simplified matters a little,
however the programming model remained that of the driver API, and kernel (GPU device) code still needed to be written in CUDA C. CUDAfy.NET goes a stage further
and hides much of the complexity of the driver API, allows kernel code to also be written in .NET, and uses standard .NET types (e.g., arrays of value types).
First, be sure you have a relatively recent NVIDIA Graphics Card, one that supports CUDA. You'll then need to go to the NVIDIA CUDA website and download
the CUDA 5.5 Toolkit. Install this in the default location. Next up, ensure that you have the latest
NVIDIA drivers. These can be obtained through an NVIDIA update or from the NVIDIA website. the
Visual Studio Express website:
This set-up of the CUDA compiler (NVCC) is actually the toughest stage of the whole process, so please persevere. Read any errors you get carefully - most likely they
are related to not finding cl.exe or not having either the 32-bit or 64-bit CUDA Toolkit. Try to get NVCC working without CUDAfy. If you still have problems, then please let me know.
The simplest way of converting to base64 in .NET is to use the Convert.ToBase64 method. However, let's look at how we can implement such a method ourselves.
Below is a method that takes a byte array and converts to a base64 string. The code is based on C code from René Nyffenegger.
Convert.ToBase64
public static string base64_encode(byte[] bytes_to_encode)
{
int i = 0;
int j = 0;
int ctr = 0;
// Initialize StringBuilder to required capacity.
StringBuilder sb = new StringBuilder((bytes_to_encode.Length * 4) / 3);
// Local array for group of three bytes
int[] char_array_3 = new int[3];
// Local array for output
int[] char_array_4 = new int[4];
int in_len = bytes_to_encode.Length;
// Loop until all bytes have been read
while (in_len-- > 0)
{
// Read bytes into local array
char_array_3[i++] = bytes_to_encode[ctr++];
// Once three bytes have been read, begin encoding
if (i == 3)
{
// 1st byte: Mask most significant 6-bits and move 2 bits to the right
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
// 1st byte: Mask least significant 2-bits and move 4 bits left
// 2nd byte: Mask most significant 4-bits and move 4 bits right
// Add values
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
// 2nd byte: Mask least significant 4-bits and move 2 bits left
// 3rd byte: Mask most significant 2-bits and move 6 bits right
// Add values
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) +
((char_array_3[2] & 0xc0) >> 6);
// 3rd byte: Mask least significant 6-bits
char_array_4[3] = char_array_3[2] & 0x3f;
// Select the base64 characters from
// the base64_chars array and write to output
for (i = 0; (i < 4); i++)
{
char c = base64_chars[char_array_4[i]];
sb.Append(c);
}
i = 0;
}
}
// If the total number of bytes is not
// a multiple of 3 then handle the last group
if (i != 0)
{
// Set remaining bytes to zero
for (j = i; j < 3; j++)
char_array_3[j] = 0;
// Handle the group as before
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
{
char c = base64_chars[char_array_4[j]];
sb.Append(c);
}
// Add padding characters
while ((i++ < 3))
sb.Append('=');
}
// Convert to string and return
string s = sb.ToString();
return s;
}
We will use this code as a basis for our GPU kernel. This is the code that will actually run on the GPU. Methods that can run on the GPU must be static and decorated
with the Cudafy attribute. Thousands of instances of device methods can run in parallel, so we need a means of identifying threads from within the method.
The GThread parameter is how this can be done. The two other parameters are the input and output arrays. The method Gettid returns the unique
ID of the thread. Threads are launched in a grid of blocks, where each block contains threads. Hence we calculate the ID by multiplying the block ID by
the block size (dimension) and adding the thread ID within the block. Grids and blocks can be multidimensional, but here we only use one dimension, signified by x.
Cudafy
GThread
Gettid
Since each thread will process a group of three bytes, the offset into the input array is three times the thread ID. The offset into the output array is four times
the thread ID. What follows is a fairly straightforward port of the code discussed above. Since String is not supported in kernel code, we simply place
the string as a constant in the code.
String
[Cudafy]
public static void ToBase64String(GThread thread, byte[] input, char[] output)
{
// Get the id of the current thread.
int tid = Gettid(thread);
// Input id is 3 times the thread id.
int itid = tid * 3;
// Output id is 4 times the thread id.
int otid = tid * 4;
// Since we always launch a fixed number of threads
// per block we do not want a thread to try
// accessing an out of range index.
if (itid + 2 < input.Length)
{
byte a0 = 0;
byte a1 = 0;
byte a2 = 0;
byte b0 = 0;
byte b1 = 0;
byte b2 = 0;
byte b3 = 0;
a0 = input[itid];
a1 = input[itid + 1];
a2 = input[itid + 2];
// Do the bit shuffling that's the core of base64 encoding.
b0 = (byte)((a0 & 0xfc) >> 2);
b1 = (byte)(((a0 & 0x03) << 4) + ((a1 & 0xf0) >> 4));
b2 = (byte)(((a1 & 0x0f) << 2) + ((a2 & 0xc0) >> 6));
b3 = (byte)(a2 & 0x3f);
// Set the four output chars by selecting the index based on above four values.
output[otid] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[b0];
output[otid + 1] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[b1];
output[otid + 2] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[b2];
output[otid + 3] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[b3];
}
}
[Cudafy]
public static int Gettid(GThread thread)
{
int tid = thread.blockIdx.x * thread.blockDim.x + thread.threadIdx.x;
return tid;
}
The code for interacting with the GPU is implemented in the class named GConvert.
GConvert
A reference is made to Cudafy.NET.dll and the following namespaces included:
using Cudafy;
using Cudafy.Host;
using Cudafy.Translator;
There are two methods implemented for performing the conversion. Both do the same thing, taking the byte array to be encoded and a Stream for the output.
We'll look at the most straightforward.
Stream
Writing to the output stream is done asynchronously. Since StreamWriter does not contain Begin and End methods for asynchronous writing, a delegate is used.
The class member _gpu refers to the CUDAfy GPGPU class and represents a single GPU device. It is passed into the GConvert constructor.
The process of working is now as follows:
StreamWriter
_gpu
GPGPU
public void ToBase64Naive(byte[] inArray, Stream outStream)
{
int totalBytes = inArray.Length;
int ctr = 0;
int chunkIndex = 0;
int threadsPerBlock = 256;
StreamWriter sw = new StreamWriter(outStream);
BeginWriteDelegate beginWrite = new BeginWriteDelegate(BeginWrite);
IAsyncResult res = null;
while (totalBytes > 0)
{
// Split into chunks
int chunkSize = Math.Min(totalBytes, MAXCHUNKSIZE);
int outChunkSize = (chunkSize * 4) / 3;
// Copy the data to GPU
_gpu.CopyToDevice(inArray, ctr, _inArrays_dev[chunkIndex], 0, chunkSize);
// Calculate blocksPerGrid - GPU launches multiple blocks (blocksPerGrid)
// each consisting of multiple threads (threadsPerBlock).
// Each thread will handle 3 bytes.
int blocksPerGrid =
(chunkSize + (threadsPerBlock * 3) - 1) / (threadsPerBlock * 3);
// Launch the function ToBase64String asynchronously
// (same stream id as previous GPU command - they are in same queue).
_gpu.Launch(blocksPerGrid, threadsPerBlock, "ToBase64String",
_inArrays_dev[chunkIndex], _outArrays_dev[chunkIndex]);
// Copy the data from GPU
_gpu.CopyFromDevice(_outArrays_dev[chunkIndex], 0,
_outArrays[chunkIndex], 0, outChunkSize);
// End any pending write
if (res != null)
beginWrite.EndInvoke(res);
// Begin writing the managed buffer to the stream asynchronously.
res = beginWrite.BeginInvoke(sw, _outArrays[chunkIndex], 0,
outChunkSize, null, null);
// Increment the chunkIndex, decrement totalBytes
// by chunkSize and increase our offset counter.
chunkIndex++;
totalBytes -= chunkSize;
ctr += chunkSize;
if (chunkIndex == MAXCHUNKS)
chunkIndex = 0;
}
// Wait for last chunk to be written.
if (res != null)
beginWrite.EndInvoke(res);
// If the total number of bytes converted was not
// a multiple of 3 then handle the last bytes here.
int remainder = inArray.Length % 3;
if (remainder != 0)
{
string s = Convert.ToBase64String(inArray,
inArray.Length - remainder,
remainder).Remove(0, remainder);
sw.Write(s);
}
sw.Flush();
}
Of interest here are the following variables:
MAXCHUNKSIZE
MAXCHUNKS
_inArrays_dev
_outArrays_dev
_outArrays
These arrays are instantiated in the GConvert constructor. The process of Cudafying is detailed in an earlier article.
Using Cudafy for GPGPU Programming in .NET.
Basically, the GPU code is contained in the class GPUConvertCUDA and we create a module with the name of that class. Using the IsModuleLoaded method,
we check if the module is already loaded. If not, we try to deserialize the module from an XML file named 'GPUConvertCUDA.cdfy'. If the file does not exist
or the serialized module was created from a different version of the assembly, then we Cudafy again. We pass the auto platform (x86 or x64),
CUDA 1.2 architecture (the latest NVIDIA devices are 2.0) parameters along with the type of the class we want to Cudafy. To save time, next time the program
runs, we serialize the module to an XML file.
GPUConvertCUDA
IsModuleLoaded
public GConvert(GPGPU gpu)
{
_gpu = gpu;
string moduleName = typeof(GPUConvertCUDA).Name;
// If module is not already loaded try to load from file.
if (!_gpu.IsModuleLoaded(moduleName))
{
var mod = CudafyModule.TryDeserialize(moduleName);
// If file does not exist or the checksum does not match then re-Cudafy.
if (mod == null || !mod.TryVerifyChecksums())
{
Debug.WriteLine("Cudafying...");
mod = CudafyTranslator.Cudafy(ePlatform.Auto,
eArchitecture.sm_12, typeof(GPUConvertCUDA));
// Save the module to file for future use.
mod.Serialize(moduleName);
}
_gpu.LoadModule(mod);
}
// Instantiate arrays. _dev arrays will ultimately be on the GPU.
_inArrays_dev = new byte[MAXCHUNKS][];
_outArrays_dev = new char[MAXCHUNKS][];
_outArrays = new char[MAXCHUNKS][];
_inStages = new IntPtr[MAXCHUNKS];
_outStages = new IntPtr[MAXCHUNKS];
// Make MAXCHUNKS number of each array. Input is bytes, output is chars.
// The output array will be 4/3 the size of the input.
for (int c = 0; c < MAXCHUNKS; c++)
{
_inArrays_dev[c] = _gpu.Allocate<byte>(MAXCHUNKSIZE);
_outArrays_dev[c] = _gpu.Allocate<char>((MAXCHUNKSIZE * 4) / 3);
_inStages[c] = _gpu.HostAllocate<byte>(MAXCHUNKSIZE);
_outStages[c] = _gpu.HostAllocate<char>((MAXCHUNKSIZE * 4) / 3);
_outArrays[c] = new char[(MAXCHUNKSIZE * 4) / 3];
}
}</char></byte></char></byte>
_inStages and _outStages are used by the optimized version of the ToBase64Naive method, ToBase64. This method makes use of pinned
memory for faster transfers and for performing asynchronous transfers and kernel launches. Use HostAllocate for allocating pinned memory.
Remember, pinned memory is limited compared to unpinned memory and that you will need to clean it up manually using HostFree. The performance increase
gained by using pinned memory for transfers can be around 50%, however this is offset by the need to transfer from managed memory into pinned memory.
Ultimately, the speed increase can be insignificant compared to normal transfers as in the ToBase64Naive method. However, it does permit another
benefit and that is asynchronous transfers and kernel launches. Transfers do not occur in parallel with each other though; instead they are placed in a queue.
Transfers can be in parallel with launches. Correct usage of stream IDs is required. Do not use stream ID 0 for this purpose - stream 0 synchronizes all streams
irrespective of ID. All operations of the same stream ID are guaranteed to be performed in sequence.
_inStages
_outStages
ToBase64Naive
ToBase64
HostAllocate
HostFree
Get a GPU device using the static CudafyHost.GetDevice method. The device is passed to the GConvert constructor.
Conversion takes two arguments, the byte array and the output stream.
CudafyHost.GetDevice
// Get the first CUDA GPGPU
GPGPU gpu = CudafyHost.GetDevice(eGPUType.Cuda);
// Pass the GPGPU to the GConvert constructor
GConvert gc = new GConvert(gpu);
gc.ToBase64(ba, gpuStream);
We want to compare a number of different ways of doing base64 encoding. The following benchmarks were run on an Intel Core i5-450M with NVIDIA GeForce GT 540M GPU:
And now as a graph; lower is better.
For small amounts of binary data, the differences in speed are relatively small. For large data sets, the GPU provided a massive performance gain over our
own base64 implementation. The differences between the simpler naive GPU implementation and the asynchronous pinned memory version were useful but not earth
shattering. If you need to squeeze every last bit of performance out of the GPU, then it's worthwhile. However, what is significant is the fantastic result
of the out of the box .NET implementation. For the vast majority of cases, it will be almost as fast as the GPU, only being beaten for much larger arrays.
If when you run the application your GPU runs much slower compared to the .NET version that the results here showed, then there is likely a good reason
for this. These benchmarks are run on the NVIDIA Fermi architecture. This recent design gives far better performance when accessing small, irregular blocks
of global memory as we do here when reading three individual bytes per thread. There are ways of circumventing this issue by clever use of shared memory,
however as in any programming task, one has to draw limits to the time spent implementing. The code here was a simple port of the CPU version.
So, why is the .NET base64 encoder so much faster than our own CPU version? Well, it is extremely unlikely that it is implemented in straightforward
C# as we did. Most likely, it makes use of special low-level SSE commands, much the same as FFTW (Fastest Fourier Transform in the West) can perform an FFT faster
than we can step through an array of the same length, doing a simple multiplication on each element. Due to the simple, sequential, in order nature of base64 encoding,
an optimized CPU version can match a GPU. Note that the .NET version could likely be made even faster by explicitly breaking up the data and performing in multiple threads,
say one per core. Be aware also that the writing to the stream does not become the bottleneck. Remove that step if necessary to ensure a true comparison.
Writing with a StreamWriter is not as fast as writing with a BinaryWriter.
BinaryWriter
Can base64 encoding still be useful on a GPU? Yes, for very large data sets, and if the data to be encoded is already on the GPU. This would remove the need
to copy the data first to the GPU. Furthermore, it would reduce the load on valuable CPU resources. the GNU LGPL version 2.1. Visit the Cudafy website for more information.
This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)
For those interested running on Intel i7 980X + NVIDIA GT460 gives:
The fact that the naive and optimized GPU implementations return the same times suggests that the writing to the output stream is the bottleneck. Removing writing to stream from all tests gives the following and shows good performance even for smaller byte arrays.
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/276993/Base-Encoding-on-a-GPU?msg=4073303 | CC-MAIN-2014-35 | refinedweb | 2,854 | 64.61 |
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi All,
I'm trying to implement a real time face detection using openCV from the IR image of the kinect, unfortunately it takes my sketch from 60fps down to 6fps. I am aware kinectPV2 does face detection but it's nowhere near as good as openCV. Can someone suggest a solution? I've tried the multithreaded "your are einstein" sketch but I couldn't get it to run.
import KinectPV2.*; import gab.opencv.*; import java.awt.Rectangle; KinectPV2 kinect; FaceData [] faceData; OpenCV opencv; Rectangle[] faces; PImage img; void setup() { size(1000, 500, P2D); opencv = new OpenCV(this, 512, 424); opencv.loadCascade(OpenCV.CASCADE_FRONTALFACE); kinect = new KinectPV2(this); //for face detection base on the infrared Img kinect.enableInfraredImg(true); //enable face detection kinect.enableFaceDetection(true); kinect.enableDepthImg(true); kinect.init(); } void draw() { background(0); img = kinect.getInfraredImage(); //512 424 opencv.loadImage(img); faces = opencv.detect(); image(img, 0, 0); image(kinect.getDepthImage(), img.width, 0); fill(255); text("frameRate "+frameRate, 50, 50); noFill(); for (int i = 0; i < faces.length; i++) { rect(faces[i].x, faces[i].y, faces[i].width, faces[i].height); } }
Answers
@CharlesDesign -- If the Kinect is 30fps you can start with frameRate(30) (or 27, or 24). That should save wasted effort trying to recalculate each unchanging camera frame twice at 60fps.
Then you could also drop the framerate on the rect() updating, independent of the higher video framerate -- perhaps texts updated at 15 or 10 fps, something like this (untested):
That's not speeding up your processor-intensive openCV calls, but it is hopefully letting your video run at full speed under slower rects -- and possibly speeding up the rects too since the overall load has dropped as well.
Good suggestion, thanks! :) | https://forum.processing.org/two/discussion/21971/speeding-up-open-cv-detect-face | CC-MAIN-2019-43 | refinedweb | 307 | 57.47 |
panda3d.core.AsyncTaskChain¶
from panda3d.core import AsyncTaskChain
- class
AsyncTaskChain¶
Bases:
TypedReferenceCount,
Namable
The AsyncTaskChain is a subset of the AsyncTaskManager. Each chain maintains a separate list of tasks, and will execute them with its own set of threads. Each chain may thereby operate independently of the other chains.
The AsyncTaskChain will spawn a specified number of threads (possibly 0) to serve the tasks. If there are no threads, you must call
poll()from time to time to serve the tasks in the main thread. Normally this is done by calling
AsyncTaskManager.poll().
Each task will run exactly once each epoch. Beyond that, the tasks’ sort and priority values control the order in which they are run: tasks are run in increasing order by sort value, and within the same sort value, they are run roughly in decreasing order by priority value, with some exceptions for parallelism. Tasks with different sort values are never run in parallel together, but tasks with different priority values might be (if there is more than one thread).
Inheritance diagram
setTickClock(tick_clock: bool) → None¶
Sets the tick_clock flag. When this is true, get_clock()->tick() will be called automatically at each task epoch. This is false by default.
getTickClock() → bool¶
Returns the tick_clock flag. See
setTickClock().
setNumThreads(num_threads: int) → None¶
Changes the number of threads for this task chain. This may require stopping the threads if they are already running.
getNumThreads() → int¶
Returns the number of threads that will be servicing tasks for this chain. Also see
getNumRunningThreads().
getNumRunningThreads() → int¶
Returns the number of threads that have been created and are actively running. This will return 0 before the threads have been started; it will also return 0 if thread support is not available.
setThreadPriority(priority: ThreadPriority) → None¶
Changes the priority associated with threads that serve this task chain. This may require stopping the threads if they are already running.
getThreadPriority() → ThreadPriority¶
Returns the priority associated with threads that serve this task chain.
- Return type
ThreadPriority
setFrameBudget(frame_budget: float) → None¶
Sets the maximum amount of time per frame the tasks on this chain are granted for execution. If this is less than zero, there is no limit; if it is >= 0, it represents a maximum amount of time (in seconds) that will be used to execute tasks. If this time is exceeded in any one frame, the task chain will stop executing tasks until the next frame, as defined by the TaskManager’s clock.
getFrameBudget() → float¶
Returns the maximum amount of time per frame the tasks on this chain are granted for execution. See
setFrameBudget().
setFrameSync(frame_sync: bool) → None¶
Sets the frame_sync flag. When this flag is true, this task chain will be forced to sync with the TaskManager’s clock. It will run no faster than one epoch per clock frame. task chains. Non-threaded task chains are automatically synchronous.
getFrameSync() → bool¶
Returns the frame_sync flag. See
setFrameSync().
setTimeslicePriority(timeslice_priority: bool) → None¶
Sets the timeslice_priority flag. This changes the interpretation of priority, and the number of times per epoch each task will run.
When this flag is true, some tasks might not run in any given epoch. Instead, tasks with priority higher than 1 will be given precedence, in proportion to the amount of time they have already used. This gives higher-priority tasks more runtime than lower-priority tasks. Each task gets the amount of time proportional to its priority value, so a task with priority 100 will get five times as much processing time as a task with priority 20. For these purposes, priority values less than 1 are deemed to be equal to 1.
When this flag is false (the default), all tasks are run exactly once each epoch, round-robin style. Priority is only used to determine which task runs first within tasks of the same sort value.
getTimeslicePriority() → bool¶
Returns the timeslice_priority flag. This changes the interpretation of priority, and the number of times per epoch each task will run. See
setTimeslicePriority().
stopThreads() → None¶
Stops any threads that are currently running. If any tasks are still pending and have not yet been picked up by a thread, they will not be serviced unless
poll()or
startThreads()is later called.
startThreads() → None¶
Starts any requested threads to service the tasks on the queue. This is normally not necessary, since adding a task will start the threads automatically.
isStarted() → bool¶
Returns true if the thread(s) have been started and are ready to service requests, false otherwise. If this is false, the next call to add() or add_and_do() will automatically start the threads.
hasTask(task: AsyncTask) → bool¶
Returns true if the indicated task has been added to this AsyncTaskChain, false otherwise.
getNumTasks() → int¶
Returns the number of tasks that are currently active or sleeping within the task chain.
getTasks() → AsyncTaskCollection¶
Returns the set of tasks that are active or sleeping on the task chain, at the time of the call.
- Return type
-
getActiveTasks() → AsyncTaskCollection¶
Returns the set of tasks that are active (and not sleeping) on the task chain, at the time of the call.
- Return type
-
getSleepingTasks() → AsyncTaskCollection¶
Returns the set of tasks that are sleeping (and not active) on the task chain, at the time of the call.
- Return type
-
poll() → None¶
Runs through all the tasks in the task list, once, if the task chain is running in single-threaded mode (no threads available). This method does nothing in threaded mode, so it may safely be called in either case.
Normally, you would not call this function directly; instead, call
AsyncTaskManager.poll(), which polls all of the task chains in sequence.
getNextWakeTime() → float¶
Returns the scheduled time (on the manager’s clock) of the next sleeping task, on any task chain, to awaken. Returns -1 if there are no sleeping tasks. | https://docs.panda3d.org/1.10/python/reference/panda3d.core.AsyncTaskChain | CC-MAIN-2020-05 | refinedweb | 962 | 64.1 |
Introduction
Although Gum provides extensive layout control, many games require Gum components with custom logic. For example, a button may need to play a sound effect when clicked – logic which should be centralised in the button component code rather than added as events on every button instance.
This tutorial shows how to use partial classes to add custom logic to a button. Although we use partial classes for the specific functionality of adding sound effects, partial classes can be used for any other logic.
What is a Partial Class?
Partial classes, which use the partial keyword, allow the definition of a single class to be spread out across multiple files. Glue uses partial classes to separate custom code from generated code (so that generated code does not overwrite custom code). In fact, all screens and entities in a Glue project already use partial classes. You can see this by expanding any screen or entity in your project in Visual Studio.
The following image shows a GameScreen’s custom code:
The following image shows a GameScreen’s generated code:
Adding a Partial Class File
All Gum components and screens are generated as partial files (they include the partial keyword) so we don’t need to make any changes in Glue or Gum to enable adding additional partial class files.
All Gum runtime object code is contained in the GumRuntimes folder. By default, this contains only generated code files, but we can add our own custom code here.
To add a partial file:
- Locate the GumRuntimes folder in Visual Studio’s Solution Explorer
- Right-click on the GumRuntimes folder
- Select Add -> Class…
- Enter the name matching the desired screen or component. For this tutorial we’ll add a partial for the Button component, so we’ll enter the name ButtonRuntime.
- By default, Visual Studio will assign a namespace to your newly-created class, which should be <YourProjectNamespace>.GumRuntimes . Verify that this is the case, as the namespace of your newly-created file must match the namespace of the generated file.
- Add the partial keyword in front of the class keyword in the newly-created file
- Save the project (ctrl+shift+s) so that Glue is notified of the changed project file. You can verify that the project has been saved and Glue reloaded the project if you are notified by Visual Studio that the project has changed.
- Click Reload. This will embed the ButtonRuntime.Generated.cs file under the newly-created ButtonRuntime.cs file.
Adding CustomInitialize
Gum runtime objects all support a CustomInitialize call. Usually, CustomInitialize is where internal event handlers are added. To add CustomInitialize, add the following code inside the ButtonRuntime.cs file:
We can handle the Click event by modifying the ButtonRuntime code as follows:
Now we can add code in our HandleClick method to perform any custom logic when the user clicks the button. This code will be executed on every instance of ButtonRuntime across our entire project.
Troubleshooting
No defining declaration found for implementing declaration of partial method
This is usually caused by having a mismatched namespace in your partial compared to the partial of the generated code.
<- 7. States — Back to Tutorials -> | http://flatredball.com/documentation/tools/gum/gum-tutorials/8-adding-code-to-gum-objects/ | CC-MAIN-2018-22 | refinedweb | 526 | 52.39 |
«
March 2003 |
»
Main
«
| May 2003
»
Wednesday 30 April 2003
Bob (you may or may not know Bob) sent along two interesting links.
How to bow is an entertaining
introduction to the complexities of Japanese business manners.
And I'm not sure what to make of this:
ASP.NET pages in 80386 assembler.
Yow.
Michael Tsai draws a parallel
between Apple's online music biz
and
Edison's attempt to sell records.
I think getting the big players on board is a necessary first step
to getting the concept accepted.
It reminds me of Don Norman's story about
how Edison's phonograph lost.
The Edison story is good, and shows how the old genius made the same
business mistakes as plenty of other geeks:
he put too much faith in technical superiority.
Tuesday 29 April 2003
I'm looking for tools for understanding how memory is being allocated and freed
in my C++ heap.
mpatrol looks very
full-featured, but perhaps a bit too grungy to get going. I like that it is free,
but would feel more optimistic about my chances with it if it mentioned Visual C++
anywhere in its documentation (it's very GNU-centric).
Does anyone have any recommendations for good tools that aren't too expensive
(free is ideal!), can report on leaks, fragmentation, etc, and is fairly painless
to get started with?
Here's a list of such tools,
though I get the sense that it is a few years out-of-date.
Monday 28 April 2003
Ken Arnold (whose long history includes curses, rogue, Java, and Jini)
has a witty and pithy piece on programming language human factors:
Are Programmers People? And If So, What to Do About It?
Sunday 27 April 2003
The weather is turning nicer, and you know what that means:
more juggling. I have long enjoyed juggling (my father taught
me so long ago I don't remember learning), and have kept it up
enough that my skills have continued to improve.
A few years back I learned the three-ball shower (where the
balls go in a circle, cartoon-like, rather than the standard
over-under cascade pattern).
Last year I finally mastered four balls, which I previously
never liked because
of its split-screen feel, since at its simplest,
the balls stay in their assigned hand.
(As with any specialized discipline, there is way more
to juggling than the person in the street would guess.
Take a look at some
Juggling Animations
to see what I mean).
This year, I'm going to try to get to a five-ball cascade.
I've been approaching it from a few different angles for a while
now, and think I may have enough basics to just go ahead and
do it. We'll see. Maybe this public declaration will force me
to master it.
In preparation and as incentive, I've ordered five
Todd Smith beanbags.
Wish me luck!
Friday 25 April 2003
You'd think after 18 months of working on the
Kubi Client,
I would be able to do
MIME
structures in my sleep.
But I had to look it up again today, so I'm putting this
here so I can find it again. Also, I figure if I need to
look something up, someone else out there may find it
useful.
There are three commonly-used Content-Type headers for
structuring MIME messages:
»
read more of: MIME message structure... (3 paragraphs)
Thursday 24 April 2003
Tantek talks about hand-rolled blogs.
I'm interested, because
I fall into his second category
("folks who rolled their own blogging content management system").
Photomatt followed on, with insightful comments
that neatly step over the class warfare between
the out-of-the-box people and the hand-rolled people,
to get at the important point:
Whatever you do should put as little as possible between
yourself and whatever it is you love about
creating your little corner of the independent web.
...
Tantek is happy writing the code for his page,
just as I get a buzz typing in a box and having everything else happen automagically.
...
Do what makes you happy.
This site is hand-rolled because I love understanding how web sites are built, and
writing tools to create web sites. Some days I would like not to have to worry about
it, but on those days I can just ignore the tools that are in place and working.
On the days when I want to make something happen differently, I can hack on the tools.
BTW: many of the hand-rollers seem to do it because they care passionately about
the style and structure of the markup (that is, the tags themselves, rather than the
page they produce). I can understand that passion, and would like to be able to partake
in it. If you look at the HTML that produces this page, it is nothing to be proud of.
Someday I will get rid of all the tables and 1-pixel gifs and do a real 21st-century
CSS-driven accessible layout. But not yet. I don't have the time, focus, or stomach
for the multi-browser debugging that would take.
The whole thread got started by
Zeldman railing against RSS feeds
(because they homogenize the web experience), something I myself have felt before.
Even when I use an RSS reader, I use it more as a bookmark manager with update notification
than as a way to read the bodies of entries.
¶
XML.com: At Microsoft's Mercy
is an interesting summary of reactions to Microsoft's new XML support in Office.
¶
Creeping toward Xanadu
is a fearful commentary on the growing complexity of web standards.
¶
Ray Ozzie has started up his blog again.
Tuesday 22 April 2003
In work-related news:
Kubi Software Ships Kubi Client.
No, it's not an episode of
Friends about cheating on Monica.
Two open-source projects became availble recently.
Chandler 0.1
was released yesterday.
It is very very early, but I applaud OSAF's determination in getting this
out, and their courage.
There will be many naysayers for this project;
I for one am glad to have it in the mix.
Vera
is a collection of typefaces from Bitsteam
for use in open-source projects.
They look good, and should provide relief from the
never-ending clones of Times and Helvetica.
Sunday 20 April 2003
I wanted a t-shirt with my
stellated logo on it,
so I set up a store at
Cafepress
to make one.
As a result, you can buy one if you like, but I won't be offended if you don't!
Saturday 19 April 2003
OpenEXR is a new image format
developed by
Industrial Light & Magic to accomodate the
needs of film makers. For example, the data is recorded at a higher dynamic
range (using 16-bit floats) than the typical 0 (black) to 1 (white)
that most image formats use.
I have no need for this technology, but it would be cool if I did, and I like
keeping up with advanced CG stuff.
Friday 18 April 2003
Two.
Wed.
Monday 14 April 2003
Time).
Sunday 13 April 2003
A.
I.
Saturday 12 April 2003
Two.
Thursday 10 April 2003
Jake Howlett wrote about
self-googling
(which he accurately describes as vain).
Googling on his whole name, then his last name, and finally his first name,
he was first, second, and 27th in the respective listings.
When I tried the same experiment, I was struck by how similar my results
were: I'm the first
Ned Batchelder,
the second
Batchelder
(the first is actually a 404),
and the 25th
Ned.
What does this mean about me and Jake? Or about blogs? Or about the web?
Is this just a coincidence? What do other people get for similar queries?
Latest Python tidbit: the re module has an option to write
regular expressions in re.VERBOSE format. This means that whitespace
can be used to layout the regular expression in a more readable style,
and comments can be included with hash marks.
For example, this regular expression:
logFmt = '\[[0-9]{8}T[0-9]{6}\.[0-9]{3}Z:[0-9](/[0-9]*)?\][ ]*.*'logFmtRe = re.compile(logFmt)
becomes:
logFmt = ''' \[ [0-9]{8}T[0-9]{6}\.[0-9]{3}Z # the date :[0-9] # the severity (/[0-9]*)? # a possible facility \] [ ]*.* # the message'''logFmtRe = re.compile(logFmt, re.VERBOSE)
Admittedly, regular expressions are pretty dense no matter what
you do, but at least this way you can try to pull them apart a little
for future readers of the code (which includes yourself starting tomorrow).
I've enabled comments here, thanks to
enetation.
I would rather have hacked something together myself, to learn more PHP and
MySQL, but this works, and enetation has done a good job providing an
off-site service, so what the hey.
The (react) links that used to send me email now bring up the comments
window.
Wednesday 9 April 2003
More amazing bookmarklets from Jesse Ruderman:
Web Development Bookmarklets.
Some of these are astounding, primarily
test styles,
which puts up a text window where you can type CSS that is applied live to
the page as you type!
Tuesday 8 April 2003
FreePaperToys is a portal to a world
of online paper print-and-fold-and-glue models. They've got all sorts of
different models, including
Star Wars models.
Cool.
I've always been a fan of paper models. My dad has a bazillion castle
models all over the place. I've designed a few myself, including a pretty
nice model of my last house, made in Visio.
We.
»
read more of: Smoke test... (5 paragraphs)
Monday 7 April 2003
AccordianGuy
has a scary story about lies between people, and the power of a blog to help bring
out the truth:
What happened to me and the new girl.
Sunday 6 April 2003
I have a new IBM T30 laptop, and it is very nice, but the video adapter
has a strange quirk: it can support a ton of different resolutions, and
for each of them, it can drive a monitor at lots of different refresh rates,
except: the LCD's natural size (1400 × 1050), where it can only do 60Hz.
Grr. This means that when using an external monitor, I have to choose a
different resolution, or the monitor flickers.
So I switch resolutions when I switch displays, and my
dispmode utility can do that, but
now I have to also switch between refresh rates. So I added that to
dispmode, and all is well.
Chaco
is a full-featured plotting package built on Numeric and wxPython.
It looks very interesting in its own right, but here's the thing
that caught my eye: MakeMenu.
In the demo script (wxdemo_plot.py), I saw this code:
plot_demo_menu = """ &File Open | Ctrl-O: self.on_open() --- Save as Single page...: self.create_file(None,0) One canvas per page...: self.create_file(None,1) One value per page...: self.create_file(None,2) --- Exit | Ctrl-Q: self.on_exit() &Edit Undo | Ctrl-Z [menu_undo]: self.undo() Redo | Ctrl-Y [menu_redo]: self.redo() #(etc, 30 more lines..)"""
and then later:
self.menu = chaco.wxMenu.MakeMenu( plot_demo_menu, self )
Very cool: a single string to define an entire menu tree, including
the Python code to execute when the item is picked, with the whole
menu constructed by a single call with the string.
Saturday 5 April 2003
Some tool and technology quick links:
¶
cvs2rss
¶
Hydra, a collaborative editor
¶
dynamicobjects spaces
¶
Event Log Monitoring with RSS
Some visually-oriented quick links:
¶
UPS has a new logo
¶
Los Angeles Times Photo Manipulation
¶
Typographica : San Serriffe
¶
The Readerville Forum - Most Coveted Covers
Thursday 3 April 2003
The greatest geometer of the 20th century, Harold Scott MacDonald Coxeter, has died
(obituary).
He was a math uber-geek, with connections to an amazing list of other
luminaries, including Bertrand Russell, Wittgenstein, and Escher.
I first heard of Coxeter as one of the authors of
The 59 Icosahedra,
which sounds like a Hitchcock movie, but is actually a treatise on the
stellations of the icosahedron.
The image below is a diagram of the stellation face of the icosahedron
(more information and pictures
here).
He contributed authoritatively to all areas of geometry, from
introductory textbooks to expositions on non-Euclidean geometery, to
his specialty, extending the concepts of uniform polyhedra to higher dimensions.
As an example of his old-school style, he apparently never used computers,
writing his papers in pencil.
Just being a professional geometer interested in shapes made him seem like a
throwback.
Whenever I try to catch a whiff of what recent geometry work is like, it
seems more like complex algebra or number theory than actual geometry
(aren't there supposed to be shapes in there somewhere?).
Wednesday 2 April 2003
Sean McGrath
has written an article entitled
A study in XML culture and evolution.
It starts out well, making interesting
observations about the differing culture between "document" people and
"data" people.
"Data" people believe in unique ids (names) for data, "document" people
are satisfied with uniqueness among all the fields (addresses). Good point.
Being a "document" person, he doesn't see the need for unique ids for
his data. Fair enough.
But then he tanks, making some sort of leap to the conclusion
that since his data doesn't need names, his XML doesn't need namespaces.
Huh? I'm hoping Sean was mis-edited, or maybe just had an off day.
He seems otherwise to know what he is talking about.
To confuse names for data with namespaces for names of attributes seems
pretty basic to me.
Tuesday 1 April 2003
A few kind readers answered my
implicit plea
for the classic quote about the differing responsibilities of producers
and consumers.
Mark Mascolino was the first to send a pointer to the IETF RFC it first
appeared in: Jon Postel's
RFC 793 - Transimission Control Protocol
(that's TCP to you and me), where it appeared in a section of its own, and
was even given a name
(Robustness Principle):
be conservative in what you do, be liberal in what you accept from others.
Charles Miller wrote to point out the downside of the
philosophy: that being liberal in acceptance means bad implementations are
allowed to flourish, leaving the burden on all future implementations to
forever pick up the slack. He has written about it before:
Grisham trumps Postel.
The XML standard took the exact opposite approach: implementation must be
extremely strict, to prevent the sort of slop that HTML allowed.
So what's the right thing to do?
To paraphrase the witticism about standards,
That's the great thing about design principles: there are so many to choose
from.
FontLab produces
TypeTool 2,
a low-cost font-editing program.
I've long been fascinated by typography (I still have the printer's type
specimen book my mother used briefly at the Village Voice, with my
red crayon scrawls in it).
TypeTool seems to be a solid if not luxurious font editor.
If I only had the time (and inspiration and artisitic ability!)
I would try my hand at it. Let a thousand faces bloom!
2003,
Ned Batchelder | http://nedbatchelder.com/blog/200304.html | crawl-002 | refinedweb | 2,541 | 71.24 |
Introduction
A lot of teams are adopting machine learning (ML) for their products to enable them to achieve more and deliver value. When we think of implementing an ML solution, there are two parts that come to mind:
- Model development.
- Model deployment and CI/CD.
The first is the job of a data scientist, who researches on what model architecture to use, what optimization algorithms work best, and other work pertaining to making a working model.
Once the model is showing satisfactory response on local inputs, it is time to put it into production, where it can be served to the public and client applications.
The requirements from such a production system include, but are not limited to, the following:
- Ability to train the model at scale, across different compute as required.
- Workflow automation that entails preprocessing of data, training, and serving the model.
- An easy-to-configure system of serving the model that works the same for all major frameworks used for machine learning, like Tensorflow and such.
- Platform agnostic; something that runs as good on your local setup as on any cloud provider.
- A user-friendly and intuitive interface that allows the data scientists with zero knowledge of Kubernetes to leverage its power.
Kubeflow is an open-source machine learning toolkit for cloud-native applications that covers all that we discussed above and provides an easy way for anyone to get started with deploying ML in production.
The Kubeflow Central Dashboard
In addition, we need some common storage for features that our model would use for training and serving.
This storage should allow
- Serving of features for both training and inference.
- Data consistency and accurate merging of data from multiple sources.
- Prevent errors like data leaks from happening and so on.
A lot of the teams working on machine learning have their own pipelines for fetching data, creating features, and storing and serving them but in this article, I'll introduce and work with Feast, an open-source feature store for ML.
From tecton.ai
I'll link an amazing article here (What is a Feature Store) that explains in detail what feature stores are, why they are important, and how Feast works in this context.
We'll talk about Feast in the next article in this series.
Contents
- Why do we need Kubeflow?
- Prerequisites
Setup
Feast for feature store
Kubeflow pipelines
Pipeline steps
Run the pipeline
Conclusion
Why do we need Kubeflow?
Firstly, most of the folks developing machine learning systems are not experts in distributed systems. To be able to efficiently deploy a model, a fair amount of experience in GitOps, Kubernetes, containerization, and networking is expected. This is because managing these services is very complex, even for relatively less sophisticated solutions. A lot of time is wasted in preparing the environment and tweaking the configurations before model training can begin.
Secondly, building a highly customized and "hacked-together" solution means that any plans to change the environment or orchestration provider will require a sizeable re-write of code and infrastructure configuration.
Kubeflow is a composable, portable solution that runs on Kubernetes and makes using your ML stack easy and extensible.
Prerequisites
Before we begin, I'll recommend that you get familiar with the following, in order to better understand the code and the workflow.
Docker and Kubernetes (I have built a hands-on, step-by-step course that covers both these concepts. Find it here and the associated YouTube playlist here!
Azure Kubernetes Service. We'll be using it as the platform of choice for deploying our solution. You can check out this seven-part tutorial on Microsoft Learn (an awesome site to learn new tech really fast!) that will help you get started with using AKS for deploying your application.
This page has other quickstarts and helpful tutorials.
Although we're using AKS for this project, you can always take the same code and deploy it on any provider or locally using platforms like Minikube, kind and such.
A typical machine learning workflow and the steps involved. You don't need the knowledge to build a model, but at least an idea of what the process looks like.
This is an example workflow, from this article by Google Cloud.
Some knowledge about Kubeflow and its components. If you're a beginner, you can watch a talk I delivered on Kubeflow at Azure Kubernetes Day from 4.55 hours.
Setup
1) Create an AKS cluster and deploy Kubeflow on it.
The images above show how you can create an AKS cluster from the Azure portal.
This tutorial will walk you through all the steps required, from creating a new cluster (if you haven't already) to finally having a running Kubeflow deployment.
2) Once Kubeflow is installed, you'll be able to visit the Kubeflow Central Dashboard by either port-forwarding, using the following command:
kubectl port-forward svc/istio-ingressgateway -n istio-system 8080:80
or by getting the address for the Istio ingress resource, if Kubeflow has configured one:
kubectl get ingress -n istio-system
The address field in the output of the command above can be visited to open up the dashboard. The following image shows how a dashboard looks on start-up.
The default credentials are email
admin@kubeflow.org and password
12341234. You can configure this following the docs here.
3) Install Feast on your cluster. Follow the guide here.
4) Finally, clone this repository to get all the code for the next steps.
Feast for feature store
After reading the article I linked above for Feast, I assume you've had some idea of what Feast is used for, and why it is important.
For now, we won't be going into the details on how Feast is implemented and will reserve it for the next edition, for the sake of readability.
The code below doesn't use Feast to fetch the features, but local files. In the next article, we'll see how we can plug Feast into our solution without affecting a major portion of the code.
Kubeflow Pipelines
Kubeflow Pipelines is a component of Kubeflow that provides a platform for building and deploying ML workflows, called pipelines. Pipelines are built from self-contained sets of code called pipeline components. They are reusable and help you perform a fixed set of tasks together and manage them through the Kubeflow Pipelines UI.
Kubeflow pipelines offer the following features:
- A user interface (UI) for managing and tracking experiments, jobs, and runs.
- An engine for scheduling multi-step ML workflows.
- An SDK for defining and manipulating pipelines and components.
- Integration with Jupyter Notebooks to allow running the pipelines from code itself.
This is how the Kubeflow pipelines homepage looks like. It contains some sample pipelines that you can run and observe how each step progresses in a rich UI.
You can also create a new pipeline with your own code, using the following screen.
More hands-on footage can be found in my talk that I'll link again here, that I delivered on Kubeflow at Azure Kubernetes Day
How to build a pipeline
The following image summarises the steps I'll take in the next section, to create a pipeline.
The first step is to write your code into a file and then build a Docker image that contains the file.
Once an image is ready, you can use it in your pipeline code to create a step, using something called
ContainerOp. It is part of the Python SDK for Kubeflow.
ContainerOpis used as a pipeline step to define a container operation. In other words, it takes in details about what image to run, with what parameters and commands, as a step in the pipeline.
The code that helps you to define and interact with Kubeflow pipelines and components is the
kfp.dslpackage. DSL stands for domain-specific language and it allows you to write code in python which is then converted into Argo pipeline configuration behind the scenes.
Argo pipelines use containers as steps and have a YAML definition for each step; the DSL package transforms your python code into the definitions that the Argo backend can use to run a workflow.
All of the concepts discussed above will be used in the next section when we start writing our pipeline steps and the code can be found at this GitHub repository.
Pipeline steps
The pipeline we'll be building will consist of four steps, each one built to perform independent tasks.
- Fetch - get data from Feast feature store into a persistent volume.
- Train - use training data to train the RL model and store the model into persistent volume.
- Export - move the model to an s3 bucket.
- Serve - deploy the model for inference using KFServing.
Reminder to keep drinking water.
Fetch
The fetch step would act as a bridge between the feature store (or some other source for our training data) and our pipeline code. While designing the code in this step, we should try to avoid any dependency on future steps. This will ensure that we could switch implementations for a feature store without affecting the code of the entire pipeline.
In the development phase, I have used a
.csv file for sourcing the training data, and later, when we switch to Feast, we won't have to make any changes to our application code.
The directory structure looks like the following:
fetch_from_source.py- the python code that talks to the source of training data, downloads the data, processes it and stores it in a directory inside a persistent volume.
userinput.csv(only in dev environment) - the file that serves as the input data. In production, it'll be redundant as the input will be sourced through Feast. You can find that the default values of the arguments inside the code point to this location.
Dockerfile- the image definition for this step which copies the python code to the container, installs the dependencies, and runs the file.
Writing the pipeline step
# fetch data operations['fetch'] = dsl.ContainerOp( name='fetch', image='insert image name:tag', command=['python3'], arguments=[ '/scripts/fetch_from_source.py', '--base_path', persistent_volume_path, '--data', training_folder, '--target', training_dataset, ] )
A few things to note:
- The step is defined as a ContainerOp which allows you to specify an image for the pipeline step which is run as a container.
- The file
fetch_from_source.pywill be run when this step is executed.
- The arguments here include
base_path: The path to the volume mount.
data: The directory where the input training data is to be stored.
target: The filename to store good input data.
How does it work?
The code inside the
fetch_from_source.py file first parses the arguments passed while running it.
It then defines the paths for retrieving and storing the input data.
base_path = Path(args.base_path).resolve(strict=False) data_path = base_path.joinpath(args.data).resolve(strict=False) target_path = Path(data_path).resolve(strict=False).joinpath(args.target)
The
target_path exists on the mounted volume. This ensures that the training data is visible to the subsequent pipeline steps.
In the next steps, the
.csv file is read as a pandas Dataframe and after some processing, it is stored on the
target_path using the following line.
df.to_csv(target_path, index=False)
Train
The training step contains the code for our ML model. Generally, there would be a number of files hosting different parts of the solution and one file (say, the critical file) which calls all the other functions. Therefore, the first step to containerizing your ML code is to identify the dependencies between the components in your code.
In our case, the file that is central to the training is
run.py. This was created from the
run.ipynb notebook because it is straightforward to execute a file inside the container using terminal commands.
The directory structure looks like the following:
code- directory to host all your ML application files.
train(only in dev environment) - contains the file that serves as the input data. In production, it'll be redundant as the input will be sourced from the persistent volume. You can find that the default values of the arguments inside the code point to this location.
Dockerfile- the image definition for this step which copies all the python files to the container, installs the dependencies, and runs the critical file.
Writing the pipeline step
# train operations['training'] = dsl.ContainerOp( name='training', image='insert image name:tag', command=['python3'], arguments=[ '/scripts/code/run.py', '--base_path', persistent_volume_path, '--data', training_folder, '--outputs', model_folder, ] )
A few things to note:
- The step is defined as a ContainerOp which allows you to specify an image for the pipeline step which is run as a container.
- The file
run.pywill be run when this step is executed.
- The arguments here include
base_path: The path to the volume mount.
data: The directory where the input training data is stored. This is the same as the
target_pathfrom the previous step.
outputs: The directory to store the trained model in.
How does it work?
The code inside the
run.py file first parses the arguments passed while running it.
It then defines the paths for retrieving and storing the input data. This is similar to the code in the previous step.
The first thing that needs to be done is to retrieve input values from the data directory and then, passing them to the training function in your code. A sample is shown below; the pandas Dataframe is built on the input
.csv file.
df = pd.read_csv(data_file) # populate input values for the model to train on feature_1 = df['feature_1'].iloc[0] ... ...
These features are then passed to your ML code for training so this ensures separation of concern between
your retrieval and model code. The model code can be independently developed by an ML engineer without worrying about how the features will be fetched.
To make the model accessible to the "export" step later, we'll have to save it on the persistent volume. We can do it using TensorFlow's library commands.
def save(self, target_path): self.model.save(target_path)
where the path would be the output path constructed using the arguments supplied while executing.
target_path = Path(args.base_path).resolve( strict=False).joinpath(args.outputs) if not os.path.exists(target_path): os.mkdir(target_path)
Export
Once the model is trained and stored on the persistent volume, we can then export it to an S3 bucket.
You can make use of the Minio service which gets installed with Kubeflow as S3 storage. Learn how to add Amazon S3 compatibility to Microsoft Azure Blob Storage here.
This step ensures that the model can later be made available to the public through an inference service. You may ask why we can't just use the existing storage; the answer lies in this file. The KFServing (explained later) component that we use for inference requires an "S3 or GCS compatible directory containing default model" for the
model_uri parameter.
This step has a single goal of fetching the model from the disk and uploading it for the next step.
The directory structure looks like the following:
export_to_s3.py- the python code that makes use of AWS Boto3 SDK to connect to an S3 bucket and perform the upload.
model(only in dev environment) - the directory hosting the model to be uploaded. In production, this functionality will be achieved using a persistent volume at a path supplied to this step as input.
Dockerfile- the image definition for this step which copies the python code to the container, installs the dependencies, and runs the file.
Writing the pipeline step
# export model operations['export'] = dsl.ContainerOp( name='export', image='insert image name:tag', command=['python3'], arguments=[ '/scripts/export_to_s3.py', '--base_path', persistent_volume_path, '--model', 'model', '--s3_bucket', export_bucket ] )
A few things to note:
- The step is defined as a ContainerOp which allows you to specify an image for the pipeline step which is run as a container.
- The file
export_to_s3.pywill be run when this step is executed.
- The arguments here include
base_path: The path to the volume mount.
model: The directory where the model is stored on the persistent volume.
s3_bucket: The name of the bucket to upload the model to.
How does it work?
The code inside the
export_to_s3.py file first parses the arguments passed while running it.
It then defines the path for retrieving the model. This will be used for specifying the source for the
boto3 code below.
Uploading to a bucket
Boto3 is the name of the Python SDK for AWS. It allows you to directly create, update, and delete AWS resources from your Python scripts. You can check out examples of using the SDK for accessing S# resources here. The
upload_file method is of interest to us. Following standard practices, we can write the following code to perform the upload operation.
s3.Bucket(args.s3_bucket).upload_file( Filename=str(model_file), Key='model_latest.h5')
Before we can run this step, we need to create the S3 client. The code below does that using the
resource function of the client. You can look at the source code here and here to get an understanding of what parameters to supply to create it and what the
resource function returns.
s3 = boto3.resource('s3', region_name='us-east-1', endpoint_url="- service.kubeflow:9000", aws_access_key_id='AK...', aws_secret_access_key='zt...')
You might notice that I've added the access key and the secret right into the code while initializing the s3 resource. This is not the best practice as it might lead to an accidental leak when you share your code online.
Thankfully, there are other ways of passing the credentials to the
boto3 client.
You can either choose environment variables or create a file for storing your keys. Check out the docs here for more options.
Once the upload is done, we can move to implement our final step, the serving of the model.
Serve
To make our model accessible to other applications and users, we need to set up an inference service. In other words, put our model in production. The following things need to be determined before we start implementing this step.
The framework to be used. Kubeflow has support for Tensorflow Serving, Seldon core among others. See here.
The inputs to the model. This will be used to construct a JSON payload to be used for scoring.
Kubeflow Pipelines comes with a pre-defined KFServing component which can be imported from the GitHub repo and reused across the pipelines without the need to define it every time. KFServing is Kubeflow's solution for "productionizing" your ML models and works with a lot of frameworks like Tensorflow, sci-kit, and PyTorch among others.
The directory structure looks like the following:
kfserving-component.yaml- This is the KFServing component, imported from Github. Any customizations required can be made, after reading through the comments.
Writing the pipeline step
kfserving = components.load_component_from_file( '/serve/kfserving-component.yaml') operations['serving'] = kfserving( action="apply", default_model_uri=f"s3://{export_bucket}/model_latest.h5", model_name="demo_model", framework="tensorflow", )
A few things to note:
- The
kfservingcomponent is loaded using a function from the Python SDK.
- The component has several configurable parameters:
default_model_uri: This is the address to the model, expressed as an S3 URI.
model_name: The name of the model.
framework: The framework used for developing the model; could be TensorFlow, PyTorch, and such.
How does it work?
When this code is executed, KFServing will create an inference service. A sample is shown below:
apiVersion: serving.kubeflow.org/v1alpha2 kind: InferenceService metadata: name: sample-serve namespace: default spec: default: predictor: serviceAccountName: serve-sa tensorflow: resources: requests: cpu: 1 memory: 1Gi runtimeVersion: 1.x.x storageUri: s3://bucket/model
When the component is executed, you'll find the YAML definition of the InferenceService in the output logs. This is because the component file has the
outputs parameter defined as below:
outputs: - {name: InferenceService Status, type: String, description: 'Status JSON output of InferenceService'}
The status of this resource will contain an HTTP URL, which can be accessed using the following command.
kubectl get inferenceservice <name of service> -n kfserving -o jsonpath='{.status.url}'
We can then POST requests to this endpoint to get back predictions. A sample request is shown below:
url = f"http://{model}.{NAMESPACE}.svc.cluster.local/v1/models/{model}:predict" ! curl -L $url -d@input.json
Run the pipeline
Once the pipeline code is ready, we can then compile the code to generate a
tar file which can be uploaded to the Pipelines UI to create runs and experiments. You can also choose to directly run the pipeline code, using the SDK, on a Jupyter Notebook.
The code for it could be the following:
client = kfp.Client() run_result = client.create_run_from_pipeline_func( pipeline_func=sample_pipeline, experiment_name='experiment_name', run_name='run_name', arguments='arguments', )
On running the pipeline, you can see all the steps listed out as they are executing, on a graph. The properties pertaining to the step can be seen on the sidebar.
You can find input/output values, metadata, information about the volumes used, the pods that are running your step, and other helpful information from the UI itself.
Conclusion
Congratulations on making it this far. I acknowledge that this turned out to be longer than most typical articles but I couldn't make myself agree to leave out any of the details that made way into this article.
To recap, we understood why Kubeflow is an important tool to help people with less experience in distributed systems and Kubernetes deploy and manage their machine learning models.
We looked at how a pipeline can be designed, what things to keep in mind while containerizing your code into different steps, and how we can stitch all the different tasks into one single reusable pipeline. The complete pipeline code can be found at the root directory in my repository linked earlier.
In the next article in the series, we'll take our solution one step closer to production by integrating Feast into our pipeline. The directories we used in our pipeline so far, can then be discarded and all exchange of data will be handled by the persistent volume and Feast.
I hope you have a better idea after reading this piece on how to start building machine learning pipelines using some amazing open-source tools. Feel free to reach out to me if you have any questions 👋
LinkedIn - wjayesh
Twitter - wjayesh
Discussion (0) | https://dev.to/wjayesh/putting-an-ml-model-into-production-using-feast-and-kubeflow-on-azure-part-i-3i33 | CC-MAIN-2021-21 | refinedweb | 3,718 | 55.95 |
+1 here too. This could be added easily to Python 2.6. --Guido On 7/7/06, Nick Coghlan <ncoghlan at gmail.com> wrote: > Fred L. Drake, Jr. wrote: > > On Thursday 06 July 2006 13:22, tomer filiba wrote: > > > my suggestion is simple -- replace this mechanism with a __dir__ - > > > a special method that returns the list of attributes of the object. > > > > > > rationale: > > > * remove deprecated __methods__, etc. > > > * symmetry -- just like hex() calls __hex__, etc. > > > * __methods__ and __members__ are lists rather than callable > > > objects, which means they cannot be updated on-demand > > > > +1 > > +1 here, too. > > It would also allow objects which override __getattribute__ and/or __getattr__ > to make dir() provide a sane answer (or raise an exception to indicate that a > sane answer isn't possible). (This was something that actually came up when > trying to implement a namespace object that *didn't* automatically fall back > to its class namespace for Python level attribute access) > > For backwards compatibility, dir() could still fall back to the current > mechanism if __dir__ isn't found. > > Cheers, > Nick. > > -- > Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia > --------------------------------------------------------------- > > _______________________________________________ > Python-Dev mailing list > Python-Dev at python.org > > Unsubscribe: > -- --Guido van Rossum (home page:) | http://mail.python.org/pipermail/python-dev/2006-July/067139.html | crawl-002 | refinedweb | 197 | 65.62 |
This is your resource to discuss support topics with your peers, and learn from each other.
09-12-2013 08:07 AM
Hello guys.
Long time listener, first time caller.
I would like to have a spinning wheel in my app but I'm struggling with the maths, no problems with animation side that's all fine and finished.
From an inital x,y position when the finger goes down to an x,y position on the finger coming up, how can I work out if the users intention was to spin the wheel clockwise or anti-clockwise?
Thinking about it a swipe from right to left is anti-clockwise above the wheel center but the same swipe below the center would be clockwise. The code I have now is all if statements but I'm sure there must be a maths solution.
Thanks for any help and QML example code would be nice.
09-12-2013 08:51 AM
Just thinking about the maths you're really looking from the cross product of the vector from the wheel centre to the initial and wheel centre to the final points. So, if the wheel centre is (Xw, Yw) and the finger down point is (Xi, Yi) and the finger up point is (Xf, Yf) then the component of the cross product ( in to or out of the plane ) would be:
(Xi - Xw)(Yf - Yw) - (Yi - Yw)(Xf -Xw)
If this is > 0 then the motion is anti-clockwise around the wheel centre and if < 0 it's clockwise round the wheel centre. If it's 0 then the swipe is along a radius of the wheel.
I think I've got the maths right :-)
09-12-2013 08:54 AM
It's a little easier to plan out if you map out your screen as a graph with the middle being 0
similar to these
so if their finger travels from -2, -2 to 2, 2 and on the way passed -2,2 this means they went clockwise(I think, bad math here
)
but that's essentially how it works.
I'm not sure if there's a way the system refers to the center as 0, if not just replace 0 with the center pixel #, same idea is involved to find the solution
09-12-2013 09:02 AM - edited 09-12-2013 09:06 AM
@sashkyle It's a simple transform to find the center just half the width and height and already in my code. The way you've suggested is my current implentation. Thanks for your response though.
@jomurray Thanks so much this is exactly what I'm looking for, I'm sure it will work or if it doesn't will just need a tweak somewhere.
09-12-2013 09:55 AM
Okay I tried it but still spinning the wrong way when a swipe is above the center or to the left of center.
This is my code:
Page { function spinDirection(w, h, dx, dy, ux, uy) { var cx = w / 2.0; var cy = h / 2.0; return ((dx - cx) * (uy - cy)) - ((dy - cy) * (ux - cx)); } Container { property int down_x: 0.0 property int down_y: 0.0 layout: DockLayout { } onTouch: { if (event.isDown()) { down_x = event.localX; down_y = event.localY; } if (event.isUp()) { if (spinDirection(400, 400, down_x, down_y, event.localX, event.localY) > 0) rotateLeft.play(); else rotateRight.play(); } } ImageView { id: wheel horizontalAlignment: HorizontalAlignment.Center verticalAlignment: VerticalAlignment.Center imageSource: "asset:///images/wheel.png" preferredHeight: 400.0 preferredWidth: 400.0 animations: [ RotateTransition { id: rotateLeft fromAngleZ: 0.0 toAngleZ: 360.0 duration: 3000.0 easingCurve: StockCurve.ExponentialOut }, RotateTransition { id: rotateRight fromAngleZ: 360.0 toAngleZ: 0.0 duration: 3000.0 easingCurve: StockCurve.ExponentialOut } ] } } } | https://supportforums.blackberry.com/t5/Native-Development/Spinning-wheel/td-p/2586345 | CC-MAIN-2017-04 | refinedweb | 615 | 75 |
Q. C Program to Find the Sum of Digits in a Given Number.
Here you will find an algorithm and program in C or declare it. Step 2: Get the modulus/remainder of the number Step 3: Sum the remainder of the number Step 4: Divide the number by 10 Step 5: Repeat the steps from 2 to 4 till the number is greater than 0. STOP
C Program to Find the Sum Of Digits in Number
#include <stdio.h> int sum_digit(long long num) { int sum = 0,rem; while (num != 0) { rem=num%10; num = num / 10; sum=sum+rem; } return sum; } int main(void) { long long num = 123456; printf("Sum Of Digits : %d", sum_digit(num)); return 0; }
Output
Sum Of Digits : 21 | https://letsfindcourse.com/c-coding-questions/c-program-to-find-the-sum-of-digits-in-number | CC-MAIN-2022-27 | refinedweb | 124 | 69.31 |
Change global prereferences from command line
Scripted change of Global HTTP Authentication PropertiesHowdy folks,
Please can anyone think of a way to change global preferences (specifically the Global HTTP Authentication Properties) via a script (i.e. non-interactively)?
The sitution is: We have several related applications, each with its own SOATest suite (i.e. $app-soatests.tst). Each application secures its WSDL with Basic Authentication... which we deal-with in SOATest (when we're running the tests interactively) by setting the Global HTTP Auth properties to the admin_user/password of the application we are testing. The applications cannot (without a lot of bureaucratic red-tape) use the same admin_user/password.
My task is to setup an ABT-suite for all these applications, so I guess I need to change the global-prefs on-the-fly... so please, can anyone think of a way to do this, from the command line, or otherwise via a script.
Merry Christmas all. Keith.
0
The WSDL itself (not just the service/s described therein) are secured by basic-authentication (they are not and cannot be public). SOATest needs to retrieve the WSDL, and rhe only way to specify the username/password for this wsdl-request is to set the global-auth properties, which are an attribute of ?the current user? of the current-machine (they are evidently NOT stored in the soatest-file)... there is no facility to specify the wsdl-request-auth-properties on a per-test-suit (let alone per-wsdl, or per-test) basis.
So... Please, is there a way to set the Global HTTP Authentication properties on the fly?
<aside>We have another possible workaround, but it's fugly. We'd save a copy of the WSDL's locally, and point soatest at them. In the ABT environment: To regression test the WSDLs, we'd retrieve the latest WSDL's from the server and diff each one with "the local cache" in a java program. I would prefer NOT to have to maintain test-harness code and configuration outside of SOATest... I may as well have stuck with our existing junit test-cases.</aside>
Thanking you sir.
Cheers. Keith.
Changing the username/password for the Global Authentication is possible but one thing you need to be aware of is that some of the Java classes exposed in the script is not part of our public API. That said, these Java classes are subject to change which may break the script in the long run. In fact, I need to provide you two different scripts one for 5.5.x and one for 6.0 as the class and interfaces does change between the two versions. In other words, you must update your .tst files with the second script when you upgrade from 5.5.x to 6.0.
For 5.5.x use the following script:
from webtool.app import *
def changeAuthValues(input, context):
webPrefs = WebtoolApp.getWebtoolAppPreferences()
if (webPrefs != None):
secPrefs = webPrefs.getSecurityPreferences()
if (secPrefs != None):
auth = secPrefs.getAuthentication()
if (auth != None):
auth.getUsername().setValue("yourUserNameValue")
auth.getPassword().setValue("yourPasswordValue")
For 6.0 use the following script:
CODE
from webtool.app import *
from com.parasoft.preferences import *
def changeAuthValues(input, context):
secPrefs = AppPreferenceProvider.getSecurityPreferenceProvider()
if (secPrefs != None):
authPrefs = secPrefs.getAuthenticationPreferenceProvider()
if (authPrefs != None):
authPrefs.setUsername("yourUserNameValue")
authPrefs.setPassword("yourPasswordValue")
You sir, are a life saver!
I've just gotten back into setting up this ABT environment and associated soatest-suites... That little script is going to save me a boring couple of days changing the auth-settings on every single request.... Yahoo!
Sorry for the delayed response. I will allways get back to my posts... just have to wait for testing to come back to the top of the pile ;-)
I thank you for your assistance... SOATest is THE best supported application I've ever used. And you can quote me on that.
Cheers mate. Keith. | https://forums.parasoft.com/discussion/1914/change-global-prereferences-from-command-line | CC-MAIN-2018-34 | refinedweb | 646 | 51.34 |
On 04/26/2012 09:02 AM, Vincent Lefevre wrote: > On 2012-04-26 08:14:51 -0600, Eric Blake wrote: >> If I write C11 code: >> >> #include <stdnoreturn.h> >> #include <stdio.h> >> >> then I expect things to work. But _MSC_VER system headers use noreturn >> in a non-C11 manner, such that the only way for this to work via gnulib >> is to make 'noreturn' a no-op on that platform, until such time as >> Microsoft updates their headers. Microsoft has a history of namespace >> pollution; had their compiler used '__declspec (__noreturn)' instead of >> '__declspec (noreturn)', we would not be facing this clash. > > GCC has the same kind of problem. Though the __ version can also > be used, it is poorly documented, and examples have the version > without __. And some libraries under GNU/Linux reuse this version > without __. Any installed header that does not use the __ version is buggy. Thankfully, in the open source world, you can post bug reports and patches to get those buggy packages fixed; which is a much different story than for the proprietary _MSC_VER system headers. > >> The whole point of gnulib is to give me enough support so that I can >> write code that is valid C11, and also which compiles under non-C11 >> compilers, without any extra #ifdef work in my code (since gnulib >> took care of it for me). > > In MPFR, we want more: to be able to use the C99/C11 features and > extensions from compilers (because the feature is not in the C > standard or is too recent for the compilers). Not only the fact > that the code compiles, but also that the feature is used. Fair enough. But then check directly for that feature, instead of asking gnulib to do it for you, and feel free to use gnulib's checks as a starting point. And I'm still not convinced that we are ready to promote this into an autoconf macro quite yet; on the other hand, if we had someone working on improving the family of C macros to make it easier to tell C89, C99, and now C11 apart, as well as allowing packages to specify which flavor of language they are specifically targetting, then at that point, AC_C_NORETURN might make sense as a part of probing for C11. >> >> Not if they were compliant to C99 (since C99 didn't reserve 'noreturn', >> then system headers under C99 mode should not be using that symbol). > > Almost no compilers/systems are compliant to C99. For instance, > under Linux, GCC defines "unix" and "linux" to 1, while they are > not reserved. Even when in --std=c99 mode? I can understand this in --std=gnu99 mode (since gnu99 explicitly allows extensions). This particular pollution is rather pervasive due to historical practice, but if it bothers you that much, I'm sure you could file a bug report, and that someone working on gcc or glibc might be willing to help you address it. >>. -- Eric Blake address@hidden +1-919-301-3266 Libvirt virtualization library
signature.asc
Description: OpenPGP digital signature | https://lists.gnu.org/archive/html/autoconf/2012-04/msg00052.html | CC-MAIN-2016-44 | refinedweb | 511 | 66.98 |
An ext’.
Changes in 3.0 (released 01/07/2008)
Namespaces have been greatly simplified. There are no namespace modules any longer. An element class can be assigned a namespace by setting the xmlns class attribute to the namespace name. Global attributes can be assigned a namespace by setting the xmlns attribute on the attribute class itself (not on the Attrs class). The classes Prefixes and NSPool are gone too. Instead a new class Pool is used to specify which classes should be used for parsing.
Dependency on PyXML has finally been dropped. XIST now uses its own XML parsing API. Two parsers are available: One based on expat and one based on a custom version of sgmlop.
Tree traversal has been rewritten again. XFind expressions involving multiple uses of // now work correctly. The method walk now doesn’t yield Cursor objects, but simple path lists (actually it’s always the same list, if you want distinct lists use walkpath). Applying XFind expressions to nodes directly is no longer supported, you have to call walk, walknode or walkpath with the XFind expression instead. Many XFind operators have been renamed and/or reimplemented (see the documentation for the xfind module for more information).
The methods __getitem__, __setitem__ and __delitem__ for Frag and Element now support the new walk filters, so you can do:
- del node[html.p] to delete all html.p child elements of node;
- del node[html.p[2]] to delete only the third html.p;
- node[xfind.hasclass("note")] = html.p("There was a note here!") to replace several child nodes with a new one;
- for c in node[xfind.empty]: print c.bytes() to print all empty (element) children of node;
- del node[node[0]] to delete the first child node (which is silly, but illustrates that you can pass a node to get/replace/delete that node);
A new module ll.xist.css has been added which contains CSS related functionality: The generator function iterrules can be passed an XIST tree and it will produce all CSS rules defined in any html.link or html.style elements or imported by them (via the CSS rule @import). This requires the cssutils package.
The function applystylesheets modifies the XIST tree passed in by removing all CSS (from html.link and html.style elements and their @import``ed stylesheets) and putting the styles into ``style attributes of the affected elements instead.
The function selector returns a tree walk filter from a CSS selector passed as a string.
Constructing trees can now be done with with blocks. Code looks like this:
with xsc.Frag() as node: +xml.XML() +html.DocTypeXHTML10transitional() with html.html(): with html.head(): +meta.contenttype() +html.title("Example page") with html.body(): +html.h1("Welcome to the example page") with html.p(): +xsc.Text("This example page has a link to the ") +html.a("Python home page", href="") +xsc.Text(".") print node.conv().bytes(encoding="us-ascii")
Also the function xsc.append has been renamed to add and supports with blocks now instead of XPython.
A subset of ReST is supported now for docstrings when using the ll.xist.ns.doc module. The module attribute __docformat__ is now honored (Set it to "xist" to get XIST docstrings).
Many classes in the ll.xist.ns.doc have been renamed to more familiar names (from HTML, XHTML 2 or ReST).
The media attribute of html.link and html.style now has a method hasmedia.
The node method asBytes has been renamed to bytes and bytes has been renamed to iterbytes.
The node method asString has been renamed to string and a new method iterstring has been added.
ll.xist.ns.xml.XML10 is gone now. Use ll.xist.ns.xml.XML instead.
xsc.tonode now will raise an exception when it can’t handle an argument instead of issuing a warning.
A class attribute empty inside element classes will now no longer get converted into model.
ll.xist.ns.doc.pyref now copes better with decorated methods.
The deprecated Element methods hasAttr, hasattr, isallowedattr, getAttr, getattr, setDefaultAttr, setdefaultattr, attrkeys, attrvalues, attritems, iterattrkeys, iterattrvalues, iterattritems, allowedattrkeys, allowedattrvalues, allowedattritems, iterallowedattrkeys, iterallowedattrvalues, iterallowedattritems and copyDefaultAttrs have been removed. The deprecated Attrs method copydefaults has been removed too.
The namespace module ll.xist.ns.cond has been removed.
When calling the function ll.xist.parsers.parseURL the arguments headers and data are now passed along to the parser’s method only if they are specified. This makes it possible to pass ssh URLs to ll.xist.parsers.parseURL.
The methods withnames and withoutnames have been split into two that take Python names and two that take XML names. Multiple arguments are used now (instead of one argument that must be a sequence). Passing a namespace to remove all attributes from the namespace is no longer supported.
The Attrs methods updatenew and updatexisting have been removed.
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/ll-xist/3.0/ | CC-MAIN-2019-09 | refinedweb | 839 | 60.31 |
NAME
msgrcv -- receive a message from a message queue
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> int msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
DESCRIPTION messages, mtext is an array of bytes, with a size up to that of the system limit (MSGMAX). The value of msgtyp has one of the following meanings: +o The msgtyp argument is greater than 0. The first message of type msgtyp will be received. +o The msgtyp argument is equal to 0. The first message on the queue will be received. +o: +o A message of the requested type becomes available on the message queue. +o The message queue is removed, in which case -1 will be returned, and errno set to EINVAL. +o A signal is received and caught. -1 is returned, and errno set to EINTR. If a message is successfully received, the data structure associated with msqid is updated as follows: +o msg_cbytes is decremented by the size of the message. +o msg_lrpid is set to the pid of the caller. +o msg_lrtime is set to the current time. +o. | http://manpages.ubuntu.com/manpages/precise/man2/msgrcv.2freebsd.html | CC-MAIN-2013-20 | refinedweb | 195 | 67.25 |
IEX-API-PythonIEX-API-Python
This module is currently being actively developed. Feedback is welcomed.
SummarySummary
The
iex-api-python module is a wrapper for the IEX API, and is designed to closely map to the organization of the original API while adding functionality. A few examples of the additional functionality are:
- Many queries are retadurned as Pandas Dataframes.
- Built-in support for websockets connections.
- Option to format timestamps as datetime objects or ISO format.
InstallationInstallation
Note that you must be using Python >=3.6
pip install iex-api-python
Getting StartedGetting Started
From the API documenation:
The IEX API is a set of services designed for developers and engineers. It can be used to build high-quality apps and services. We’re always working to improve the IEX API. Please check back for enhancements and improvements.
- Read the terms.
- Read the manual and start building.
- Attribute properly.
The API terms apply to the use of this module, as does the requirement to properly attribute the use of IEX data.
OrganizationOrganization
The
IEX-API-Python module is designed to map closely to the API from IEX. For many of the API calls, the resulting dataset is better represented in a tabular format. For these calls, data are returned as a pandas.DataFrame.
ExamplesExamples
To illustrate a few things you can do with
iex-api-python, take a look at the examples below.
Fetch all stock symbols
from iex import reference reference.symbols() # Returns a Pandas Dataframe of all stock symbols, names, and more.
symbol date iexId isEnabled \ 0 A 2018-05-16 2 True 1 AA 2018-05-16 12042 True 2 AABA 2018-05-16 7653 True 3 AAC 2018-05-16 9169 True
Get a stock price
from iex import Stock Stock("F").price()
11.4
Get a stocks price for the last year
from iex import Stock Stock("F").chart_table(range="1y")
change changeOverTime changePercent close date high \ 0 0.000000 0.000000 0.000 10.2760 2017-05-16 10.3982 1 -0.169075 -0.016446 -1.645 10.1070 2017-05-17 10.2854 2 0.028180 -0.013712 0.279 10.1351 2017-05-18 10.1633 3 0.075144 -0.006394 0.741 10.2103 2017-05-19 10.2760 4 0.216042 0.014626 2.116 10.4263 2017-05-22 10.4545 5 -0.046966 0.010062 -0.450 10.3794 2017-05-23 10.4874 6 -0.084539 0.001830 -0.814 10.2948 2017-05-24 10.3888 ... | https://libraries.io/pypi/iex-api-python | CC-MAIN-2019-18 | refinedweb | 419 | 70.39 |
These electronic exercises (with solutions) accompany the book chapter "A Gene Ontology Tutorial in Python" by Alex Warwick Vesztrocy and Christophe Dessimoz, to appear in The Gene Ontology Handbook, C Dessimoz and N Skunca Eds, Springer Humana.
Version: 1.0.2 (Feb 2019): Updated QuickGO API calls and usage of GOATOOLS to version 0.8.12
First, we need to load the GOATools library. This enables us to parse the Gene Ontology (GO) OBO file. For more information on GOATools, see their documentation.
# Import the OBO parser from GOATools from goatools import obo_parser
In order to download the GO OBO file, we also require the
wget and
os libraries.
import wget import os
Now, we can download the OBO file into the
'./data' folder using the following. We are going to download the
go-basic.obo version of the ontology, which is guaranteed to be acyclic, which means that annotations can be propagated up the graph.
go_obo_url = '' data_folder = os.getcwd() + '/data' # Check if we have the ./data directory already if(not os.path.isfile(data_folder)): # Emulate mkdir -p (no error if folder exists) try: os.mkdir(data_folder) except OSError as e: if(e.errno != 17): raise e else: raise Exception('Data path (' + data_folder + ') exists as a file. ' 'Please rename, remove or change the desired location of the data path.') # Check if the file exists already if(not os.path.isfile(data_folder+'/go-basic.obo')): go_obo = wget.download(go_obo_url, data_folder+'/go-basic.obo') else: go_obo = data_folder+'/go-basic.obo'
The path to the GO OBO file is now stored in the variable
go_obo.
print(go_obo)
Now we can create a dictionary of the GO terms, using the
obo_parser from GOATools.
go = obo_parser.GODag(go_obo)
Using the
get_term() function, listed below, answer the following questions.
Note: the
get_oboxml() function listed in the chapter, in Source Code 2.1, will no longer work. This is due to an API overhaul of the EMBL-EBI's QuickGO browser.
For the interested reader, it is also possible to use the
bioservices library, in order to retrieve information from QuickGO (as well as many other web services).
from future.standard_library import install_aliases install_aliases() from urllib.request import urlopen import json def get_term(go_id): """ This function retrieves the definition of a given Gene Ontology term, using EMBL-EBI's QuickGO browser. Input: go_id - a valid Gene Ontology ID, e.g. GO:0048527. """ quickgo_url = "" + go_id ret = urlopen(quickgo_url) # Check the response if(ret.getcode() == 200): term = json.loads(ret.read()) return term['results'][0] else: raise ValueError("Couldn't receive information from QuickGO. Check GO ID and try again.")
import Bio.UniProt.GOA as GOA
First we need to download a GAF file from the EBI FTP website, which hosts the current and all previous UniProt-GOA annotations. The links to these can be found on the EBI GOA Downloads page.
As an example, we are going to download the reduced GAF file containing gene association data for Arabidopsis Thaliana.
import os from ftplib import FTP arab_uri = '/pub/databases/GO/goa/ARABIDOPSIS/goa_arabidopsis.gaf.gz' arab_fn = arab_uri.split('/')[-1] # Check if the file exists already arab_gaf = os.path.join(data_folder, arab_fn) if(not os.path.isfile(arab_gaf)): # Login to FTP server ebi_ftp = FTP('') ebi_ # Logs in anonymously # Download with open(arab_gaf,'wb') as arab_fp: ebi_('RETR {}'.format(arab_uri), arab_fp.write) # Logout from FTP server ebi_
Now we can load all the annotations into a dictionary, using the iterator from the BioPython package (
Bio.UniProt.GOA.gafiterator).
import gzip # File is a gunzip file, so we need to open it in this way with gzip.open(arab_gaf, 'rt') as arab_gaf_fp: arab_funcs = {} # Initialise the dictionary of functions # Iterate on each function using Bio.UniProt.GOA library. for entry in GOA.gafiterator(arab_gaf_fp): uniprot_id = entry.pop('DB_Object_ID') arab_funcs[uniprot_id] = entry
Now we have a structure of the annotations which can manipulated. Each of the entries have been loaded in the following form.
print(arab_funcs[list(arab_funcs.keys())[0]])
In this section, the
GOEnrichmentStudy() function from the GOATools library will be used to perform GO enrichment analysis.
from goatools.go_enrichment import GOEnrichmentStudy
Perform an enrichment analysis using the list of genes with the "growth" keyword from exercise 3.1.c, and the GO structure from exercise 2.1.
The population is the functions observed in the Arabidopsis thaliana GOA file.
pop = arab_funcs.keys()
Then, we need to create a dictionary of genes with their UniProt ID as a key and their set of GO annotations as the values.
assoc = {} for x in arab_funcs: if x not in assoc: assoc[x] = set() assoc[x].add(str(arab_funcs[x]['GO_ID']))
Now, the study set here is those genes with the "growth" keyword, found previously.
study = growth_dict.keys()
In this section we look at how to compute semantic similarity between GO terms.
from collections import Counter class TermCounts(): ''' TermCounts counts the term counts for each ''' def __init__(self, go, annots): ''' Initialise the counts and ''' # Backup self._go = go # Initialise the counters self._counts = Counter() self._aspect_counts = Counter() # Fill the counters... self._count_terms(go, annots) def _count_terms(self, go, annots): ''' Fills in the counts and overall aspect counts. ''' for x in annots: # Extract term information go_id = annots[x]['GO_ID'] namespace = go[go_id].namespace self._counts[go_id] += 1 rec = go[go_id] parents = rec.get_all_parents() for p in parents: self._counts[p] += 1 self._aspect_counts[namespace] += 1 def get_count(self, go_id): ''' Returns the count of that GO term observed in the annotations. ''' return self._counts[go_id] def get_total_count(self, aspect): ''' Gets the total count that's been precomputed. ''' return self._aspect_counts[aspect] def get_term_freq(self, go_id): ''' Returns the frequency at which a particular GO term has been observed in the annotations. ''' try: namespace = self._go[go_id].namespace freq = float(self.get_count(go_id)) / float(self.get_total_count(namespace)) except ZeroDivisionError: freq = 0 return freq | https://nbviewer.jupyter.org/urls/dessimozlab.github.io/go-handbook/GO%20Tutorial%20in%20Python%20-%20Exercises.ipynb | CC-MAIN-2019-13 | refinedweb | 964 | 51.44 |
In this chapter, let us write a simple Long Short Term Memory (LSTM) based RNN to do sequence analysis. A sequence is a set of values where each value corresponds to a particular instance of time. Let us consider a simple example of reading a sentence. Reading and understanding a sentence involves reading the word in the given order and trying to understand each word and its meaning in the given context and finally understanding the sentence in a positive or negative sentiment.
Here, the words are considered as values, and first value corresponds to first word, second value corresponds to second word, etc., and the order will be strictly maintained. Sequence Analysis is used frequently in natural language processing to find the sentiment analysis of the given text.
Let us create a LSTM model to analyze the IMDB movie reviews and find its positive/negative sentiment.
The model for the sequence analysis can be represented as below −
The core features of the model are as follows −
Input layer using Embedding layer with 128 features.
First layer, Dense consists of 128 units with normal dropout and recurrent dropout set to 0.2.
Output layer, Dense consists of 1 unit and ‘sigmoid’ activation function.
Use binary_crossentropy as loss function.
Use adam as Optimizer.
Use accuracy as metrics.
Use 32 as batch size.
Use 15 as epochs.
Use 80 as the maximum length of the word.
Use 2000 as the maximum number of word in a given sentence.
Let us import the necessary modules.
from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Embedding from keras.layers import LSTM from keras.datasets import imdb
Let us import the imdb dataset.
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words = 2000)
Here,
imdb is a dataset provided by Keras. It represents a collection of movies and its reviews.
num_words represent the maximum number of words in the review.
Let us change the dataset according to our model, so that it can be fed into our model. The data can be changed using the below code −
x_train = sequence.pad_sequences(x_train, maxlen=80) x_test = sequence.pad_sequences(x_test, maxlen=80)
Here,
sequence.pad_sequences convert the list of input data with shape, (data) into 2D NumPy array of shape (data, timesteps). Basically, it adds timesteps concept into the given data. It generates the timesteps of length, maxlen.
Let us create the actual model.
model = Sequential() model.add(Embedding(2000, 128)) model.add(LSTM(128, dropout = 0.2, recurrent_dropout = 0.2)) model.add(Dense(1, activation = 'sigmoid'))
Here,
We have used Embedding layer as input layer and then added the LSTM layer. Finally, a Dense layer is used as output layer.
Let us compile the model using selected loss function, optimizer and metrics.
model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
LLet us train the model using fit() method.
model.fit( x_train, y_train, batch_size = 32, epochs = 15, validation_data = (x_test, y_test) )
Executing the application will output the below information −
Epoch 1/15 2019-09-24 01:19:01.151247: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not co mpiled to use: AVX2 25000/25000 [==============================] - 101s 4ms/step - loss: 0.4707 - acc: 0.7716 - val_loss: 0.3769 - val_acc: 0.8349 Epoch 2/15 25000/25000 [==============================] - 95s 4ms/step - loss: 0.3058 - acc: 0.8756 - val_loss: 0.3763 - val_acc: 0.8350 Epoch 3/15 25000/25000 [==============================] - 91s 4ms/step - loss: 0.2100 - acc: 0.9178 - val_loss: 0.5065 - val_acc: 0.8110 Epoch 4/15 25000/25000 [==============================] - 90s 4ms/step - loss: 0.1394 - acc: 0.9495 - val_loss: 0.6046 - val_acc: 0.8146 Epoch 5/15 25000/25000 [==============================] - 90s 4ms/step - loss: 0.0973 - acc: 0.9652 - val_loss: 0.5969 - val_acc: 0.8147 Epoch 6/15 25000/25000 [==============================] - 98s 4ms/step - loss: 0.0759 - acc: 0.9730 - val_loss: 0.6368 - val_acc: 0.8208 Epoch 7/15 25000/25000 [==============================] - 95s 4ms/step - loss: 0.0578 - acc: 0.9811 - val_loss: 0.6657 - val_acc: 0.8184 Epoch 8/15 25000/25000 [==============================] - 97s 4ms/step - loss: 0.0448 - acc: 0.9850 - val_loss: 0.7452 - val_acc: 0.8136 Epoch 9/15 25000/25000 [==============================] - 95s 4ms/step - loss: 0.0324 - acc: 0.9894 - val_loss: 0.7616 - val_acc: 0.8162Epoch 10/15 25000/25000 [==============================] - 100s 4ms/step - loss: 0.0247 - acc: 0.9922 - val_loss: 0.9654 - val_acc: 0.8148 Epoch 11/15 25000/25000 [==============================] - 99s 4ms/step - loss: 0.0169 - acc: 0.9946 - val_loss: 1.0013 - val_acc: 0.8104 Epoch 12/15 25000/25000 [==============================] - 90s 4ms/step - loss: 0.0154 - acc: 0.9948 - val_loss: 1.0316 - val_acc: 0.8100 Epoch 13/15 25000/25000 [==============================] - 89s 4ms/step - loss: 0.0113 - acc: 0.9963 - val_loss: 1.1138 - val_acc: 0.8108 Epoch 14/15 25000/25000 [==============================] - 89s 4ms/step - loss: 0.0106 - acc: 0.9971 - val_loss: 1.0538 - val_acc: 0.8102 Epoch 15/15 25000/25000 [==============================] - 89s 4ms/step - loss: 0.0090 - acc: 0.9972 - val_loss: 1.1453 - val_acc: 0.8129 25000/25000 [==============================] - 10s 390us/step
Let us evaluate the model using test data.
score, acc = model.evaluate(x_test, y_test, batch_size = 32) print('Test score:', score) print('Test accuracy:', acc)
Executing the above code will output the below information −
Test score: 1.145306069601178 Test accuracy: 0.81292 | https://www.tutorialspoint.com/keras/keras_time_series_prediction_using_lstm_rnn.htm | CC-MAIN-2021-25 | refinedweb | 868 | 73.34 |
empty Wrote:hehe thats why I wrote "the option in the settings are enabled" sry if my english skills aren't so good
For example this great song , with your browser you are able to view this file in HD. But with the youtube 3.4 script it isnt' possible
Haggy Wrote:I have to re-mention the terrible audio sync issues. Running a recent svn version (but it did happen on atlantis too) on linux every video is way out of sync, audio is at least one second to early. is there anything i can do about this?
borick Wrote:HD isn't supported currently (it lags out my xbox anyway) only high quality and regular quality. on youtube there is reg quality, high quality, and also HD. HD isn't currently supported (high quality does not refer to HD)
empty Wrote:Ah ok, but would be great if you can implement an HD Option, I'm using XBMC on a Windows 2,5Ghz dualcore machine, which has enough power :o :o
def _check_video_url( self, url, quality ): # only need the parameter for non standard quality if ( quality ): try: # TODO: check for fmt=22 for 720p and verify all videos now support fmt=18 arg # create the new url with the fmt parameter check_url = url + "&fmt=%d" % ( quality, ) # we need to request the url with quality request = urllib2.Request( check_url ) # create an opener object and validate the url opener = urllib2.urlopen( request ) # close opener opener.close() # success, return the new url return check_url except urllib2.URLError, e: # invalid quality pass # none or invalid quality, return the original url return url
TheCrook Wrote:I am having the same problem, I am running the latest build of XBMC and the latest youtube script but it still fails to play videos. | http://forum.xbmc.org/printthread.php?tid=33585&page=14 | CC-MAIN-2013-20 | refinedweb | 298 | 56.29 |
Minimize Cost for Reducing Array by Replacing Two Elements with Sum at most K times for any Index
Understanding
This blog discusses a coding problem based on n-ary trees and prefix sums. The blog will present a challenge that involves tricky observations and constructions. The problem will challenge you to reimagine the problem differently to get to the solution. Such problems are increasingly asked in programming contests where you need to transform a question to relate it with a different concept where you can construct things that resemble entities in the original problem.
Problem Statement
Ninja has given you an array, ‘ARR’ and an integer ‘K’. Your task is to determine the minimum possible cost to collect the sum of the array. You can collect the sum of the array elements by using the given operation as many times as possible till the restriction proposed is true:
- Pick two indices, ‘INDEX1’ and ‘INDEX2’, and add ‘ARR[INDEX2]’ to ‘ARR[INDEX1]’.
- Cost of collection += ARR[INDEX2].
- Make ARR[INDEX2] = 0.
Restriction: The addition of elements at the same index is allowed at most K times. It means for any valid index, ‘INDEX’, you can add elements of other indices to this index at most ‘K’ times.
Input
ARR: {4, 8, 6, 2, 3}
K = 2
Output
20
Explanation
You can do the following operations:
- Add ‘ARR[3]’ to ‘ARR[0]’. ARR = {6, 8, 6, 0, 3}
- Add ‘ARR[4]’ to ‘ARR[2]’. ARR = {6, 8, 9, 0, 0}
- Add ‘ARR[0]’ to ‘ARR[1]’. ARR = {0, 14, 9, 0, 3}
- Add ‘ARR[2]’ to ‘ARR[1]’. ARR = {0, 23, 0, 0, 0}
We have added elements of other indices to index 1 two times, which is within limits.
Approach
To solve this problem, we need to transform this problem into a graphical one. Let's first sort the array in non-increasing order. Now, let's assume each array element represents a node in a k-ary tree. A k-ary tree is a tree where each node has at most ‘K’ children.
We can visualise the operation of adding an array element, ‘ELEM1’ to another element ‘ELEM2’ as appending the subtree of ‘ELEM1’ as a child to ‘ELEM2’. We can append the subtree of ‘ELEM1’ to ‘ELEM2’ only if ‘ELEM2’ has fewer than ‘K’ children.
Now, as we have identified an operation in trees that resemble the addition operation described in the problem, let's move on to the definition of cost in the new context.
The cost of collecting the sum of an array can be calculated by summing up the multiplication of each node with its depth in the tree, assuming the root is at depth 0.
To understand this, let's take the example mentioned before.
Let's create the tree corresponding to the operations. Each previously mentioned operation translates to an edge as shown in the images below.
The initial configuration
Operation 1
Operation 2
Operation 3
Operation 4
Cost = 8 * 0 + 4 * 1 + 6 * 1 + 2 * 2 + 3 * 2 = 20
Now, the question is how to minimize the cost?
Taking intuition from the tree structure, we can do the following:
- Nodes with higher values should have lower depth.
- Each non-leaf node should have K children to accumulate as many nodes as possible in the lower depths.
Remember, we need not create the tree. We just did this analysis to understand the problem better.
Algorithm
- Take the input array and integer K.
- Sort the array in non-increasing order.
- Calculate the prefix sum in the ‘PREF_SUM’ array.
- Initialise the following variables:
- COST: To store the cost of collection.
- START_INDEX: It will depict the index of the leftmost node at each level.
- DEPTH: To store the current depth as the algorithm runs.
- DEPTH_SIZE: To hold the number of nodes at each depth.
- While the ‘START_INDEX’ is less than ‘N’, do the following:
- Calculate END_INDEX = START_INDEX + DEPTH_SIZE.
- Take the minimum of ‘END_INDEX’ and ‘N - 1’ and store it in ‘END_INDEX’
- Calculate the sum of elements in the range described by ‘START_INDEX’ and ‘END_INDEX’ using ‘PREF_SUM’ array.
- Increment ‘COST’ by the sum calculated in previous step multiplied by the current depth.
- Increment ‘DEPTH’ by one.
- DEPTH_SIZE *= K to take into account the second point on minimising the cost.
- Output the COST.
Program
#include<iostream> #include<algorithm> using namespace std; int findCost(int arr[]) { // Size of the array. int N = sizeof(arr)/sizeof(arr[0]); // Integer K as described in the problem statement. int K = 2; // Sort the array in the non-increasing order. sort(arr, arr + N, greater<int>()); // Prefix sum calculation. int prefSum[N+1]; prefSum[0] = 0; // Standard technique to compute prefix sum in O(N) time. for(int i = 0; i < N; i++) { prefSum[i + 1] = prefSum[i] + arr[i]; } // Cost of sum collection. int cost = 0; // Elements to pick from. 0th index is ignored as it will always be multiplied by zero, thus contribution to the cost. int startIndex = 1; // Current depth. int depth = 1; // Number of nodes at the current depth. int depthSize = K; while(startIndex < N) { // Array elements covered at this depth. int endIndex = startIndex + depthSize - 1; // In case of overflow. endIndex = min(endIndex, N - 1); // Sum of elements at the current depth. int levelSum = prefSum[endIndex + 1] - prefSum[startIndex]; // As described by the approach. cost += levelSum * depth; // Update the startIndex after covering all the elements till endIndex. startIndex = endIndex + 1; // The number of nodes at the next level will be K times the number of nodes at this level. // This is to accumulate as many nodes as possible in the lower depths. // Level is used interchangeably with depth. depthSize *= K; // Increase the depth. depth++; } } int main() { // Read the size. int N; cout << "Enter the size of the array: "; cin >> N; // Input array. int arr[N]; cout << "Enter the elements: "; for(int i = 0; i < N; i++){ cin >> arr[i]; } // Output the answer. cout << findCost(arr) << endl; }
Input
Enter the size of the array: 5 Enter the elements: 4 8 6 2 3
Output
20
Time Complexity
The time complexity of the above approach is O(N * logN), where N is the size of the input array.
It is because we are sorting the array in non-increasing order which takes O(N * log N). The time complexity of the while loop is O(logKN) where K is the input parameter, however, the sorting algorithm is the upper bound to the time complexity.
Space Complexity
The space complexity of the above approach is O(N) to store the prefix sum array.
Key Takeaways
This blog discussed a very interesting problem based on prefix sums and k-ary trees. It was intriguing to analyse the problem graphically. We created operations in the graphical domain that resemble operations described in the problem. The most important part and the motive of the construction was to understand how to minimise the cost of collecting the sum.
Hence learning never stops, and there is a lot more to learn.
So head over to our practice platform CodeStudio to practice top problems, attempt mock tests, read interview experiences, and much more. Till then, Happy Coding! | https://www.codingninjas.com/codestudio/library/minimize-cost-for-reducing-array-by-replacing-two-elements-with-sum-at-most-k-times-for-any-index | CC-MAIN-2022-27 | refinedweb | 1,188 | 65.22 |
Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
All of the XML processors that we have seen up to now are based
on the Perl module
XML::Parser, which
is, in turn, based on James Clark’s expat XML parser. However, expat doesn’t have support for newer XML
features such as namespaces, so another parser has emerged as the first
choice for many XML processing tasks. It is called libxml2, and you can find more details about
it at.
Perl has a module,
XML::LibXML,
that gives access to the libxml2
API, and Mark Fowler has written
Template::Plugin::XML::LibXML, which allows
the API to be used from the Template Toolkit. Both of these modules can
be downloaded from CPAN at and,
respectively. | http://my.safaribooksonline.com/book/programming/perl/0596004761/xml/perltt-chp-10-sect-6 | CC-MAIN-2013-48 | refinedweb | 134 | 67.08 |
a odd thing of "from __future__ import ..."
Discussion in 'Python' started by mithrond
'from __future__ import ...' overviewLogan, Nov 25, 2003, in forum: Python
- Replies:
- 3
- Views:
- 897
- Michael Hudson
- Nov 25, 2003
from __future__ import decoratorsJacek Generowicz, Jan 13, 2005, in forum: Python
- Replies:
- 8
- Views:
- 464
- Jacek Generowicz
- Jan 17, 2005
from __future__ import absolute_import ?Ron Adam, Feb 2, 2007, in forum: Python
- Replies:
- 7
- Views:
- 601
- Ron Adam
- Feb 9, 2007
from __future__ import print, Apr 10, 2008, in forum: Python
- Replies:
- 8
- Views:
- 889
- Roy Smith
- Apr 20, 2008
Recommended "from __future__ import" options for Python 2.5.2?Malcolm Greene, Apr 12, 2008, in forum: Python
- Replies:
- 1
- Views:
- 477
- Dan Bishop
- Apr 12, 2008 | http://www.thecodingforums.com/threads/a-odd-thing-of-from-__future__-import.395240/ | CC-MAIN-2015-48 | refinedweb | 119 | 64.85 |
A Beginner's Guide to D/Conditions and Loops/Switch Statement< A Beginner's Guide to D | Conditions and Loops
BasicsEdit
The switch statement can be found in almost every programming language, it's commonly used for checking multiple conditions. Syntax is identical as it is in C++ or Java. It has following form:
switch(variable) { case value_to_check: statements; break; default: statements; }
Here's some simple example:
import std.stdio, std.string : strip; void main() { // Command that user want to launch string input; write("Enter some command: "); // Get input without whitespaces, such as newline input = strip(readln()); // We are checking input variable switch( input ) { // If input is equals to '/hello' case "/hello": writeln("Hello!"); break; // If it is equals to '/bye' case "/bye": writeln("Bye!"); break; // None of specified, unknown command default: writeln("I don't know that command"); } }
And the result of our code:
Enter some command: /hello Hello!
Note break keyword after each case! If it's bypassed each case after it will be called. So here's console output of code without breaks:
Enter some command: /hello Hello! Bye! I don't know that command
As you may see, all cases after
/hello were "called", this is useful if we want to call same statements in more that one case. Here's one more example:
string cmd = "/hi"; switch( cmd ) { case "/hi": case "/hello": case "/wassup": writeln("Hi!"); break; // ... } | https://en.m.wikibooks.org/wiki/A_Beginner%27s_Guide_to_D/Conditions_and_Loops/Switch_Statement | CC-MAIN-2016-40 | refinedweb | 232 | 60.35 |
Apply a glitch effect with the Vue Glitch component
vue-glitch
Styling preferences can be very different and with Vue it can be really easy to give a unique look to your elements. Vue Glitch comes in to serve as a component for Vue.js which can be used to apply a glitch effect in any kind of text.
You can see it live here.
Example
To start working with vue-glitch use the following command to install it.
$ yarn add vue-glitch
Import in your project
import Glitch from 'vue-glitch' Vue.component('glitch', Glitch)
Component Usage:
<glitch text="Glitched"></glitch> <glitch text="Text appeared to be stuck" color="DeepPink" > </glitch> <glitch text="Text that looks spooky with custom background" color="Orange" background="steelblue" > </glitch>
To apply custom styles you can use
.glitch and
.glitch-wrapper classes.
.glitch { margin-bottom: 20px; padding: 20px; } .glitch-wrapper { font-size: 40px; font-family: sans-serif; }
If you would like to explore more about Vue Glitch, head to the project's repository on GitHub, where you will also find the source code. Created & submitted by @ianaya89. | https://vuejsfeed.com/blog/apply-a-glitch-effect-with-the-vue-glitch-component | CC-MAIN-2019-35 | refinedweb | 183 | 71.95 |
import *
Widgets have their own display
repr which allows them to be displayed using IPython's display framework. Constructing and returning an
IntSlider automatically displays the widget (as seen below). Widgets are displayed inside the
widget area, which sits between the code cell and output. You can hide all of the widgets in the
widget area by clicking the grey x in the margin.
IntSlider()
You can also explicitly display the widget using
display(...).
from IPython.display import display w = IntSlider() display(w)
If you display the same widget twice, the displayed instances in the front-end will remain in sync with each other.
display(w)
Widgets are represented in the back-end by a single object. Each time a widget is displayed, a new representation of that same object is created in the front-end. These representations are called views.
You can close a widget by calling its
close() method.
display(w)
w.close()
All of the IPython widgets share a similar naming scheme. To read the value of a widget, you can query its
value property.
w = IntSlider() display(w)
w.value
Similarly, to set a widget's value, you can set its
value property.
w.value = 100
In addition to
value, most widgets share
keys,
description,
disabled, and
visible. To see the entire list of synchronized, stateful properties, of any specific widget, you can query the
keys property.
w.keys
While creating a widget, you can set some or all of the initial values of that widget by defining them as keyword arguments in the widget's constructor (as seen below).
Text(value='Hello World!', disabled=True)
If you need to display the same value two different ways, you'll have to use two different widgets. Instead of attempting to manually synchronize the values of the two widgets, you can use the
traitlet
link function to link two properties together. Below, the values of three widgets are linked together.
from() | https://nbviewer.jupyter.org/format/slides/github/ipython/ipython/blob/rel-4.0.2/examples/Interactive%20Widgets/Widget%20Basics.ipynb | CC-MAIN-2019-43 | refinedweb | 323 | 64.51 |
Pylons supports a variety of template languages in addition to Mako through the use of template engine
plug-ins. This can be useful both for migrating web applications to Pylons, or in cases where you just
would rather prefer some other templating solution.
Template language plug-ins can be installed rather easily using setuptools. A current list of template
engine plug-ins is at the Buffet website.
Once you have installed one of these, using the new template language within Pylons is quite easy. As
Pylons does not come pre-configured with this in mind, you will need to do a little more work yourself
depending on which template language you're using.
If you didn't select the kid optional extra package when you installed Pylons (described on the
install page) you will need to install the appropriate Buffet plugin. In the case
of Kid, this is called TurboKid and can be installed as follows:
1
$ easy_install TurboKid
To use Kid with Pylons, first we must setup a new template directory for the Kid templates.
First, create a directory in yourproject called kidtemplates and add a controller:
1
2
3
$ cd yourproject
$ mkdir yourproject/kidtemplates
$ paster controller kid
You will now have a kid.py controller in your controllers directory. First, we will need to add Kid to the available template engines.
Edit yourproject/config/environment.py add to the bottom of the load_environment function:
1
2
kidopts = {'kid.assume_encoding':'utf-8', 'kid.encoding':'utf-8'}
config.add_template_engine('kid', 'yourproject.kidtemplates', kidopts)
Edit the KidController class so it looks like this:
1
2
3
4
5
class KidController(BaseController):
def index(self):
c.title = "Your Page"
c.message = 'hi'
return render_response('kid', 'test')
Make sure to change yourproject.kidtemplates to reflect what your project is actually called. The
first argument to render or render_response can be the template engine to use, while the second non-keyword argument is the template. If you don't specify a template engine, it will drop back to the default (Mako, unless you change the default).
Now let's add the Kid template to render, create the file yourproject/kidtemplates/test.kid with
the following content:
1
2
3
4
5
6
7
8
9
<html xmlns="" xmlns:
<head>
<title py:title</title>
</head>
<body>
<p py:message</p>
<p>You made it to the following url: ${h.url_for()}</p>
</body>
</html>
Since the template plug-ins currently expect paths to act as module imports, you will also need to create
a __init__.py file inside yourproject/kidtemplates.
Loading /kid will now return the Kid template that you have created.
Notice that all the same Pylons variables are made accessible to template engine plug-ins. You will have c, h, g,
session, and request available in any template language you choose to use. This also makes it easier to switch
later to Mako or a different template language without having to update your controller action.
In Pylons, customization is not just allowed but actively encouraged. It's quite easy to change the default engine from Mako to your choice. Let's make Kid the default template engine.
Edit yourproject/config/environment.py and change the template_engine argument passed to config.init_app:
config.init_app(global_conf, app_conf, package='yourproject',
template_engine='kid', paths=paths)
This swaps Mako out and uses Kid, making Kid the new default template engine. The above index method no longer needs to specify 'kid' now when rendering a template. The existing templates directory will be used, and you'll need to create the __init__.py file before adding Kid templates. Current template engine's that can be swapped in this manner are kid, mako, and genshi.
Note
For more details on the config object, check out the extensive Config docs from the Pylons Module API.
Using genshi allongside mako (in 0.9.6rc1)
==========================================
First you need to install Genshi, the usual way applies 'easy_install Genshi'.
Then you need to configure the genshi engine in your project, open yourproject/config/environment.py and add
>>>
config.add_template_engine('genshi', 'yourproject.templates', {})
<<<
at the end of the file.
Also, don't forget to create an empy _init.py in yourproject/templates/ so that genshi is certain it's a python package directory (this is required by Genshi 0.4.3 at least). A simple 'touch yourproject/templates/init_.py' is enough.
Then, if you have a yourproject/templates/serverinfo.html template, you can render it by
calling render('genshi', 'serverinfo')
This is equivalent to return render('mako', '/serverinfo.mak') or just return render('/serverinfo.mak') since mako is still default (we didn't change that).
Using genshi as the default templating engine in Pylons 0.9.6.1
Install genshi with Pylons by easy_install:
easy_install Pylons[genshi]
Now edit the init_app line in config/environment.py like so:
config.init_app(global_conf, app_conf, package='mypackage',
template_engine='genshi', paths=paths)
As above, you need to create a blank _init_.py in any directories that contain genshi templates.
One last note is with regards to naming. genshi templates are .html files, and they're rendered as if they were python packages. So, if in your templates directory, you have a subdirectory called account, and you want a template called signup.html, your directory structure would be as follows:
template/
template/_init_.py
template/account
template/account/_init_.py
template/account/signup.html
In your code, you would render this file like this:
render('account.signup') | http://wiki.pylonshq.com/display/pylonsdocs/Using+Other+Template+Languages | crawl-001 | refinedweb | 905 | 58.38 |
Foreign.Storable.Traversable
Description
If you have a
Traversable instance of a record,
you can load and store all elements,
that are accessible by
Traversable methods.
We treat the record like an array,
that is we assume, that all elements have the same size and alignment.
Example:
import Foreign.Storable.Traversable as Store data Stereo a = Stereo {left, right :: a} instance Functor Stereo where fmap = Trav.fmapDefault instance Foldable Stereo where foldMap = Trav.foldMapDefault instance Traversable Stereo where sequenceA ~(Stereo l r) = liftA2 Stereo l r instance (Storable a) => Storable (Stereo a) where sizeOf = Store.sizeOf alignment = Store.alignment peek = Store.peek (error "instance Traversable Stereo is lazy, so we do not provide a real value here") poke = Store.poke
You would certainly not define
Traversable.
For instance when reading a list, it is not clear,
how many elements shall be read.
Using the skeleton you can give this information
and you also provide information that is not contained in the element type
a.
For example you can call
peek (replicate 10 ()) ptr
for reading 10 elements from memory starting at
ptr.
peekApplicative :: (Applicative f, Traversable f, Storable a) => Ptr (f a) -> IO (f a)Source | http://hackage.haskell.org/package/storable-record-0.0.2.4/docs/Foreign-Storable-Traversable.html | CC-MAIN-2015-06 | refinedweb | 196 | 66.54 |
Trying to create just a basic Servlet is extremly frustrating in IDEA 12 (same as 11?)
Steps....
0. No IDEA 12 step by step documentation found, so....
1. I create a web project.
1.5. Added Tomcat App Server.
2. I create a package under src
3. I create a Servlet
Then notice that idea leaves a "{Package Name}" element in the servlet (that of course won't compile) even though there is a package statement. IDEA doesn't put a semi-colon after the package name at top. OK, fixed those.
4. Clicked in the web.xml and tried to enter the deployment descriptor elements. There's a "+" enabled, but clicking it ... NOTHING HAPPENS. Same for Servlet Mapping. Clicked and highligted everything I could possibly think of in web.xml and other parts of the "Web" view. Here again, the IDE is utterly confusing. There is an ENABLED "+" button for adding the Servlet mapping, but clicking it....NOTHING HAPPENS. Again.
---------
I also noticed that after entering some text in the servlet description, I was not able to edit it! Not sure what this feature is all about...
--------
Even after manually adding the servlet path information, I can't just "run" the web application and have the Servlet work. Sure, the HTML page (index.jsp) works OK, but the Servlet doesn't even look like it's deployed (possibly related to all the other problems above?) No idea.
Looking at the directories IDEA creates under the project (test, web, etc.), there's not a single directory with everything in it needed to work.
Why is this so difficult and so much apparent burdent put on the developer to "know" just exactly how "IDEA works"?
For what is relatively simple in other IDEs, it often seems more difficult to use IDEA than using advanced features of Java. I would prefer on banging my head on my app logic, not on the IDE. Yet, that's what I seem to often do with IDEA.
Am I honestly alone on this?
Sigh....
Trying to create just a basic Servlet is extremly frustrating in IDEA 12 (same as 11?)
It works for me. Could you submit a bug report for further investigation?
{Package Name} error is unrelated and is caused by your custom file template.
Here again, I'm confused.
Thanks for your reply, but could you be more specific?
I've never created a "Custom File Template".
Looking in the File Templates, they're all the defaults to the best of my knowledge.
Also, I didn't see a Template for a Servlet.
Can you suggest where this setting might be?
Thanks much in advance.
- m
You have this template customized:
My Template (for Web:Java code templates:Servlet Class.java) is below.
I've never customized this so I don't see how it's different from the default (or why it's putting in artifacts or not creating a semicolon after the package name.
Thanks,
-m
---------------------------
#parse("File Header.java")
#if (${PACKAGE_NAME} != "")
package ${PACKAGE_NAME};
#end
public class ${Class_Name} extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException, java.io();
}
-m | https://intellij-support.jetbrains.com/hc/en-us/community/posts/206220389-Can-t-create-basic-Servlet-in-12?page=1 | CC-MAIN-2021-25 | refinedweb | 532 | 77.94 |
Hey I want to be able to put a movie title in the is more than one world and it goes crazy when i do, if you run my program and enter one word when it asks for the movie title it will work fine. but when u enter a more than one word (using space) it goes crazy and ends the program. what do i need to do.
#include "stdafx.h" #include <iostream> #include <ctype.h> using namespace std; int main() { char movie[50]; int adult_ticket_price, child_ticket_price; int adult_ticket_sold, child_ticket_sold; int percentage_of_gross_amount_donated; cout <<"Enter The Movie Name: "; cin >> movie; cout << ""; cout <<"Enter The Adult Ticket Price: $"; cin >> adult_ticket_price; cout << ""; cout <<"Enter The child ticket price: $"; cin >> child_ticket_price; cout << ""; cout <<"Enter The Number of Adult Tickets Sold: "; cin >> adult_ticket_sold; cout << ""; cout <<"Enter The Number of Child Tickets Sold: "; cin >> child_ticket_sold; cout << ""; cout <<"Enter The Percentage of Gross Amount Donated: "; cin >> percentage_of_gross_amount_donated; cout << ""; cout <<"Number of Tickets Sold: " << ((adult_ticket_sold)+(child_ticket_sold))<< endl; cout <<"Gross Amout is: $" << (((adult_ticket_sold)*(adult_ticket_price))+((child_ticket_sold)*(child_ticket_price))) << endl; cout <<"Amount Donated is: $" << ((((adult_ticket_sold)*(adult_ticket_price))+((child_ticket_sold)*(child_ticket_price)))*((percentage_of_gross_amount_donated)*(.01))); cout <<" "<<endl; return 0; } | https://www.daniweb.com/programming/software-development/threads/73596/program-help-please | CC-MAIN-2017-17 | refinedweb | 183 | 51.01 |
I'm trying to write a loop program prompts the user to enter a number. The number has to be between 10 and 20 (both inclusive). If the number input is not between that range, it will display an error message and prompts the user to re-enter a new number again until the user get it right.
When I enter any number between 10 and 20 it works, but when I input in a number out of the range nothing happens. Anyone know what is wrong with my code??
Code :
import javax.swing.JOptionPane; public class input { public static void main(String[] args){ int number; String input = JOptionPane.showInputDialog(null,"Enter enter a number",JOptionPane.INFORMATION_MESSAGE); number = Integer.parseInt(input); while ((number>=10)&&(number<=20)) if ((number>=10)&&(number<=20)) { JOptionPane.showMessageDialog(null,"End of program!"); break; } else {JOptionPane.showMessageDialog(null,"Pls enter a number between 10 and 20","Error",JOptionPane.ERROR_MESSAGE); break;} } } | http://www.javaprogrammingforums.com/%20java-theory-questions/33427-loop-error-printingthethread.html | CC-MAIN-2018-13 | refinedweb | 154 | 53.07 |
Source
features/pep-382-2 / Doc / reference / simple_stmts.rst
Simple statements
Simple statements are comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. The syntax for simple statements is:
Expression statements:
An expression statement evaluates the expression list (which may be a single expression).
In interactive mode, if the value is not None, it is converted to a string using the built-in :func:`repr` function and the resulting string is written to standard output on a line by itself (except if the result is None, so that procedure calls do not cause any output.)
Assignment statements
Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:
(See section :ref: :ref:`types`).
Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, a sequence with at least as many items as there are targets in the target list, minus one. The first items of the sequence are assigned, from left to right, to the targets before the starred target. The final items of the sequence are assigned to the targets after the starred target. A list of the remaining items in the sequence is then assigned to the starred target (the list can be empty).
- Else: The object must be a sequence :keyword:`global` or :keyword:`nonlocal` statement in the current code block: the name is bound to the object in the current local namespace.
- Otherwise: the name is bound to the object in the global namespace or the outer namespace determined by :keyword:, :exc:`TypeError` is raised. That object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily :exc: :func:, :meth:`_.
WARNING::
(See section :ref: :ref:`caveat about class and instance attributes <attr-target-note>` applies as for regular assignments.
The :keyword:`assert` statement
Assert :const:`__debug__` and :exc:`AssertionError` refer to the built-in variables with those names. In the current implementation, the built-in variable :const:`_ :const:`__debug__` are illegal. The value for the built-in variable is determined when the interpreter starts.
The :keyword:`pass` statement
:keyword:)
The :keyword:`del` statement :keyword:`global` statement in the same code block. If the name is unbound, a :exc:`NameError` exception will be raised.
Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).
The :keyword:`return` statement
:keyword:`return` may only occur syntactically nested in a function definition, not within a nested class definition.
If an expression list is present, it is evaluated, else None is substituted.
:keyword:`return` leaves the current function call with the expression list (or None) as return value.
When :keyword:`return` passes control out of a :keyword:`try` statement with a :keyword:`finally` clause, that :keyword:`finally` clause is executed before really leaving the function.
In a generator function, the :keyword:`return` statement is not allowed to include an :token:`expression_list`. In that context, a bare :keyword:`return` indicates that the generator is done and will cause :exc:`StopIteration` to be raised.
The :keyword:`yield` statement
The :keyword:`yield` statement is only used when defining a generator function, and is only used in the body of the generator function. Using a :keyword: :func:`next` function on the generator repeatedly until it raises an exception.
When a :keyword:`yield` statement is executed, the state of the generator is frozen and the value of :token:`expression_list` is returned to :meth:`next`'s caller. By "frozen" we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack: enough information is saved so that the next time :func:`next` is invoked, the function can proceed exactly as if the :keyword:`yield` statement were just another external call.
The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a :keyword:`try` ... :keyword:`finally` construct. If the generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), the generator-iterator's :meth:`close` method will be called, allowing any pending :keyword:`finally` clauses to execute.
The :keyword:`raise` statement
If no expressions are present, :keyword:`raise` re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a :exc:`TypeError` exception is raised indicating that this is an error (if running under IDLE, a :exc:`queue.Empty` exception is raised instead).
Otherwise, :keyword:`raise` evaluates the first expression as the exception object. It must be either a subclass or an instance of :class:`BaseException`. If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.
The :dfn:`type` of the exception is the exception instance's class, the :dfn:`value` is the instance itself.
A traceback object is normally created automatically when an exception is raised and attached to it as the :attr:`__traceback__` attribute, which is writable. You can create an exception and set your own traceback in one step using the :meth: :attr:`_ :attr:`_ :ref:`exceptions`, and information about handling exceptions is in section :ref:`try`.
The :keyword:`break` statement
:keyword:`break` may only occur syntactically nested in a :keyword:`for` or :keyword:`while` loop, but not nested in a function or class definition within that loop.
It terminates the nearest enclosing loop, skipping the optional :keyword:`else` clause if the loop has one.
If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control target keeps its current value.
When :keyword:`break` passes control out of a :keyword:`try` statement with a :keyword:`finally` clause, that :keyword:`finally` clause is executed before really leaving the loop.
The :keyword:`continue` statement
:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or :keyword:`while` loop, but not nested in a function or class definition or :keyword:`finally` clause within that loop. It continues with the next cycle of the nearest enclosing loop.
When :keyword:`continue` passes control out of a :keyword:`try` statement with a :keyword:`finally` clause, that :keyword:`finally` clause is executed before really starting the next loop cycle.
The :keyword:`import` statement
Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the :keyword:`import` statement occurs). The statement comes in two forms differing on whether it uses the :keyword:`from` keyword. The first form (without :keyword:`from`) repeats these steps for each identifier in the list. The form with :keyword:`from` performs step (1) once, and then performs step (2) repeatedly. For a reference implementation of step (1), see the :mod: :data:`sys.modules`, the cache of all modules that have been imported previously. If the module is found there then it is used in step (2) of import unless None is found in :data:`sys.modules`, in which case :exc:`ImportError` is raised.
If the module is not found in the cache, then :data:`sys.meta_path` is searched (the specification for :data:`sys.meta_path` can be found in PEP 302). The object is a list of :term:`finder` objects which are queried in order as to whether they know how to load the module by calling their :meth:`find_module` method with the name of the module. If the module happens to be contained within a package (as denoted by the existence of a dot in the name), then a second argument to :meth:`find_module` is given as the value of the :attr:`__path__` attribute from the parent package (everything up to the last dot in the name of the module being imported). If a finder can find the module it returns a :term:`loader` (discussed later) or returns None.
If none of the finders on :data:`sys.meta_path` are able to find the module then some implicitly defined finders are queried. Implementations of Python vary in what implicit meta path finders are defined. The one they all do define, though, is one that handles :data:`sys.path_hooks`, :data:`sys.path_importer_cache`, and :data:`sys.path`.
The implicit finder searches for the requested module in the "paths" specified in one of two places ("paths" do not have to be file system paths). If the module being imported is supposed to be contained within a package then the second argument passed to :meth:`find_module`, :attr:`__path__` on the parent package, is used as the source of paths. If the module is not contained in a package then :data:`sys.path` is used as the source of paths.
The finder looks for various files and directories to locate a module or package P. If a directory P with a file __init__.py is found, it is considered as a package, and later __init__.py is loaded. If directories P.pyp are found in the path, they are remembered and form part of the new package's __path__. If no P/__init__.py is found, but P.pyp directories, an empty package will be created with the directories as __path__. If neither directory is found, the extensions as reported from :func:`imp.get_suffixes` are considered. Those extensions will at least include Python source code files (.py) and Python byte code files (either .pyc or .pyo), and typically also extensions related to dynamically loadable machine code (e.g. .so or .pyd).
Once the source of paths is chosen it is iterated over to find a finder that can handle that path. The dict at :data:`sys.path_importer_cache` caches finders for paths and is checked for a finder. If the path does not have a finder cached then :data:`sys.path_hooks` is searched by calling each object in the list with a single argument of the path, returning a finder or raises :exc:`ImportError`. If a finder is returned then it is cached in :data:`sys.path_importer_cache` and then used for that path entry. If no finder can be found but the path exists then a value of None is stored in :data: :exc:`ImportError` is raised. Otherwise some finder returned a loader whose :meth:`load_module` method is called with the name of the module to load (see PEP 302 for the original definition of loaders). A loader has several responsibilities to perform on a module it loads. First, if the module already exists in :data:`sys.modules` (a possibility if the loader is called outside of the import machinery) then it is to use that module for initialization and not a new module. But if the module does not exist in :data:`sys.modules` then it is to be added to that dict before initialization begins. If an error occurs during loading of the module and it was added to :data:`sys.modules` it is to be removed from the dict. If an error occurs but the module was already in :data:`sys.modules` it is left in the dict.
The loader must set several attributes on the module. :data:`__name__` is to be set to the name of the module. :data:`__file__` is to be the "path" to the file unless the module is built-in (and thus listed in :data:`sys.builtin_module_names`) in which case the attribute is not set. If what is being imported is a package then :data:`__path__` is to be set to a list of paths to be searched when looking for modules and packages contained within the package being imported. :data:`__package__` is optional but should be set to the name of package that contains the module or package (the empty string is used for module not contained in a package). :data:`__loader__` is also optional but should be set to the loader object that is loading the module.
If an error occurs during loading then the loader raises :exc:`ImportError` if some other exception is not already being propagated. Otherwise the loader returns the module that was loaded and initialized.
When step (1) finishes without raising an exception, step (2) can begin.
The first form of :keyword:`import` statement binds the module name in the local namespace to the module object, and then goes on to import the next identifier, if any. If the module name is followed by :keyword:`as`, the name following :keyword:`as` is used as the local name for the module.
The :keyword:`from` form does not bind the module name: it goes through the list of identifiers, looks each one of them up in the module found in step (1), and binds the name in the local namespace to the object thus found. As with the first form of :keyword:`import`, an alternate local name can be supplied by specifying ":keyword:`as` localname". If a name is not found, :exc:`ImportError` is raised. If the list of identifiers is replaced by a star ('*'), all public names defined in the module are bound in the local namespace of the :keyword: :keyword:`from` form with * may only occur in a module scope. The wild card form of import --- import * --- is only allowed at the module level. Attempting to use it in class or function definitions will raise a :exc: :keyword:.
:func:`importlib.import_module` is provided to support applications that determine which modules need to be loaded dynamically.
Future statements
A :dfn: module docstring (if any),
- blank lines, and
- other future statements. :mod:`_ :func:`exec` and :func:`compile` that occur in a module :mod:`M` containing a future statement will, by default, use the new syntax or semantics associated with the future statement. This can be controlled by optional arguments to :func:`compile` --- see the documentation of that function for details.
A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session. If an interpreter is started with the :option:`-i` option, is passed a script name to execute, and the script includes a future statement, it will be in effect in the interactive session started after the script is executed.
The :keyword:`global` statement
The :keyword:`global` statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without :keyword:`global`, although free variables may refer to globals without being declared global.
Names listed in a :keyword:`global` statement must not be used in the same code block textually preceding that :keyword:`global` statement.
Names listed in a :keyword:`global` statement must not be defined as formal parameters or in a :keyword:`for` loop control target, :keyword:`class` definition, function definition, or :keyword:`import` statement.
Programmer's note: the :keyword:`global` is a directive to the parser. It applies only to code parsed at the same time as the :keyword:`global` statement. In particular, a :keyword:`global` statement contained in a string or code object supplied to the built-in :func:`exec` function does not affect the code block containing the function call, and code contained in such a string is unaffected by :keyword:`global` statements in the code containing the function call. The same applies to the :func:`eval` and :func:`compile` functions.
The :keyword:`nonlocal` statement
The :keyword: :keyword:`nonlocal` statement, unlike to those listed in a :keyword:`global` statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).
Names listed in a :keyword:`nonlocal` statement must not collide with pre-existing bindings in the local scope. | https://bitbucket.org/python_mirrors/features-pep-382-2/src/a2fe122de5c95cd1d2f06260e216b05e9e5cf75e/Doc/reference/simple_stmts.rst | CC-MAIN-2015-22 | refinedweb | 2,639 | 53.51 |
Be the first to know about new publications.Follow publisher Unfollow publisher Free Press Media
- Info
Spread the word.
Share this publication.
- Stack
Organize your favorites into stacks.
- Like
Like this publication.
Mankato Magazine
People, Places, Lifestyles of the Minnesota River Valley
PAYING CASH FOR USED PRO-LINE GOLF CLUBS! ANKATO M FEATURE S May 2013 Volume 8, Issue 5 magazine 18 Partners like no other The legacy of Lowell and Nadine Andreas 14 Partners at play Mankato gets together to make sure everyone has a good time 22 Putting together the Panic The makings of a semi-pro football team 28 Day Trip Destinations From Winona to Red Wing on the trail of the 100-Mile Garage Sale About the Cover Callie Syverson, a Minnesota State University student and lead actress in its April production of “Legally Blonde,” is pictured on the set of the play in the Ted Paul Theatre. Photo by The Free Press Media photographer Pat Christman. MANKATO MAGAZINE • May 2013 • 3 MANKATO DEPAR TMENTS magazine 6 From the Editor Partnerships weave the Mankato fabric 8 Odds ‘n’ Ends 10 Introductions Barbe Marshall Hansen of 10 12 12 The Gallery Renee Erdmann, Speechless Film Festival 30 That’s Life Birth (and graduation) of a salesman 32 Garden Chat Overcoming hoop house woes 34 Then and Now Beers over the years 36 Coming Attractions May events calendar 38 Your Health Ice or heat? 40 Your Tastes Salad days of the farmers market 42 Your Style Dress cool for warmer weather 44 Happy Hour Rum plays up, and ignores, its roots 52 Remember When The boys of summer, 32 22 Twin Rivers Council for the Arts and other recollections Coming in June We’re turning up the music. We’ll see what it sounds like to be backstage, as well as on the leading edge of Mankato’s music scene. We’ll enjoy some musically inspired literary diversions and chat with a few personalities you’re sure to recognize. Join us, and we’ll dance in the street until July. 42 4 • May 2013 • MANKATO MAGAZINE 52 MANKATO From The Editor magazine May 2013 • VOLUME 8, ISSUE 5 PUBLISHER James P. Santori EDITOR Joe Spear ASSOCIATE Tanner Kent EDITOR CONTRIBUTING Nell Musolf WRITERS Pete Steiner Jean Lundquist Marie Wood Sarah Zenk Blossom Wess McConville PHOTOGRAPHERS John Cross Pat Christman PAGE DESIGNER Christina Sankey ADVERTISING David Habrat MANAGER ADVERTISING Karla Marsh May 2013 • MANKATO MAGAZINE By Joe Spear Partnerships weave our fabric I f the Hatfields and McCoys had started out in Mankato, they might very well be best of neighbors by now. The storied West Virginia vs. Kentucky feud emanating from Civil War rivalries has come to be used generically as a description for any two groups that don’t get along. You’d be hard-pressed, possibly, to find two such groups in Mankato. Having seen every controversy possible in the last 25 years as a local newspaper editor, I can’t think of such a feud continuing for long. I’ll take nominations if you think you have one. But given the narratives in this month’s “Partnership” issue, the stories of cooperation and mutual admiration dominate the social and cultural environment. The partnerships are big by many measures. Some involved large amounts of money. Take the partnership the evolved between Lowell and Nadine Andreas and the Mankato community and Minnesota State University. Lowell, a founder with his brother Dwayne of Agribusiness giant ADM, appeared to have fondness for living in Mankato, where he and his brother got their start with Honeymead soybean processing. While Dwayne moved away to bigger cities were ADM was located, Lowell stayed and ended putting up $4 million for the cancer center at Immanuel St. Joseph’s Hospital, now known as Mayo Clinic Health System. He and his arts-loving wife Nadine donated another $1 million to build MSU’s black box theater. They left millions more for an arts and humanities program at MSU that funds all manner of high quality artists and performers. Longtime KTOE radio newsman Pete Steiner has particular perspective on the Andreas family as he grew up in the same west Mankato neighborhood they lived in at the beginning. It’s a great story and one longtime residents and newcomers will appreciate. The partnerships also reach in a lot of different directions. The Andreas family was not the only partner for MSU, its arts and theater. Consider that over the years, numerous local businesses have donated and sponsored productions at the MSU theater. From HickoryTech to Blethen Gage & Krause to Mayo Clinic all manner of businesses partner with those who would bring us the arts. But there are many smaller partnerships as well. Dozens, even hundreds, of ordinary family folks donate their time and energy to YMCA youth sports every year. It’s a real partnership between volunteers, parents, kids and the Y that promotes healthy living and healthy youth. Other partners also find a certain satisfaction in joining with local organizations that develop youth. Gene Lancaster helps coach youth baseball at the Y. “It’s hard not to smile when one of those kids make their first basket. The celebration and high fives they give each other are priceless. I guess that’s what keeps me coming back.” Barbe Marshall Hansen, executive director of the Twin Rivers Council for the Arts, landed in Mankato last fall to run one of the biggest partnerships and arts collaborations in the region. The Nebraska native helped rebuild support for various arts organizations in the Twin Cities — including the Penumbra Theatre — as well as performing herself. She sees value for a community in not only experiencing the arts, but helping create them. Partnerships help make that happen. “I love directing because you get to be a part of a team that creates something amazing and ephemeral” she says. “The experience of creating the play is as important as performing it. And if it is done well, everyone changes for the better as a result.” M Joe Spear is editor of Mankato Magazine. Contact him at 344-6382 or jspear@mankatofreepress.com. bright colors bright ideas! YEARS 1988-2013 Corporate Graphics Your Printing Solutions Company 1750 Northway Drive North Mankato, MN 56003 800-729-7575 Odds n’ Ends By Tanner Kent This Day in History May 1, 1925: On this day, The Free Press reported that “there was cussing and swearing and laughing and kidding at Mankato’s oil stations as autoists paid the 2-cent gas tax this morning.” After Oregon became the first state in the country to levy a gas tax in 1919, Photo courtesy of Nicollet County Historical Society Minnesota followed suit Minnesota enacted its 2-cent gas tax in 1925, not long before not long after with a tax Haugdahl’s Gas Station opened in St. Peter in 1930 (pictured). that amounted to about 10 percent of the pump price. The Free Press reported that several autoists laughed, or muttered oaths, that they had not filled up the day before. One farmer remarked to the reporter: “That darn legislature ought to have waited a year. We’ve paid for our licenses this year and now they’re soaking us again.” By 1959, every state had its own gas tax. May 9, 1955: The Free Press reported that four individuals escaped any serious injury after an emergency landing in a farm field 11 miles east of Le Center. The pilot of the single-engine Beechcraft was Harry Beske of Minnesota Lake. One of the passengers was Haakon Nordaas, owner of American Homes in Minnesota Lake. The other two passengers were unidentified. According to Nordaas, the four left the Mankato Airport and went first to St. James. On their way to Minneapolis, they were forced down at 10 a.m. when a faulty gas gauge showed an empty tank as full. Nordaas went on to praise the pilot for his skillful job in landing the plane in a field of oats. May 12, 1921: Mankato’s Automobile Club offered a $25 cash reward — the equivalent of more than $300 in today’s dollars — for information that would lead to the arrest of the individuals who “scattered tacks and broken glass throughout the streets of this city.” May 26, 1898: The baseball club for the State Normal School expressed outrage over a public challenge issued by the Mankato High School baseball team. In a letter to The Free Press editor, team captain W.R. Williams claimed the two teams had already agreed not to play a fourth game (Normal already held Photo courtesy of MSU photo archives the season series lead Pictured are five members of the the State Normal School of 2-1). Williams said in Mankato’s athletic club around 1900. the letter: “We deprecate their action in trying to put us in a false light before the public.” The challenge was, however, accepted by J.T. Biede, captain of the Normal School’s second team. Ask the Expert: Pamela Weller Finding a job after college It’s May and along with Memorial Day and Mother’s Day, this month marks the end of college for many people and the beginning of that often elusive thing — finding a job. Pamela Weller, director of the Career Development Center at Minnesota State University, has some advice for the brand-new college graduate. Weller recommends people start looking for a job before graduation. “There are many things a student can do even two years prior to graduation to stay on track,” Weller said. She suggested that students could mentor other students, join professional and community groups, and gain experience through internships. Networking is another strategy Weller stresses. “Tell everyone you know that you are looking for a job and what you are looking for,” Weller said. MSU offers students a wealth of career planning and job/internship search resources for students in all majors. Some of the tools offered include career interest assessments, one-on-one help with career path planning and finding employment. Career events, job fairs and a comprehensive online system for identifying employers and job opportunities are also available. After landing an interview, Weller said that it is smart to dress professionally and conservatively. “A suit is always appropriate for both men and women. If you don’t have a suit and can’t get one prior to the interview, wear the most professional outfit you can come up with,” W e l l e r recommended. “You can’t go wrong being overdressed but John Cross you can go Pamela Weller is the director of the Career wrong being Development Center at Minnesota State University. underdressed.” Weller also advises freshly minted graduates to hold on to the job they have until they find another. “It is always more appealing to hire someone who is employed versus someone who is unemployed. Put your heart and soul into your search for employment, be patient and know that rejection is part of the process for everyone. You’ve put four-plus years into pursuing your degree. Now give the same level of investment into your job search!” News to Use: Give babies a head start with motor skills By Nicholas Day Slate CHICAGO — The small humans of America are the most razzle-dazzled, overstimulated, bugged-out small humans in the world. — couldaggressive, hyper-anxious American parenting: If you really love your child — if you want to give her a head start in life — then twirl her around without mercy. MANKATO MAGAZINE • May 2013 • 9 Introductions Interview by Tanner Kent John Cross Barbe Marshall Hansen is the new director of the Twin Rivers Council for the Arts. She comes to Mankato with a long and diverse history in art and theatre. Bonding agent Meet Barbe Marshall Hansen, the recently hired executive director of the Twin Rivers Council for the Arts In business terms, Barbe Marshall Hansen’s title is executive director. In plainer terms, she’s a supporter, encourager, collaborator, organizer and catalyzer for greater visibility and support of artistic endeavors in the Mankato area. Since her official start date in October 2012, Marshall Hansen has been bringing her wealth of professional theatre experience and arts organization management to the Twin Rivers Council for the Arts, an organization whose mission she summarized as “connecting people to arts and culture.” 10 • May 2013 • MANKATO MAGAZINE Mankato Magazine: You’ve been involved in all kinds of arts and theatre over the course of your career. Can you give me a quick sketch of your background? Barbe Marshall Hansen: Grew up in Beatrice, Neb. (population 13,920). My grandfather was a farmer who was a huge opera fan, so his records were always a part of my childhood. I love opera. The other side of my family is Welsh, so we grew up singing a lot. Men who can play the piano are sexy. We can all play piano in my family. My mom loves music theater, so she would take us to many musicals a year -- from the local community theater, to tours that stopped in Lincoln and Omaha, and to Kansas City, Chicago, and Broadway. I still love really good music theater. Got a BFA in music theatre at the University of Nebraska-Lincoln (always will be a huge Husker fan). Lived in San Francisco for five years, directing, assistant directing, and teaching. Moved to Minneapolis in 1995 to get MFA in stage direction with Lou Bellamy. I have been freelancing as a stage director in the Twin Cities since 2000. I spent a lot of time on adjunct faculties teaching viewpoints movement, Meisner technique, business skills for actors, acting, and directing. I spent four years as the lead fundraiser during Penumbra’s successful turnaround that retired $600,000 in debt and built a $3.2 million cash reserve. Then, I did the same thing at History Theatre. I have always continued to direct, which is my medium and my voice. MM: What led you into theatre? When, and how did it become a passion of yours? BMH: I started taking dance lessons at age 4 and have always loved to sing and dance. I wasn’t able to get into many shows in high school, but loved the speech team, band, orchestra, and show choir. In college, I really began to get serious about theater, and got a BFA in Music Theatre performance with a dance minor. I acted for a while after college, including a tour of Japan as Eunice in “A Streetcar Named Desire.” Then I moved to San Francisco and started getting serious about directing, working with the Artistic Directing team at The American Conservatory Theatre while I taught theater and produced my own work at small venues. I love directing because you get to be a part of a team that creates something amazing and ephemeral. The experience of creating the play is as important as performing it. And if it is done well, everyone changes for the better as a result. MM: What’s your style as a director? Who were your influences, and can you share a piece or two that were particularly special for you? BMH: I love to do reinterpretations of classical works. “The Duchess of Malfi” and Charles L. Mee’s “Orestes” remain two of my favorite projects. I also love musicals -- “Jesus Christ Superstar” has been my favorite to date. I work with viewpoints movement Work, Meisner technique, and musicians to create collaborative adaptations with integrated soundscapes. MM: What led you to accept the position as executive director for Twin Rivers Council for the Arts? BMH: History Theatre was out of debt with a hefty cash reserve in the bank, so I was casually looking for the next challenge. I was also on the board of another group in St. Paul that is dedicated to building arts audiences, and discovered that I have a real passion for helping artists become more successful. So when I saw the listing (for the Twin Rivers positions), I thought it might be a good fit. I believe it is. The city is beautiful, the people are friendly and supportive, I’m surrounded by art, and I have a big, beautiful office with a huge window overlooking historic mansions. I love going to work every day. Working this job fuels me, and the days are flying by. I could use a 36-hour day. MM: Before coming to Twin Rivers, you also played a key role in orchestrating financial turnarounds for Penumbra Theatre and History Theatre. How useful is that experience in your role with Twin Rivers? BMH: There are a lot of similarities between digging a company out of debt and building a healthy company. Both are essentially reorganizations designed to build capacity. Fortunately, Twin Rivers has no debt, so they aren’t in need of a turnaround. However, Twin Rivers is at an exciting crossroads, and is poised for explosive growth. The board and staff have successfully founded a young arts organization, and now they are working to create a strategic plan to take the company to the next level, increase capacity and ensure sustainability. Strategic plans are critical, in my opinion, if you want to take an organization to a higher level of success. Both successful turnarounds that I was involved with in St. Paul began with a process of strategic planning. In this way, my work here will be similar. Although, walking into a company without debt is a lot more fun than starting by digging yourself out of a hole. I have had the pleasure of hiring a number of extremely talented young professionals, which is very different than the way I started my tenure at companies in need of downsizing to reduce debt. MM: What are your impressions so far of the arts community in the Mankato area? BMH: As an outsider, I was surprised to find such a visible, thriving arts community here. The CityArt Sculptures send a strong message that this community values art, but that is only the beginning. TRCA has 58 arts organizations who are affiliates, and there are many more arts organizations and independent artists in the region who are not yet affiliated with TRCA. There is more art to see and do than anyone could possibly do here. And there is such a wide variety of arts opportunities available that there really is something for everyone. I’m impressed with the arts community here in Mankato, and especially delighted to find such robust support from local governments and business leaders. Without this support, none of the arts would be possible. M MANKATO MAGAZINE • May 2013 • 11 The Gallery By Tanner Kent Leaving Mankato ‘Speechless’ Inaugural Bethany film festival features film screenings, local winner and music video premier T he inaugural Speechless Film Festival kicks off May 3-4 in the theater at the Mankato Place mall. Speechless is an international film festival for students and professionals inspired by the universal art of visual, but not silent, storytelling. The inaugural event received 86 entries from 24 countries. The festival springs from Bethany’s highly competitive media arts program, which boasts a long record of regional and national accolades, including a 2010 Emmy nomination for “Maverick Hockey Weekend.” In addition to screening submitted films, the event will also include the debut of the stop-motion music video that Bethany media arts students created for “Midnight on the Interstate” by Trampled By Turtles. The festival winners, which were announced before the event began, include: • Professional Long Form: “Indrivaren,” directed by Michael Rendell (English title: “When The Man Comes Around”). A 23-minute film produced in Sweden and Poland, “Indrivaran”. • Student Long Form: . • Professional Animation/Experimental/Other: “Sleight of Hand,” written and directed by Michael Cusack of Australia. In this 10-minute film stopmotion film about illusions, a man yearns to know his place in the world and how he fits in when, sometimes, it’s better not to know. • Student Animation/Experimental/Other: “18 Minutes,” by Savannah College of Art and Design student Christopher Mennuto. Mennuto wrote of his three-minute short film: “This animation is the story of my father’s survival on September 11th. Although I was only 10 when my father narrowly escaped the fall of the towers, my recollection of the events of that day still resonate in my mind.” • Professional Short Form: “Later than Usual,” written and directed by David Hovan of Canada. This 6-minute film shows a day in the life of an elderly couple. This couple has lived so long together that they have nothing left to say to each other. The non-verbal interactions 12 • May 2013 • MANKATO MAGAZINE between the two make for sometimes funny and at other times poignant moments throughout the film. • Student Short Form: “Enveloped,” directed by Bethany Lutheran College student Landon Brands and co-written by Grace Merchant.” Professional winners will receive $1,000 while student winners receive $500. Judges included: Lars Johnson, associate professor of English at Bethany Lutheran College; Don Larsson, professor of English at Minnesota State University; Jeff Boortz, assistant professor of graphic design at Georgia State University; and Tim Lind and Shelley Pierce, KMSU radio morning show hosts. To purchase event passes or find more information, visit. M Self-taught stitcher After two decades of quilting, Nicollet’s Renee Erdmann has become an expert R enee Erdmann has been quilting for at least 20 years but has been a crafter for as long as she can remember. “My mom and my grandma were crafters,” Erdmann said. “They did everything, but I always wanted to know how to quilt. So, one day I decided that I was going to teach myself how.” Since that day, Erdmann has made countless quilts ranging from baby blankets to king-sized bed covers. She estimates that baby quilts can be made in a few hours while the larger items take at least 45 hours to complete. To get her quilting done, Erdmann uses a Gammill quilting sewing machine. “I admire people who quilt by hand but I’m not one of them,” Erdmann said. “I think it would take the patience of Job to do that and I’m afraid I just don’t have that kind of patience.” Erdmann’s sewing machine has taken over the master bedroom of the Nicollet home she shares with her husband and children. “The master bedroom was the only room in the house that was big enough for the machine. It’s quite large,” Erdmann said. In addition to her own quilts, Erdmann also quilts for other people who give her their completed quilt tops that she then sews patterns into, connecting the quilt top to an all-cotton backing. The patterns she uses are freehand and usually depend on the kind of mood she is in while sewing. “I look at a block and decided what it needs,” Erdmann said. “I might put a flower pattern in it or something else. Some days are more creative than others.” Erdmann has fun with her quilting too and enjoys hiding the names of her children in the quilts she has made for them. “I like to secretly put their names in their quilts,” Erdmann said. “They have to look for it and are always excited when they find it.” Erdmann said her hobby is always on the forefront of her mind. “I’m always looking for patterns that I can use in my quilting. I look at a brick wall and see a pattern, or (when I look) at a piece of carpeting. My mind is always seeing patterns.” Photo by John Cross Renee Erdmann has turned the master bedroom of her Nicollet home into a quilting workshop, the centerpiece of which is her Gammill quilting machine. M Quick hits: Herbach’s new release, area playwright gaining exposure • Geoff Herbach’s literary star continues to rise. After the Minnesota State University English instructor won the Minnesota Book Award in April for the second installment of his Felton Reinstein trilogy, “Nothing Special,” Sourcebooks will release the final installment this month. “I’m With Stupid” is summarized on Herbach’s website thus: .” • Eagle Lake playwright Tom Barna has a busy month. Barna, who publishes under the name tdbarna, is debuting a pair of plays in May. During the Northfield Very Short Play Festival on May 4, the 22-year Marine Corps veteran will share a personal reflection on war and its effects in a 10-minute short play: “The memory recounted in this play is from 20 years ago and I can still vividly remember the night in that bunker.” Also, tdbarna will have a staged reading of “Partial Disclosure: The Bradley Manning Interview” during the prestigious Last Frontier Theatre Conference on May 23 in Valdez, Alaska. The play synthesizes the real-life actions and words of the Army soldier who passed confidential information to WikiLeaks in 2010 into a fictional prison interview: “I found it to be a fascinating story. He enjoys this worldwide popularity. ... Others consider him the traitor of the century.” M MANKATO MAGAZINE • May 2013 • 13 Partners at play Mankato gets together to make sure everyone has a good time By Nell Musolf P artnerships come in all different shapes and sizes. In Mankato, partnerships vary from the one-on-one variety that occur between volunteer coaches and ballplayers at the YMCA to larger scale partnerships between Minnesota State University and a variety of sponsors who help put on the theatre department’s dramas, comedies and musicals. Whatever form a partnership takes, there are always advantages to teamwork. 14 • May 2013 • MANKATO MAGAZINE Photo by Pat Christman Mankato lawyer Herb Kroon is one of MSU Theatre’s staunchest supporters, and his family sponsors the Phyllis and Clif Kroon Memorial Scholarship. The 2012-13 recipient was Callie Syverson, who earned a handful of leading roles in the past performance season. For many years, the Mankato Symphony Orchestra has partnered with Mankato Area Public Schools to bring music into public classrooms. According to Sara Buechmann, MSO’s director, one of the longest partnerships MSO has is the Music Education at the Elementary School Level program, which began in 1969. When the program first began, MSO musicians went to the elementary school to demonstrate instruments for the students. The program has changed so that now the high school band and orchestra students do the demonstrations. “The students donate their time and their teachers give up a day of class to make it happen,” Buechmann said. “Our orchestra pays for buses to transport the elementary school kids to the high schools and our volunteers train the high school students.” Dave Urness, music teacher for Mankato schools, agreed that the partnership between MSO and the school district has been beneficial and said that since the high school students have a good command of their instruments, the younger students want to emulate that command. The performance gives the older students the chance to show how much they have learned and accomplished musically since first starting in the orchestra. The partnership also lets the younger students see stringed instruments up close, something that many of them have never before had the opportunity to do. “My students do enjoy performing for the younger kids,” Urness said. “They love to show them what they know. These students are closer in age to the third grade kids than the adult performers are, and the younger kids relate to the high school students much better than adults.” Hearing orchestra instruments up close and personal can occasionally surprise some of the new listeners. “I did get a huge reaction this year from the kids when I had one of our bass students bring his bass out to the front so the kids could see it up close. They let out a collective ‘woooo!’” Mike Lagerquist, MSU theatre department’s director of public relations, credits partnerships with helping the college have the opportunity to present the community with highcaliber productions. Over the years, the theatre department has developed a diverse list of corporate partners, many of whom sponsor specific productions. Such sponsors have included HickoryTech, Express Personnel Services, Blethen, Gage & Krause, General Mills, Hale Associates, Gislason & Hunter, Mayo Clinic Health System of Mankato, MSU TRIO Program, MSU Women’s Center, Orthopaedic and Fracture Clinic, Eide Bailly, Farrish Johnson Law Office, Community Bank, Radio Mankato and Mankato Ford. “Sponsorships greatly increase the department’s ability to MANKATO MAGAZINE • May 2013 • 15 present recent productions whose royalty costs are quite prohibitive while keeping funds available for other things, such as student scholarships,” Lagerquist noted. Businesses and foundations that partner with the theater department do more than help entertain Mankatoans; they also gets perks such as being able to attend the final dress rehearsal to the show that they are sponsoring. During the dress rehearsal presentation, sponsors can host a reception before and/or at intermission and are also recognized in a speech before the show where they are thanked and presented with a plaque. Lagerquist said that sponsors may invite whomever they like but tend to ask employees, current business associates and potential business associates. “The people who come to sponsor previews are oftentimes not regular theatre-goers, so it gives us great visibility with a potential new audience base. It’s a great night out and a great opportunity for sponsors to thank those who help make them successful,” Lagerquist observed. One of the staunchest supporters of the MSU theatre is lawyer Herb Kroon. Kroon’s involvement with the MSU theatre department dates back to the days when he was in junior high in Mankato and began attending productions on a regular basis. His family ties to the department go back to the 1970s when his mother appeared in the department’s production of Gilbert and Sullivan’s “H.M.S. Pinafore” and “The Sound of Music.” On an individual basis, Kroon does his part by publicizing MSU theatre department productions on his KMSU-FM radio show, “Best of Broadway,” via interviews with each show’s director and actors. In addition to such personal touches, Kroon’s family has sponsored the Phyllis and Clif Kroon Memorial Scholarship that is presented annually to a single theater student. “Recently an MSU theatre department graduate landed a role in a Broadway musical,” Kroon said, referencing Claire Wellin, who landed a role in “Once” in March when the original actress took a break from the production. “She was a recipient 16 • May 2013 • MANKATO MAGAZINE of the Kroon scholarship. Many MSU theatre department graduates can be seen in excellent theatre work in the Twin Cities.” Over at the YMCA, partnering often comes in the shape of people who donate their time as volunteer coaches. According to YMCA program director Laura Diaz, volunteer coaches come from a variety of sources including the community, MSU and parents of children who are participating in various activities. “All of our volunteers go through a background check similar to our staff’s. They also participate in a meeting for the particular sport they are going to be working with,” Diaz said. The YMCA allows volunteers to pick their practice time as well as the day and location of outdoor activities. Such flexibility helps the volunteers to work around their schedules while giving the youths focused coaches who help them build their skills. Angela Kilmer has been a volunteer youth volleyball at YMCA for the past three years. Kilmer has coached the third-, fourth-, fifth- and sixth-grade groups during that time. Kilmer got involved with coaching at the YMCA when her daughter signed up for the third grade volleyball group and Kilmer offered to coach the team. She has been coaching her daughter’s team ever since. Being a partner with the YMCA as a volunteer has had many benefits for Kilmer. In addition to having the opportunity to become a part of the YMCA community, she also has gotten to see the kids she’s coached learn and grow through each season of volleyball. Kilmer said that some of the kids she has worked come have come in with only a basic knowledge of volleyball while other have come to the group already knowing how to do an overhand serve. As the coach, she has had the privilege to see the joy on the faces of the kids as they’ve achieved whatever goals they’ve set out for themselves. “I enjoy working with the kids the most,” Kilmer said. “They really make this experience worthwhile. They are so excited to File photos The Mankato Symphony Orchestra has sponsored instrument demonstrations for Mankato elementary students since 1969. get out there and learn. You get to celebrate their accomplishments with them and encourage them when they are struggling. It is truly rewarding to work with the young people at the Y.” Gene Lancaster has been coaching youth basketball teams at the YMCA for about nine years. Lancaster became involved with coaching when his oldest daughter signed up to play on one of the youth teams. He said that one of the biggest benefits of being a coach is spending practice time with his own children as well as the other kids he coaches. Watching the kids grow and develop is another enjoyable aspect of coaching. “If you want a good chuckle, show up at that first game of the season and watch one of the younger teams show off their moves. The fulfilling part comes at the last game of the season and those same kids are running an offense and playing pretty good defense. It’s hard not to smile when one of those kids make their first basket. The celebration and high fives they give each other are priceless. I guess that’s what keeps me coming back.” M Read us online! MANKATO magazine MANKATO MAGAZINE • May 2013 • 17 Photo courtesy of Andreas family Lowell and Nadine Andreas at their granddaughter’s wedding rehearsal dinner. Partners like no others The legacy of Lowell and Nadine Andreas By Pete Steiner L et’s fill in the blanks: The WORLD knows Mankato above all for _____. The people most responsible for that legacy are _____. The name is pronounced _____. I suppose there’s room for disagreement about that first blank, but I would fill it in with “soybean processing.” After all, Mankato, which was once the largest soybean processing location in the world, still ranks among the top few in that 18 • May 2013 • MANKATO MAGAZINE category. Then the second blank would be filled in with “the Andreas brothers.” (Developers of Honeymead, now CHS. Lowell would keep a Mankato address from the late 1940s on, Dwayne would live elsewhere.) And that third blank would be “ANN-dree-us.” (Many try to pronounce it differently.) The Andreas legacy locally may have begun with soybeans, Photos by John Cross In addition to the $7.5 million Nadine Andreas Endowment in Arts and Humanities, Minnesota State University bears evidence of the Andreas legacy in the Andreas Theatre and the Andreas Observatory. Elsewhere in Mankato, Mayo Clinic Health System is home to the Andreas Cancer Center. but it certainly does not end there. Go to any local artistic or entertainment venue, read the program, and the list of donors almost always begins with Lowell and Nadine Andreas, or a grant from the Andreas foundation. Perhaps only Glen Taylor comes to mind to rival the Andreases’ generosity when it comes to philanthropy in Mankato. •••• Friends remember Lowell and Nadine as generous and exceedingly loyal. That may explain why, even though Lowell’s business ventures eventually took him to ag giant Archer Daniels Midland headquarters in St. Paul and Decatur, Ill., the couple kept returning to Mankato, where he retired in 1973. “Fun” and “very smart” are adjectives friends use to describe Lowell, who was renowned for his boisterous, infectious laugh and his outlandishly loud sportcoats. Comfortable with his wealth, he rarely flaunted it beyond the fact that he drove the only Rolls Royce in town. Nadine was quieter, behind the scenes, but the two were an inseparable team. Son David says, after Nadine died, Lowell observed, “When you’ve been together 63 years, you aren’t really two people.” I was only 5 or 6 when they moved into our West Mankato neighborhood. Within a decade they built a larger house on the south edge of town, but our families remained close, with Fourth of July pool parties at their place, and holiday gatherings featuring the kids performing folk music, David on guitar. And of course, there was daughter Pam’s wedding, with 500 guests poolside, including then-Vice-President Hubert Humphrey. I knew Lowell was very successful, yet as a teenager, I found him more approachable than many other adults — it was probably that ready laugh. •••• Recently I asked David what his father was like in business dealings. “He always thought of the long-term effects. ... He was a tough trader, but understood each party in a transaction has to have some benefit. ... His way of doing business required quick decisions. ... Often when someone wanted to meet him, he would have already made up his mind what he was going to do and present them with the deal he was willing to make ... He insisted that any presentation take no more than one page.” Lowell had gone to the University of Iowa, majoring not in business, but in philosophy. He had a lifelong interest in theology, and David points out his dad had many theologians as friends and served on the Westminster Theological Seminary board. David says Lowell and Nadine always remembered their Iowa roots (Nadine was born in West Liberty) and their modest beginnings. Maybe it was that memory, and that theological bent, that spurred their generosity. David puts it simply: “They did believe in giving back.” •••• Give back they did. Rick Kimbrough, chief development officer at Mayo Clinic Health System of Mankato, was not yet on board when the Andreases worked with Norleen Rans, Bob Weiss and Dr. Bill Rupp to secure the $4 million lead donation that led to completion of the Andreas Cancer Center in 2009, shortly after Lowell’s death. But Kimbrough confirms that the Andreases had a longstanding relationship with the hospital, and “the family had received care locally and were grateful. They stepped up to the plate very generously.” MANKATO MAGAZINE • May 2013 • 19 Photos courtesy of MSU Theatre Lowell and Nadine Andreas at the groundbreaking for MSU’s black box theatre that bears their name. The $1 million that Lowell and Nadine donated for that project was the first-ever seven-figure donation to a MnSCU institution. In the photo at right, Paul Hustoles is pictured holding the microphone. Kimbrough says the $14 million facility serves thousands annually and notes, “the (Andreas) family continues to support the Palliative Care Program within the Center.” He confirms that lead donors are critical in signifying “worthy community investments”, yet notes, “it doesn’t have to be a million-dollar gift. Ten-thousand dollars can have an impact (and) advance a legacy.” •••• Paul Hustoles had arrived at then-Mankato State’s theatre department in 1985 with the mandate to get a new theatre built to expand performance opportunities. But with no state or MnSCU appropriations forthcoming, and with total private donations around $20,000 a year, the so-called “black-box theatre” was “really a pipe dream.” But Hustoles saw the Andreases were responsible for 75 percent of that annual giving and he soon learned Nadine, who had done theatre in college, represented “the heart of art.” So he decided to ask Lowell to endow a new theatre addition. Hustoles recalls the response: “You guys don’t know how to handle money,” and that the couple would prefer the annual $15,000 gift. When Hustoles subsequently learned the Andreases would fund a new observatory on campus, he sighed, “They’re giving for REAL stars, not our kind of stars!” Dean Jane Earley, however, urged him to continue pursuing the theatre project. In the early ’90s, he took a new approach: 20 • May 2013 • MANKATO MAGAZINE “We don’t want the (big) money now. ... We need $30,000 for a study.” Lowell liked that idea. Later, with new President Dick Rush, Hustoles went to the Andreases’ home for lemonade. They astounded their hosts, saying the study had cost just $20,000, so they were refunding $10,000. Lowell burst out laughing, “No one’s ever done that before!” However, Hustoles, like a matador then pulled back the red cape: “But we do want to ask you for $2 million (to build the theatre).” Before long, Lowell revealed, they would fund half the theatre. That became the first-ever $1 million gift to any institution in the entire Minnesota State Colleges and Universities system. Other gifts began pouring in. Hustoles says, “That lead gift triggered a huge surge in giving. ... It was Lowell and Nadine that did that.” •••• There’s an interesting coda: The theatre that would bear the Andreas’ name ran $200,000 over estimate. Hustoles and MSU Vice President Ron Korvas flew to the Andreas’ winter home in Florida. Never shy, Hustoles told Lowell, “You said you’d pay half. You owe me a hundred grand!” Lowell erupted with his famous laugh. Eventually he wrote a check. •••• An even larger gift was to come after Nadine’s death in 2005. According to Hustoles, Dean Earley had wanted “something more profound,” and in 2007, Lowell, along with son David and his wife, Debbie, delivered: $7.5 million for the Nadine Andreas Endowment in Arts and Humanities at MSU to fund student and faculty development and bring significant cultural events to the campus and community. •••• We’ll give Nadine the last word. After the Andreas black box theatre opened in 2000, Paul Hustoles offered Nadine “a golden ticket.” That ticket would be good for a free pass to any show the theatre-lover ever wanted to attend at MSU. Nadine’s reply? “That’s stupid — you NEED the money!” M MANKATO MAGAZINE • May 2013 • 21 The Panic host its first home game on May 4 at Nicollet High School. Putting together the Panic The makings of a semi-pro football team By Tanner Kent | Photos by Pat Christman 22 • May 2013 • MANKATO MAGAZINE Stan Legg (at right, in hat) is the owner and coach of the Panic semi-pro football team. In his inaugural season in the Southern Plains Football League, Legg has amassed partnerships with a physical trainer, wellness coach and dozens of community sponsors. T he players are huddled at midfield. The late March air is damp, swamp thick and still crackling with the snap of their shoulder pads. This is their first practice outside after months indoors and built-up aggression has punctuated every collision for the last 30 minutes. At the center of the huddled mass is Kerry Sorensen. He is tall and thickly muscular with a beard that, at 41 years old, announces his stature as the team’s elder statesman. He is glowering at the younger men, his voice commanding rapt attention. Towering above his teammates, he could be a Viking — in both senses of the word. He is, after all, wearing a helmet and shoulder pads and preparing for an eight-game season as a member of the Panic, a locally based, semi-pro football team playing its inaugural year in the Southern Plains Football League. But he recalls something, too, of the Old Norse seafarers of legend. The mist in the air has turned to heavy rain now, and his words stream forth from plumes of hot breath. With his proud and menacing stature, he would seem just as well on the prow of a longship, guiding 30 young warriors toward some gridiron siren and their Valhalla of football redemption. “Every day, I see my life wilting away a little more and a little more,” Sorensen booms into the earholes of their helmets. “What you guys have in front of you is an opportunity to do something you’ll never do again.” A s one of nine teams in the nine-man football League, the Panic will play a full schedule with rules modified only slightly from the pro game. Home games will be held at the Nicollet High School football field. Team owner and head coach Stan Legg got into the league after working with another team last year. Displaying the same tenacity and ambition that led him to open Audio Addix — a state-of-the-art music recording and media studio in St. Peter that he assembled in fewer than two months in the winter of 2012 — Legg wasted no time putting together his own team. There’s Sorensen, a father of four and former truck driver who’s gained respect for outworking men half his age. There’s a few like Garrett Mensing and Wes Berninghaus, former prep standouts with collegiate skills; and many more like Matt Sharits, a 2003 Lake Crystal Wellcome Memorial graduate who last played for a one-win high school team and is willing to sacrifice his body for one more chance to play. Caleb Huls, the team’s defensive captain who played formerly for Gustavus Adolphus College and proved himself a dominant player in the league last year, summarized the driving motivation for many of the players. “I wasn’t ready to quit,” said the 2010 Mankato East graduate. “I have a lot of fight left in me.” When Legg had a team assembled, he lined up a scrimmage last December — in the Metrodome, of all places — and began investing more than $10,000 in helmets, pads, jerseys, merchandise and team apparel. His vision is of a family-friendly, minor league-style atmosphere. He’s secured food vendors for home games, bought a T-shirt cannon, recorded a team anthem and put together an in-game soundtrack of more than 40 songs and sound effects. Legg has secured more than 20 local sponsors and is emphasizing the same community-mindedness he’s made part of his mission at Audio Addix. But his vision also includes a winning team — and not only that, but a team that looks, acts and performs like it’s composed of serious athletes. MANKATO MAGAZINE • May 2013 • 23 Panic 2013 schedule May 4 — host Dodge County Outlaws, 7 p.m. at Nicollet High School May 11 — at Buffalo Ridge Wildcats May 18 — at Minnesota River Valley Shock May 25 — host North Iowa Bucks, 7 p.m. at Nicollet High School June 1 — host Tri-State Buffaloes, 7 p.m. at Nicollet High School Quarterback Garrett Mensing (in red, above) is a former Blue Earth Area standout who played two years at the University of Minnesota-Morris: “Playing in this league is all about the love of the game.” June 8 — host Albert Lea Grizzlies, 7 p.m. at Nicollet High School June 15 — at Steele County Warriors June 22 — at South Central Hawgs For more information on teams and schedules, visit. To that end, he’s recruited a team trainer and a wellness coach. He’s demanded participation in thrice-weekly practices and has set a high standard of dedication for his players. “Nate and I feel a lot of pressure,” he said, referring to his fellow coach and business partner Nate Showalter. “We feel pressure to make sure the fans have a great experience. But there’s been so much hype — we feel pressure to win, too.” T he smells, sights and sounds of pain fill the Lincoln Community Center gymnasium. This is where the team practices indoors, and where its players experienced regular 45-minute plyometric workouts delivered by Jo Ann Radlinger, a powerlifter, personal trainer and slightly built but muscle-bound dynamo who is the team’s physical trainer. These are frenetic, highly intensive, muscle-destructing regimens that break down the sculpted bodies of football players into a soup of lactic acid, metabolites and soreness. They include hundreds of crunches, hundreds of plyometric jumps, several long periods of planking exercises, pushups, jumping jacks, burpees and other core-strengthening and agility drills. After the workout, dozens of young men are strewn about in various stages of exhaustion. Some are sucking wind through red, huffing cheeks. Others are pale and sallow, scanning the room for the nearest trash can. Privately, she praises the players and ranks this role as one of the highlights of her training career. But, in the midst of this crowd of mostly 20-something testosterone-laden jocks, she yields nothing. Her mission is clear: “I want these players to be fast, explosive and injury-free.” And there’s only one way to do it: “If they’re looking for a patty-cake, pansy trainer, that isn’t me. ... On scale of 1-10, this workout is a 10-plus. I want them to not like me.” 24 • May 2013 • MANKATO MAGAZINE Later, the players will visit Rhonda Anderson, a wellness coach with Symmetry Nutrition in Mankato. Each player on the team has regular body scans and counseling sessions about diet and nutrition. Anderson sets individual targets for each player, carefully weighing their calorie intake against body fat percentages, physical activity levels outside football, and a host of other factors. For instance, after discovering that a number of players were actually losing muscle mass because of strenuous day jobs combined with Radlinger’s workouts, she recommended ways to boost protein intake. “We have had everyone on the spectrum. Everyone has a different goal,” Anderson said. “We are working together to get these guys in tip-top shape.” The season begins soon. Pressure is mounting. Urgency has crept into the practice proceedings at Gault field in St. Peter. Since Sorensen’s pep talk at midfield, players have responded by ratcheting up their intensity. Legg is prowling the field, watching every move, alternately offering encouragement and criticism as players fight to earn his favor. The team is coming together, he says. The workouts with Radlinger and the wellness counseling sessions with Symmetry are paying off. Players are in the best physical shape of their lives and are starting to look like a serious outfit. Legg has big goals for this team. He hopes to build it into a stable and profitable entity, one that could perhaps someday afford its own stadium and offer the Mankato area a unique entertainment option. But, he knows he must take one practice, one game, one season at a time. Still, he can hardly contain his ambition. The national championships are in July, he says, eyes flashing with excitement. “I’m serious about a winning team. I want a team the community can be proud of.” M MANKATO MAGAZINE • May 2013 • 25 Reflections By John Cross T he annual give-and-take battle in Minnesota between winter and summer is better known as spring. Two years ago, summer triumphed early on, leaving south-central Minnesota residents basking in record warmth already in March. This year, however, winter has maintained the offensive advantage, delivering snowstorms and unseasonably chilly weather throughout the month of April. Nevertheless, the outcome of this seasonal conflict is pre-ordained: When May rolls around and under the strengthening gaze of the sun, snowbanks and lake ice will be in full retreat. Soon to follow will be an army of emerging greenery accompanied by explosive displays of flowery color. Summer, most would agree, is a much kinder occupying force. M 26 • May 2013 • MANKATO MAGAZINE MANKATO MAGAZINE • May 2013 • 27 Day Trip Destinations: 100 Mile Garage Sale r e v E a E By Sarah Zenk Blossom e r e h yw e l a S ach year, during the first weekend in May, thousands of shoppers — in fact, about 50,000 of them — descend upon the picturesque Mississippi River valley for the annual community garage sale. This is not just any sale; this is the 100-Mile Garage Sale. It extends from Winona to Red Wing on the Minnesota side of the river and from Fountain City to Prescott on the Wisconsin side. The sale is organized by Mississippi Valley Partners. Entire streets are blocked off. There are The 100 Mile Garage no maps, because, according to Larry Sale from Winona to Red Wing takes plac Nielsen, president of Mississippi Valley e May 2-4 Partners, “You don’t need a map. There are signs up, and it’s T h e re real obvious where all the sales are. You won’t have one iota of are pet supplies. There are trouble finding the sales. You’ll see signs along the highway. baked goods and beverages. If you can imagine it, you can Everything’s identified. You just show up and start driving probably find it at the 100-Mile Garage Sale. One of the down the road, and you will find garage sales. reasons the sale is so popular is its setting. “As near as we can tell,” Nielsen continued, “it’s one of the “It’s a really scenic drive,” Nielsen said. “Everybody really largest garage sales in the United States” enjoys it. It’s one of the more scenic places in North America.” When asked exactly how many sales there are, Nielsen said: The Mississippi valley between Winona and Red Wing is “Boy, I tell ya. I would say each town might have 100 or 200 nationally known for the beauty of the river, its bluffs, its water, sales, and the towns are about 10 miles apart up and down the and its natural surroundings. river, maybe 16 of them, so it’s approaching 2,000 sales in the “It’s world-class scenery,” Nielsen said. Shoppers from the whole region. You can walk 30 or 40 sales in just a few blocks.” Twin Cities, Chicago, Rochester, Mankato, and many other Anything conceivable is for sale — clothes, household nearby cities gather for the sales, and while it’s possible to find goods, art, antiques, even cars and boats. There are sporting lodging on short notice, Nielsen recommends making goods and hunting equipment. reservations in advance. “Bowflexes are gone in 10 minutes,” Nielsen said. This year will be the 15th annual sale, and it takes place There have been RVs sold. There is gardening equipment. May 2-4. M 28 • May 2013 • MANKATO MAGAZINE Along the Way Red Wing In addition to endless baragins, visitors to the 100 Mile Garage Sale can count on pictaresque Mississippi River Valley scenery. Pictured is downtown Red Wing. One of the best-known oddities along the river is the Red Wing Shoe Museum, located at the northern end of the sale route in Red Wing. It is housed alongside the Red Wing Shoes retail store and is home to world’s largest boot, a 16-foot-tall, 20-foot-long ... foot. The Aliveo Military Museum is also in Red Wing. At the other end of the 100-mile garage sale lies Winona, home of the Watkins Museum. Exhibits tell the story of the J.R. Watkins Company and the traveling salesman, and the museum architecture features marble, glass tile mosaics and semi-precious stones. Winona is also home to Winona County History Center, the Polish Cultural Institute and Museum, the Minnesota Marine Art Museum, the Pickwick Mill and others. In Wabasha, visitors can dine at Slippery’s Bar and Restaurant, featured in the movie “Grumpy Old Men.” Here, it is possible to boat up to the 200-foot dock, and boat parking is offered. Many interesting restaurants can also be found in Winona and in Lake City, and all along the river. Along the 100-mile sale route, it is also interesting to note that Lake City is where waterskiing was invented in 1922, and that Dennis A. Challeen was the first judge to sentence with community service hours, which started in Winona before spreading nationally. Rochester and Mantorville The drive from Mankato to the Mississippi valley yields a variety of attractions in Rochester such as the Mayo Clinic, the Mayowood estate, Assisi Heights chapel, and the Rochester Art Center. Between Mankato and Rochester is the historic Hubbell House restaurant, located in Mantorville, just north of Kasson. In 1854, John Hubbell constructed the original Hubbell House, a hotel and popular stagecoach stop. Two years later, the current structure was built. The three-story building is now home to a restaurant where history is tangible, and plans to restore the entire village of Mantorville have been under way since 1963. Most will take Highway 14, which is the Laura Ingalls Wilder historic highway. Maps are available from Explore Minnesota that detail the historic sites associated with her life and writing. Rochester The Red Wing Shoe Museum is home to the world’s largest boot. Fountain City Winona The Rock in the House The Mayo Clinic in Rochester is one of many attractions in that city. Just north of Winona is Fountain City, Wis., home of the Rock in the House. Not to be confused with the House on the Rock (an architectural site in Spring Green, Wis.), the Rock in the House is a 55-ton boulder that rolled down a hill in 1995 and came to rest in the middle of Maxine and Dwight Anderson’s master bedroom. The rock, still inside the house, is now a roadside attraction. Even more curiously, the house and the rock stand on the exact site of a similar incident that occurred in 1901. In that incident, homeowners Mr. and Mrs. Dubler slept next to one another in the same bed. The boulder that rolled through their home killed Mrs. Dubler but left Mr. Dubler unscathed. MANKATO MAGAZINE • May 2013 • 29 That’s Life By Nell Musolf Birth (and graduation) of a salesman I t’s that time of year again when school fundraising sales campaigns are in full bloom. It’s the time of year when neighborhood children are about as popular as fire ants than pulling out a hot pink sheet of paper announcing, gulp, yet another fundraiser. While I understand why the schools need to resort to fundraisers, especially during these dismal financial days, I also have to say that the day our sons graduated from the public school system a n d would no longer be called upon to help prop up sagging budgets with their generally futile attempts at selling was a very good day indeed. Our oldest son Joe introduced us to the dreaded world of candy bar sales on the second day of kindergarten when 30 • May 2013 • MANKATO MAGAZINE he came home with an enormous cardboard box filled to the brim with chocolate bars along with a brochure that explained Joe’s job was to sell those candy bars and win points for his class and possibly “fabulous prizes” for himself. He already had his “fabulous prize” picked out: a teeny, tiny radio that promised “stereo quality sound.” To win such an awesome prize, he needed to sell a mere 400 candy bars. After a few hours of doing the door-to-door bit under the hot September sun with the chocolate bars melting and my nerves fraying, Joe was more than ready to retire from the glamorous world of door-todoor as a timid 8-year-old,. Joe and Hank. M Nell Musolf is a mom and a freelance writer from Mankato. MANKATO MAGAZINE • May 2013 • 31 Garden Chat By Jean Lundquist Overcoming hoop house woes T here are two dates gardeners of all ilk need to keep in mind. The important one for this time of year is the last usual date of frost. In 2013, that date is May 20. If climate change is real, it will likely change to an earlier date, at some point. But for now — burn it in your brain — May 20 is the last date of frost. Usually. That is a week after the fishing opener in Minnesota, so it’s easy to remember. The 20th this year is a Monday. I will either have to take vacation from work, or push the envelope just a little and set plants and sow seeds the weekend before. This year I started seeds in the basement right on time — the Ides of March (that’s March 15). I used the heating mat again this year, and the plants I set out will never have been bigger. I really believe it’s because of the warmth from the mat. Our basement is beneath a house that is more than 50 years old. The basement is unfinished, and minimally heated. I had expected the mat to help with germination, more than anything. But I start my seeds in Solo cups, and yes, most of them are red. The seeds near the top of the cup, close to the surface of the seed starting mixture, are several inches from the seed mat. Germination was not aided in the least. But once the little plants sprouted and sent down roots, did they ever grow! Usually in late April or early May, I transplant them each to their own Solo cup, to untangle their roots. This year, I had to transplant them the first weekend in April to untangle their root systems. Was the seed mat worth $100? I’m not sure. But it certainly didn’t hurt anything. Several years ago, I had a seed heating mat, and it melted the solo cups and the flat they were set into. I was happy I found that before the house caught fire. I don’t know why I tried it again, but I’m not sorry I did. When I transplanted my seeds in past years, I always tried to choose a rainy, cool day. I’d sit in Carol and Dale’s hoop house with the doors shut, in a nice, warm environment, and listen to the rain fall gently against the plastic. I always felt cheated if I had to do it on a sunny day, with the doors open, and no rain. When finished, I’d step out into the rain, shiver, and run for my car. This year, of course, I have my own tiny version of a hoop house. It’s so small, it’s portable, and it’s perfect. Or so I hope. I set my hoop house up in early April, and planted some 32 • May 2013 • MANKATO MAGAZINE My Brussels sprouts and Brandywine tomatoes have benefited from the use of a heating mat. mesclun and some spinach for the chickens. When I went out to actually plant the seeds, a few hours after it had been up, I stepped inside, and discovered it was raining — inside the hoop house. Humidity and condensation were definitely a problem. A few hours later, I visited again, and was rained on again. I unzipped one of the doors a little and left it for the night. The next morning, it was still raining in there. I unzipped the door some more. It was below freezing that night. When I went to check the next morning, I found that when the plastic hoop house was disturbed, it was hailing on me. The temperature was down to 20 degrees, just like outside. Later, of course, it rained some more when the temperature was 80 degrees. I started to wonder if I was smart enough to figure out how to make this little hoop house work without having all my seedlings just mold to death. I whined to Carol about my woes, and she told me to get a cross-breeze going in there. So I unzipped the opposite door a little. No more rain! Carol has graciously invited me to use her hoop house again this year while I figure things out. One of the loneliest things about not using her hoop house was not seeing her or Dale on a daily basis. Still, I think I am going to put a few “extra” seedlings in my hoop house, and work out the process. The worst that can happen is that I’m successful, and friends get some extra garden seedlings. M Jean Lundquist is a master gardener who lives near Good Thunder. INSET CABINETRY IS 20% OFF 10% OFF LYPTUS CABINETS 15% OFF ALDER & RUSTIC ALDER CABINETS These discounts discounts are are effective effectivethrough through Friday, Friday, May May10, 31,2013. 2013. 219 S Victory Dr | Mankato 507 | 345 | 7009 ipaf@hickorytech.net independentpaintandflooring.com HOURS: Tue & Wed & Fri | 9 am to 6 pm Mon & Thu | 9 am to 7 pm Saturday | 9 am to 4 pm EQUAL HOUSING OPPORTUNITY MANKATO MAGAZINE • May 2013 • 33 Then and Now: Story and Photos by Sarah Zenk Blossom Artist depiction of the old Bierbauer Brewery in Mankato. The front gate still stands at the eastern terminus of Rock Street in Mankato. Beers over the years Mankato Brewery revives local beer-making tradition T im Tupy shows me two small jars filled with grain. The contents of one are milquetoast plain; the contents of the other are rich and dark. They look like ... chocolate? Coffee? He explains that only a small proportion of the grains used in craft brews are specialty-roasted like these; most are base malt. The base malt is beige and looks like health food. Tupy co-owns the Mankato Brewery, and once these grains are ground, they are fed into the mash tun just on the other side of the wall. From there, the wort is made, fermented into beer, filtered and tested, and packaged. Of course, at the Mankato Brewery, this is done using modern technologies, but Tony Feuchtenberger, co-owner, explains that, “historically, [breweries] were built on hills because everything was run by gravity.” Everything started at the top of the hill, and then “they’d literally roll the barrels out and store them in caves at the base of the hill.” Tupy and Feuchtenberger founded the brewery on Jan. 5, 2012. “Mankato intrigued us,” Tupy explained. “It had not 34 • May 2013 • MANKATO MAGAZINE had a production brewery since 1967. The brands (in the area) at that time were Kato Beers, Jordan, and Regal. If they’d had a local market, things might have gone differently, but at that time, there were Hamm’s and the big national brands taking over and cannibalizing some of the small regional breweries. That’s also when you see beer being made cheaper, and prices were dropping significantly.” Marge Leiferman, whose father owned the Mankato Brewing Company during its final years, explained that there were internal difficulties, while a Free Press article from 1967 lists a litany of problems, both internal and external — with management, with money, with taxation, with local support. The Mankato Brewing Company had been founded in May 1933 by Gerald R. Martin of Minneapolis in an attempt to revive its predecessor, Bierbauer Brewing, which had closed during Prohibition. Bierbauer had been in business since 1857, and despite heavy competition during the 1870s and 1880s, thrived right up until beer was banned in 1920. When it closed, the Bierbauer brewery could produce 25,000 barrels per year. After 13 years of Prohibition, the building reopened, but not without some changes. As the Bierbauer brewery was transformed into the Mankato Brewing Company, 80 men worked to refurbish and expand it, and its new capacity was around 90,000 barrels annually. It has been noted that the Mankato Brewing Company’s purchase of the Schutz and Hilgers brewery building in Jordan overextended the company significantly and, in 1951, the Cold Spring Brewing Company took over. Cold Spring used the brewery building for three years and in 1954, Mankato Brewing Company came back under new ownership. Lieferman has collected some artifacts from this time period and from the previous incarnation of Mankato Brewing Company. “The chairs were three-legged,” she said, displaying the last remaining set of them. “They were a little tipsy when you were a little tipsy.” There are several different bottle labels, each bearing the Kato Beer griffin logo. There is a bottle opener, a tasting glass, stationery. Inventory slips. “Artifacts are difficult to find,” Leiferman said. “People who have them are usually not interested in selling them.” Mankato Brewery does have a keg on display from the old Mankato Brewing Company. “Our distributor gave us this as a gift,” Tupy said. The keg sits in the tasting room, which is a space that reflects Tupy and Feuchtenberger’s commitment to the community; it is furnished with stunning wood countertops, handmade paddles that hold four tasting glasses, and a tap for 1919 Root Beer. Most of the brewery supplies are sourced locally, too: boxes, labels, bottles, and grains all come from suppliers based in Minnesota. The tasting room is open 4-7 p.m. on Tuesdays, Thursdays and Fridays, and noon to 5 p.m. on Saturdays. Tours are offered at 1 p.m. on Saturdays. The old gate of the Bierbauer Brewing and Mankato Brewing Company building is still visible on Seventh Street and Rock, and the extensive Jordan Brewery ruins appear on the National Register of Historic Places. M Brewery paperwork from the 1940s and 1950s. Mankato Brewing Company bottles and memorabilia from the 1950s and 1960s. A three-legged stool from the tasting room of the previous incarnation of the Mankato Brewing Company. A Mankato Brewing Company ration book holder, circa 1943. MANKATO MAGAZINE • May 2013 • 35 Coming Attractions: May By Wess McConville 3 • Lafayette Charter School’s “Twilight Trot” 5K & 1K run/walk Registration and packet pickup at 5 p.m. • $25 registration for 5K, $10 for 1K • Begins and ends at Lafayette Charter School • 351 Sixth St., Lafayette • 3-4 • MSU Spring Dance Concert 7:30 p.m. May 3, 2 p.m. May 4 • Earley Center for the Performing Arts • $10 general admission, $9 discounted, $8 MSU students • 4-5 • MSU presents “Gianni Schicchi” opera 7:30 p.m. May 4, 3 p.m. May 5 • Halling Recital Hall • $12 general admission, $11 students with MavCard •. edu/music 4 • MACS Night 6 p.m.• 145 Good Counsel Drive • free • 388-2997 4 • MAD Girls vs. Moose Lake Mafia Roller Derby Girls 6 p.m. • Verizon Wireless Center • $10 in advance, $12 at the door, free for children 10 and under • greatermankatoevents.com 4 • Mankato Ballet Performing Company presents “Stars & Stripes” 1 p.m. & 5 p.m. • Mankato West High School • 1351 S. Riverfront Drive • $8 adults & children, children under 2 admitted free • 4 • The Gustavus & Vasa Wind Orchestras’ Spring Concert 7:30 p.m. • Bjorling Recital Hall, Gustavus Adolphus • free • 4 • Arthritis Walk-Southern Lakes 9 a.m. to noon • Spring Lake Park • 609 McKinley Ave., North Mankato • free • 4 • 7@7 Trail Race/Fun Run 9-11 a.m. • Seven Mile Creek Park • Highway 169 between Mankato and St. Peter • $35 for 7-mile run and 5K, $14 kids run • 5 • Walk MS: Mankato 11 a.m. to 4 p.m. • Myers Field House, MSU • free • www. greatermankatoevents.com 7 • “Fingerprints and Footnotes” walking tour of Front Street 6-8 p.m. • Blue Earth County Historical Society Heritage Center • 415 Cherry St., Mankato • free • 9-12 • Gustavus Adolphus presents “Machinal” 8 p.m. May 9-11, 2 p.m. May 12 • Anderson Theatre, Gustavus Adolphus • $9 adults, $6 seniors and students • 36 • May 2013 • MANKATO MAGAZINE 10-12 & 17-19 •Merely Players present “The Taffetas” 7:30 p.m. • Lincoln Community Center Auditorium • 110 Fulton St., Mankato • 11 • 14th Annual Cystic Fibrosis Great Strides Walk Registration at 9 a.m., walk begins at 10 a.m. • Minnesota Square, St. Peter • Participants are asked to raise $125 for a T-shirt and lunch • 507-327-7431 11 • Mother’s Day photos at Cambria Studios 10 a.m. to 1 p.m. • Cambria Studios • 44 Good Counsel Drive, Mankato • 952-944-1676 14 • Senior Expo 9 a.m. to 2 p.m. • Verizon Wireless Center • free • 15 • The Choir of Christ Chapel Home Concert 7:30 p.m. • Christ Chapel, Gustavus Adolphus • 16 • The Lucia Singers & St. Ansgars Chorus in Concert 7:30 p.m. • Christ Chapel, Gustavus Adolphus • 18 • The Gustavus Philharmonic Orchestra in Concert 1:30 p.m. • Bjorling Recital Hall, Gustavus Adolphus • 18 • SSND presents Wine and Chocolate Soiree 5:30 p.m. • Our Lady of Good Counsel Campus • 170 Good Counsel Drive, Mankato • $50 • 507-389-4231 18 • Mankato Symphony Orchestra presents “Mozart in Me IV” 11 a.m. • Mankato YMCA • 1401 S. Riverfront Drive • $10 adults, $5 youth under 18 • 507-625-8880 19 • Mankato Symphony Orchestra presents “Lonely Planet” 2 p.m. • 170 Good Counsel Drive, Mankato • $12 in advance, $15 at the door •, 625-8880 21 • Taste of Home Cooking School 7 p.m. • Verizon Wireless Center • Premium $39.91, General $16.18 • May 24 • Whacking Dead Golf Tournament 6:30 registration, 7 p.m. dinner, 8:30 tournament • Terrace View Golf Course • $75 • www. whackingdeadgolf.com 25 • Downtown Shopping Spree in Benefit of Relay for Life 9:30 a.m. • City Center Hotel • 101 E. Main St., Mankato • free • 25 • Second Annual Lake Crystal Duathlon and Kids Fun Run 8:15-11 a.m. • Lake Crystal Recreation Center • 621 W. Nathan St.• free • 29 • Bethany Choir Homecoming Concert 7 p.m. • Trinity Chapel, Bethany Lutheran College • free • 7@7 Trail Race/Fun Run to involve mud, fun and charity MANKATO — Run through wooded trails and have the chance of winning $500 toward the charity of your choice at the Greater Mankato MultiSport Club’s 7@7 Trail Race/Fun Run, May 4 at Seven Mile Creek Park. “We’re now in the third year of the 7@7 run,” said Chris Crocker of the Greater Mankato MultiSport Club. “We’re pretty excited we can keep it going, help charity and get people physically active.” The 7@7 Trail Race/Fun Run will have a seven-mile course, a 5K fun run/walk and a onekilometer kid’s run. The top male and female finishers of the seven-mile race will win $500 for charity. In addition to the race, there will be a babysitting service for children older than 3 and Dance Express will have activities to offer. For more information, visit. MANKATO MAGAZINE • May 2013 • 37 Your Health By Lenny Bernstein | The Washington Post Ice or heat? C The debate continues to inflame opinions on 38 • May 2013 • MANKATO MAGAZINE. M Boat Loans Providing Excellent Service in: • Janitorial Services • Window Washing • Carpet Cleaning • Water, Fire & Smoke • Hard Floor Care Restoration • Family Owned Since 1973 • Insured & Bonded MANKATO MAGAZINE • May 2013 • 39 Your Tastes By Elaine Gordon | The Washington Post These are the salad days of farmers markets W ith all the recent interest in locally grown, farmfresh. Feeling inspired? The accompanying salad recipe — one to 1 1/2 inches is the ideal diameter. You want the green leaves to be fresh and not wilted. As soon as you get home. Note: The beets can be roasted, cooled, peeled and refrigerated a day or two in advance. The vinaigrette can be refrigerated a day or two in advance. Bring to room temperature before using. From Elaine Gordon, a master certified health education specialist and creator of EatingbyElaine.com. 40 • May 2013 • MANKATO MAGAZINE Steps. from the market, trim off most of the greens, leaving only one. Get ready for the market Proper preparation can help make a good experience great. Follow these guidelines to get the most out of your farmers market: • Bring reusable, clean bags to carry your goodies home. Use separate bags for raw and cooked foods. • Bring storage containers for delicate produce such as berries and cherry tomatoes that might otherwise get crushed when combined with other products. • Arrive early in the day before the crowds for the best selection. That perfectly plump tomato will be the first to go. However, if you do go toward the end of the day, you might get some good deals. • Bring cash in small bills with a bag for change. •. •. Gordon, a master of public health professional and a master certified health education specialist, is creator of the healthful recipe site EatingbyElaine.com. M MANKATO MAGAZINE • May 2013 • 41 Your Style Jennifer Barger | The Washington Post Bright, black or white: Dress cool for warmer weather N eprint shoes, a lace top, maybe jeans in “it” color mint. “Yes, a few of these ideas can be mixed, say lace shorts with a bright print,” says Julie Egermayer, owner of the Violet Boutique in Washington. “But the easiest trend? Black and white. It’s something we come around to again and again.” Sort of like spring itself. Lace Formerly prim, lace gets racy when sewn onto short shorts. Black Sheep shorts ($68, South Moon Under stores and www. southmoonunder.com; Timing striped top ($29, Willow boutique in Washington and Arkansas City, Kan.); and Melissa “Prism” wedges ($145) and Alexis Bittar bangles ($155 each), both available at The Shoe Hive in Alexandria, Va., and TheShoeHive. com. Neon Tame the shades of traffic signs and 1980s Madonna videos by pairing them with crisp white. Tibi peplum top ($350, B l o o m i n g d a l e ’s ) ; Hudson jeans ( $ 1 6 5 , Bloomingdale’s); vegan “leather” clutch ($49) and faux gem necklace ($24), both from Violet Boutique; CC Skye bracelet ($315, Bishop Boutique in Alexandria, Va., and; and Kate Spade sunglasses ($138, couture.zappos.com. Black and white The classic noncolor on noncolor combo looks fresh in new shapes and styles. Tracy Reese convertible silk pleat shorts ($248,; Maeve black tank ($68, Anthropologie); Waverly blazer ($264, Zoe Boutique in Alexandria, Va.); Alexis Bittar black and white rings ($35 each, The Shoe Hive); chandelier earrings ($12, Violet Boutique); Charming Charlie belt ($8, Charming Charlie stores and; and L.K. Bennett “Sandy” strappy heels ($365, Shopbop.com). Tropical prints Are-we-in-Jamaica? patterns scream spring break — in a non-trashy-movie way. BB Dakota pants and tank ($78 and $78, South Moon Under); Remi & Reed belt ($42, South Moon Under); CC Skye cuff ($175, Bishop Boutique); long necklace ($16, Violet Boutique); and MICHAEL Michael Kors wooden “Josephine” wedges ($185, Zappos.com). Mint Skin is now also in for hotter months. It’s especially nice paired with ice-cream-dreamy mint. Vince gray leather motorcycle jacket and gray T-shirt ($995 and $78, Bloomingdale’s); Modern Supply Clothiers mint-green chinos ($88, Bloomingdale’s); earrings and necklace ($10 and $20, Violet Boutique); and Target bracelet ($20, Target stores). Accessories Nanette Lepore coral blouse ($228, Bloomingdale’s); Elaine Turner black and white clutch ($75, www. elaineturner.com; Jon Josef pastel blue raffia shoes ($140, The Shoe Hive); and J. Crew mint and teal bag ($295, J. Crew stores). M Car Loans We’ll help make your dreams come true. The group you can trust with your savings. Call Michelle today. Securities offered through National Planning Corp. (NPC), Member FINRA/SIPC. Advisory services offered through The Sherwin Group, Inc. ; a Registered Investment Advisor. The Sherwin Group, Inc and NPC are separate and unrelated companies. MANKATO MAGAZINE • May 2013 • 43 Happy Hour By Jennifer Kay | Associated Press Rum plays up — and ignores — its Caribbean roots W hen. 44 • May 2013 • MANKATO MAGAZINE.” M MANKATO MAGAZINE • May 2013 • 45 46 • May 2013 • MANKATO MAGAZINE Great Rides Deserve Great Rates. IT PAYS TO BANK WHERE YOU’RE PART OWNER! 387-3055 THE CLASSIC CAMP ALL SUMMER LONG. ALL AGES. ALL KINDS OF CAMPS. For backpacking preschoolers to skateboarding teens. From half-day camps to resident camps. The Mankato Family YMCA offers another great summer. Bus transportation is provided as well as before- and after-care to make dropping off and picking up easy on parents. Contact the Y at 387-8255 or at mankatoymca.org. MANKATO MAGAZINE • May 2013 • 47 Faces & Places Photos By Sport Pix MSU Alumni Family Rock climbing Event 1 1. Dan Cole stops for a photo before continuing his climb. 2. Spectators watch others climb the wall. 3. Dan Cole climbs inverted on the most difficult part of the rock wall. 4. Molly Rorvig smiles as she skillfully makes her way up the wall. 5. Visitors wait their turn as they watch others climb the rock wall in Myers Fieldhouse. 6. Sam Steiger gives encouragement to a young climber during the event. 2 4 48 • May 2013 • MANKATO MAGAZINE 3 5 6 Faces & Places Photos By Sport Pix YWCA Women of Distinction 1. Julie Vetter gives a speech while receiving her award. 2. Donna Norgren, founder of the YWCA Women of Distinction event, receives a standing ovation and a bouquet of flowers. 3. Mary O’Sullivan gives an introduction for her nominee Pam Determan. 4. Current and former Women of Distinction gathered before the event for a group photo. 5. Former Minnesota State University President Margaret Preska talks with some friends at the event. 6. State Rep. Kathy Brynaert chats with some friends during the social hour. 2 1 3 4 5 6 MANKATO MAGAZINE • May 2013 • 49 Faces & Places Photos By Sport Pix St. Peter’s St. Patrick’s day parade 1 1. Elizabeth Munick and Madison More get fully decked out in holiday apparel for the parade. 2. The St. Peter Crusaders entertained the crowd with a few tunes. 3. The Miss Arlington roaylty, Kimberly Kurtzweg, Jessica Garza and Sarah Shimota, wave to the crowd. 4. Connor Bjorling sports a green mohawk as he walks the parade route. 5. Adam Spector, who spends his days working for the St. Peter High School, waves to the crowd. 6. Sevyron Brandt, a member of the Govenaires Flag Team, had one of the brightest outfits of the day. 2 4 50 • May 2013 • MANKATO MAGAZINE 3 5 6 It’s May. The sun is up earlier and so are we. We’re making delicious Hot Sandwiches on homemade cheddar biscuits. Grab one with bacon or sausage and the local eggs and cheese we are known for...it’s the most important meal of the day! 228 Mulberry Street, St. Peter, MN stpeterfood.coop Open 7 a.m. to 9 p.m. daily. Everyone is welcome everyday! good morning breakfast at the co-op 7-11 everyday MANKATO MAGAZINE • May 2013 • 51 Remember when By Pete Steiner Boys of summer, and other recollections “We’re not raising grass, we’re raising boys.” — Harmon Killebrew Sr., father of Twins Hall of Famer, quoted by Harmon at his Hall of Fame induction G rowing up in West Mankato in the ’50s and ’60s, we of course did not have video games for our amusement. What we did have was a big backyard, plus lots of imagination. That meant our backyard was sometimes a football field, or sometimes it was a make-believe World War II battlefield (and I wanted to be the general). But what I remember most was that just about every summer, for the better part of a decade, that backyard was a ballfield. With nearly two dozen boys between 9 and 14 in a several block radius in our neighborhood, it seemed a majority of them often ended up in our backyard. In 1953, according to Wikipedia, David N. Mullany had invented the “wiffle ball” at his home in Fairfield, Conn. He had designed a ball that curved easily for his 12-yearold son. A classic wiffle ball is about the same size as a regulation baseball, but it’s hollow plastic no more than 1/8inch thick, often perforated to help it curve, causing the batter to “whiff,” or strike out. For us, it didn’t matter whether the ball was “classic,” whether it was small or large, or whether the plastic bat was regulation size, or oversized with a giant 6-inch barrel. We just wanted to get out in the backyard and swing for the fences. Or rather, swing for the poplar trees that bordered the yard, and constituted center field, or for the telephone pole that marked the left-center fence, or the “short porch” straight down the line toward the hackberry next to Berge’s garage that represented the left field foul pole. From June through August, we would be out there for hours every day, with pickup teams, tramping down the grass into 52 • May 2013 • MANKATO MAGAZINE basepaths. I broke my wrist one summer racing into the small sapling that represented second base. We kept rather meticulous records. As avid baseball card collectors, we all wish we still had our Hank Aaron and Mickey Mantle rookie cards. We had memorized our favorite major leaguers’ “stats,” and then went out to tally up our own. I think Davey Brown still holds the single-season home-run record, in the vicinity of 120. He had quick wrists, sort of like Aaron. Davey liked to turn on the ball quickly to take advantage of that short left field. •••• By the time we reached high school in the early ’60s, we’d pretty much outgrown wiffle ball. But our poor backyard was still mostly dirt. Rather than investing in grass seed, our dad decided to build an asphalt, 20-by-20 basketball court. That brought another decade of backyard joy. We’d even shovel off November snow if it wasn’t too cold, so we could go out hoopin’. I’ve never before contemplated the psychology of parents’ forsaking the perfect lawn for basepaths and asphalt courts. But you know, I think Mom enjoyed knowing where we were much of the time — right out the kitchen window. •••• In Minnesota Valley Business Magazine this month, I write about Mocol’s, the last surviving neighborhood grocery store in town. There used to be similar stores in nearly every corner of town, and sometimes Dad would take us to the Farho sisters’ store on South Front, across from where the Mankato Ballet studio now stands (formerly Earthly Remains). That’s me, swinging fo backyard sandlot ar r the fences in our ound 1960. Annie and Jo were colorful characters and shrewd businesswomen from an era when many women still did not work outside the home. I remember they always had a big banana bunch hanging from the ceiling near the main counter. Dad, an insurance man well-versed in risk, would advise his young sons not to touch the bananas for fear there might be a black widow spider hiding somewhere in there. Probably prevented me from becoming a vegetarian. I seem to remember — of course, memory can trick us — the floors were wood. The grocery was torn down in the late ’70s or early ’80s, but the Farho sisters also operated a liquor store two doors down. Dad insured the sisters, so he would also shop there. I tell this story as a reminder that small kindnesses are not soon forgotten. I was home from Army basic training early in 1970, about to ship out to Fort Dix for assignment. Dad related this fact to Annie, who said, “Come over here,” and led me to a shelf. She grabbed a pint of Old Sunny Brook blended whisky and gave it to me, thinking I might have use for it. I remember going to great lengths to hide the contraband in my locker at Fort Dix. Annie was certainly right about having a use for it. M Pete Steiner is host of “Talk of the Town” weekdays at 1:05 p.m. on KTOE. Quality When ooring is one of the biggest investments you make in your home, quality counts. | http://issuu.com/dhabrat/docs/kato_mag_5_13 | CC-MAIN-2015-48 | refinedweb | 14,601 | 71.24 |
config_get_message_routing_domain
Name
config_get_message_routing_domain — Determine where to place a message
Synopsis
#include "hooks/core/config_get_message_routing_domain.h"
int **core_config_get_message_routing_domain** ( | closure, | |
| | cs, | |
| | m, | |
| | buff, | |
| | len
); | |
void * <var class="pdparam">closure</var>;
generic_module_infrastructure * <var class="pdparam">cs</var>;
ec_message * <var class="pdparam">m</var>;
char * <var class="pdparam">buff</var>;
int <var class="pdparam">len</var>;
Description
This hook is called when the system needs to determine what domain to send a message to. It provides a way to set the gateway configuration directive at the per-message level.
This hook is called to determine which domain's queue messages should be placed in. The default queue is based on the result of
config_get_binding_domain_gateway, but the queue can be overridden by registering a custom function at this hook.
buff is supplied by the caller and is at least
len bytes long.
buff will be populated with the full gateway domain.
- closure
A pointer to the closure function.
- cs
For a description of this data type see generic_module_infrastructure.
- buff
The buffer for holding the routing domain.
- len
The length of the buffer.
This hook returns zero or
1. If non-zero, no further hook providers are called.
This hook will be called in any thread. | https://support.sparkpost.com/momentum/3/3-api/hooks-core-config-get-message-routing-domain | CC-MAIN-2022-21 | refinedweb | 200 | 58.48 |
How to replace all those special characters with white spaces in python ?
I have a list of names of a company . . .
Ex:-[myfiles.txt]
MY company.INC
Old Wine pvt
master-minds ltd
"apex-labs ltd"
"India-New corp"
Indo-American pvt/ltd
Here, as per the above example . . . I need all the special characters[-,",/,.] in the file
myfiles.txt must be replaced with a single white space and saved into another text file
myfiles1.txt.
Can anyone please help me out?
Assuming you mean to change everything non-alphanumeric, you can do this on the command line:
cat foo.txt | sed "s/[^A-Za-z0-99]/ /g" > bar.txt
Or in Python with the
re module:
import re original_string = open('foo.txt').read() new_string = re.sub('[^a-zA-Z0-9\n\.]', ' ', original_string) open('bar.txt', 'w').write(new_string)
import string specials = '-"/.' #etc trans = string.maketrans(specials, ' '*len(specials)) #for line in file cleanline = line.translate(trans)
e.g.
>>>>> line.translate(trans) 'Indo American pvt ltd'
import re strs = "how much for the maple syrup? $20.99? That's ricidulous!!!" strs = re.sub(r'[?|$|.|!]',r'',strs) #for remove particular special char strs = re.sub(r'[^a-zA-Z0-9 ]',r'',strs) #for remove all characters strs=''.join(c if c not in map(str,range(0,10)) else '' for c in strs) #for remove numbers strs = re.sub(' ',' ',strs) #for remove extra spaces print(strs) Ans: how much for the maple syrup Thats ricidulous
At first i thought to provide a string.maketrans/translate example, but maybe you are using some utf-8 encoded strings and the ord() sorted translate-table will blow in your face, so i thought about another solution:
conversion = '-"/.' text = f.read() newtext = '' for c in text: newtext += ' ' if c in conversion else c
It's not the fastest way, but easy to grasp and modify.
So if your text is non-ascii you could decode
conversion and the text-strings to unicode and afterwards reencode in whichever encoding you want to.
While maketrans is the fastes way to do it, I never remerber the syntax. Since speed is rarely an issue and I know regular expression, I would tend to do this:
>>>>> import re >>> re.sub(r'[^a-zA-Z0-9]', ' ',line) ' myfiles txt MY company INC'
This has the additional benefit of declaring the character you accept instead of the one you reject, which feels easier in this case.
Of couse if you are using non ASCII caracters you'll have to go back to removing the characters you reject. If there are just punctuations sign, you can do:
>>> import string >>> chars = re.escape(string.punctuation) >>> re.sub(r'['+chars+']', ' ',line) ' myfiles txt MY company INC'
But you'll notice | http://www.dlxedu.com/askdetail/3/0346fc45362adb9adfcbd5fad776ad1c.html | CC-MAIN-2018-39 | refinedweb | 456 | 66.84 |
Build awesome Games!.
Treating burns, and helping young children get through the burn treatments is an art, why? Quite simply it is because of the inability of young children to handle painkillers during the stretching of their skin while being treated. See: Snowy game, VR goggles take burn victims' minds off of pain, this is the type of game that you could easily build using the C# Express and XNA Game Studio, unfortunately, WII and Playstation would force you to pay $10,000 for their development tools, and then pay for access to the console.
Bottom line: Be safe, have fun, celebrate Independence! no matter where you are.
No difference in how to use Fonts in XNA 3.1 over XNA 2.0. If you already know how to use text in your project, this won’t be a big help to you. This article was written to try to look a little smarter than my previous blog may have made me look.
Using the previous Blog approach, was simple, but not elegant.
It would be better to add text that indicates whether or not SpriteBatch is an abstract class or a base class.
In this case you will need to add an existing content resource to the project. The image below shows you how to add the spritefont material to the content folder. There is a link that gets you to a very clear way to implement text in your game project. Over future blogs we will go over how to add text, scoring and so forth to your game.
Follow the article on MSDN:
Use the diagram to the right to add the existing content templates, in this case Sprite Font.
public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch;
//Add the two lines below
SpriteFont Font1; Vector2 FontPos;
//******************
Your code should look like:.
if (x.IsPublic) GraphicsDevice.Clear(Color.Red); else GraphicsDevice.Clear(Color.Black);.
The defense attorneys and the prosecutors both made a statement that Halo 3 addiction was the basis for the murder, the problem is that Halo 3 was released in May 15, 2007, the murder occurred in Oct., 2007. This seems a little quick for addiction to reach this level. My initial comment was: "Get out of here..."
Take a look at the article “So-Called ‘Halo killer’ gets 23 to life”, the article states that:
.
The judge even went on to state:
"I feel confident that if there were no such thing as violent video games, I wouldn't know Daniel Petric.”
"I feel confident that if there were no such thing as violent video games, I wouldn't know Daniel Petric.”
For a judge to make this kind of statement is telling and an example of the judge using the "bench" as a bully pulpit, and it would not allowed in the court. If you offered this type of judgement in the court, you might get questions like:
If Daniel Petric hadn’t played Halo 3 for 18 hours a day, he could have done the same thing with pornography, watching Taxi too many time (President Reagan’s shooter did), stalking a women, watching Law & Order then pretending they understand the law, and so forth.
To say that Halo 3 was the cause of the addiction, frankly really puts a little to much on Halo 3. I don’t find it addictive at all, in fact, I have had to learn to play it to do demos and found that it was fun, then lost interest quickly after completing the self play successfully. I did keep it online and really enjoyed designing using the forge.
Addictive personalities are a problem in many areas of life, but in game design we do want to make the games fun and immersive, that is the goal. It is natural that addictive personalities will be attracted to playing games, gambling, etc. The rest of us have fun and move on. Sometimes addictive personalities lead society to better things, no clear examples, on the other hand, if they are failures, we look at them as losers who need a shower, and dental work.
In reading the ““So-Called ‘Halo killer’ gets 23 to life” I see this case as having some other elements, for instance, did Daniel Petric go through a process that altered his brain due to the use of painkillers during his recovery from an accident (in a separate article). Maybe the painkillers mixed with the infinite game play Daniel Petric was doing caused the addiction. Maybe his injury could have scrambled his brain.
However, that isn't something that I can judge as I am not a neuroscientist, I don’t have a degree in Psychology, so according to the way courts work, I couldn’t have an opinion. But the judge did.
I wonder if the judge did any research on game addiction. I turned to the MS Library, the same digital library that colleges and universities would make available to their students, and I took a look to see if I can find any articles that might have researched the nature of addiction to games.
From the article:
A bibliometric analysis of the scientific literature on Internet, video games, and cell phone addiction
Video Game Addiction in Children and Teenagers in Taiwan
This article is available for free inside of the Microsoft library, so you might be able to get it for free:
The object of the paper:
Conclusion:
People get addicted to a range of things that most people may find:
Bottom line to me, and I am not a lawyer, so it is my opinion:
(Note: I made changes after the initial publication because I rechecked my facts, initially I had thought the murder took place in 2004 instead of 2007. Something one can do on one owns blog. If you see any "facts" that I have cited incorrectly let me know with comments, I think the reference to Taxi is correct.)
Here are some helpful links for your development as a developer and software architect
A good blog that is written for educational purposes, but is a good example of a blog that a lot more technologists should emulate is Tamer Maher, a hard working Egyptian guy, see his blog at:
Now for the links of links, Ta-Da, and yes I used Bing to find these wonderful links!
First off tip of the hat to Tamer Maher:
Cy Khormaee and Bradley Jensen who will be joining their student teams to attend the Imagine Cup in Cairo, Egypt! They will be joining my other teammates: Dan Waters, Clint Rutkas, and Diane Curtis.
Oops:
In the previous blog I said that we would go over how to use abstract classes. I decided to discuss object instantiation from classes
Now back to something that is entirely on track to using existing code and building code that you can share with others.
A few important points:
Objects can be created using the new keyword followed by the name of the class that the object will be based upon.
In C# you create the object from the class pattern by the code, written here where the object is given the same name as the class, in the following line of code, I show you the way that is more professional and easier to utilize:
Avatar Avatar = new Avatar(); //Can be confusing, but used in many examples
A better way to instantiate an object would be to give the instantiated object a separate but clear name:
Avatar BaldGuy = new Avatar(); //Less confusing and more descriptive
When an instance of a class is created (instantiate), a reference to the object is passed back to the programmer (the yellow arrow in the figure). In the example above, BaldGuy is a reference to an object based on Avatar. This reference refers to the new object, but does not contain the object data itself. In fact, you can create an object reference without creating an object at all:
Avatar BaldGuyA;
Creating object references that do not reference an object is a bad idea because it will fail at run time which occurs after you compile the program. This is an error that will not show up until you try to use your program.
However, such a reference can be made to refer to an object, either by creating a new object, or by assigning it to an existing object, like this:
Avatar BaldGuyB = new Avatar();
Avatar BaldGuyC = BaldGuyB;
We aren’t quite at the point where we can use DLLs, but we need to take a look at the concept of the abstract class and how to derive or construct the abstract class, you can derive or construct a “concrete” class as well, but that is usually well defined.
An abstract class is a class that has to be derived or constructed by another class, it can’t instantiated by itself like a concrete class is able to. This shows the C# approach, apologies to the Visual Basic reader. Please feel free to add a comment with the VB approach.
Next blog, we will go over how to implement the abstract class, use it in the Derived Class.
If you want to get a head start, go to: How to: Define Abstract Properties. Make sure to check the comments at the end of the article, there is a documentation bug and the comment fixes it. The article assumes you know how to use the Visual Studio command line to compile. Command line compiles are very useful, but can be tricky, I will cover this later.
You will see where this is going from the point of view of games, in fact this is very important stuff. For XNA, F# and Silverlight games.
Heading to UCI for Senior Project Day! June 10, 2009
Oh yeah, make sure to try Bing!
OMG: I appeared to have made a commitment to show how to build a dll in a previous blog and Angelina Jolie tells her story about DLLs
I am sorry, I made the statement:
Back to DLLs, a way to store your programming stuff. In one of the previous blogs, I talked about DLLs. Let’s examine how the DLL is referenced in the Visual Studio environment. To set a reference, in any of the Visual Studio tools you would use the reference and then right click it to add the DLL assembly reference to you IDE. To add the reference to a DLL, you would right click on the reference for the project (you can have more than one project in a solution), select “Add Reference”, another dialog box opens. One of the tabs you would select from the .NET tab, in the case of XNA, you might pick Microsoft.Xna.Framework.Pipeline, which isn’t selected by default when you start with building a new XNA project. The following are brief explanations of the tabs:
Lists all .NET Framework components available for referencing.
Component
Description
Component Name
Either the full or "friendly" name of the component.
Version
The version number of the component.
Runtime
The version number of the .NET Framework that the component was created with.
Path
The folder path and filename of the component.
Lists all COM components available for referencing. COM is a type of class library that has some added features and legacy features. COM is only used in Windows and not Windows Mobile or Windows CE.
Lists Visual Studio projects in the current solution available for referencing. Select assemblies from this tab to create project-to-project references. This tab is used if you wish to reference another project either that are in the IDE or in the Projects Folder, you have to navigate the folder to find the DLL
Project Name
Displays the names of referenced projects.
Project Directory
Displays the folder path for referenced projects.
Allows you browse additional files to find a component not listed in the current tab and add it to the list.
Displays recently added references.
Next blog will discuss how to use these references in your code.
I.
Now that is a great title: Some more stuff. Well that is what the blog is about: Stuff.
Game stuff, to build a game, it is a good idea to understand the concept of DLL and classes. DLL stands for Dynamic Linking Libraries, which is a library that contains classes that you can reuse. DLLs are an important concept in object oriented programming, yet when I talk to students, there is often confusion about DLLs. In this blog, we will create a simple DLL that works in both Windows 7, Vista and the like, as well as on a Microsoft mobile device. What this blog entry won’t do is show the concept of interfaces, for that watch for a later blog in my random universe. More on Interfaces can be found at Interfaces (C# Programming Guide) and MSDN Webcast: Architecting .NET Solutions with VB.NET
Think about DLLs as a storage place for your classes. Other programs can call your DLL if you set up your DLL to be able to work with other programs. This is the case for the many Windows DLL and for the system DLL. You reference these programs in your program by setting references in the project IDE, there are other ways you can reference them as well.
In the past, DLL suffered from a problem when the contract was broken by another program. In .NET this was overcome by the use of assemblies.
Why use DLLs? In a game, whether you are running it on the XBox, Windows or a Mobile device, you can modularize your program. For example you could use a DLL to provide a physics solution for an XBox game, then you could reuse it with a Silverlight based game, and you might reuse in a game that works on a Mobile device, although it will have to allow for certain constraints with the Compact Framework.
The concept of DLLs is used both in Windows programming as well as Linux, see Anatomy of Linux dynamic libraries. In the next posting I will work through a simple creation of a DLL and then use of the same DLL in several different types of projects.
It’s spinning triangle time! In case the video on this page is too small, you can download the video from my codeplex site:, the codesnippets are located at this site as well. In the video, I cover the following:
I have decided to spend some time on programming games on the Windows Mobile, just for the heck of it. I will use the cool codeplex site to store the builds and releases.
Check.
Star Trek has long been the focus for games, and now with the new movie: “Star Trek: Love Boat”, there will be a lot of excitement again about Star Trek. In previous posts I stated that we would examine the XNA Racing Game. Then I went down the road with Bar Stool Racers. You might well be asking yourself: So just how in the heck is Sam going to make that CONNECTION? Well I had to contact Captain Randomness for assistance. He couldn’t come by my house because the Post Office decided to CHANGE my street name, true story, and it wouldn’t come up in Google Maps. Later when he realized that Live Maps were better, he will be by later.
Now how did this blog get the Racing Game, Bar Stool Racers and the Star Trek movie (which isn’t really about the conversion of the Enterprise into a Love Boat).
I could be accused of being random. It seems pretty easy to me that we could make those connections. When you watch the trailers for the real Star Trek movie there is a motorcycle racing across some planet and then a Corvette, so it looks like a racing game is appropriate. Then another trailer has asteroid like action, which we will go into depth about how to create a asteroid game. Looks like we got two levels to me.
But let’s keep on with the “Star Trek: Love Boat” theme for now.
Game Story: Single level, the crew of the Love Boat, Enterprise are suddenly trapped in a world by “Q” that requires that the guests must race bar stool carts to save one of the crewmembers from being forced to listen to Hubert Horatio Humphrey speeches for eternity, good politician, boring speaker.
Now on to the physics of ground vehicles, like cars or bar stool racers (which would parallel motorcycles). From the diagram that I showed in a previous post, the Bar Stool Racer has an important spring component: The human in a sitting position acts like a spring. The bar stool cart will fall over if the center of gravity moves to a certain point off the upright axis. Strangely the spring constant is important for the feel of the game, and it is a simple physics principle with easy to write equation.
The equations of a spring is:
With the respect to the car physics, the spring constant is 1.0, if you were developing simulations for a car manufacturer or test facility, you would have to do tests to determine what this constant for the automobile classes that you are testing. Here is a code sample from the Car Racing Game:
public void Simulate(float timeChange) { // Calculate force again force += -pos * springConstant; // Calculate velocity velocity = force / mass; // And apply it to the current position pos += timeChange * velocity; // Apply friction force *= 1.0f - (timeChange * friction); }
In the next post I will show you how to use the class diagrams to examine your code.
Cool, Alien Game. Designed for Zune, has music. Sweet. Check it out, download, show your friends.
Also, did you download the Racing game yet? Make it happen. Physics discussion coming up, reading the code. So play with the racing game.
Yep, not writing code, reading code. We all need to do more code reading. There I said it.
Ok, the Motorized (or Motorised for the English speaking) barstool is interesting because it is much like a go-cart which has a center of gravity as low as possible, except that the driver is riding quite a bit above the ground. With the driver and their center of gravity acting like a pendulum creates an interesting equation of motions.
Now if we assume that the barstool is basically is an object that has a rider whose weight raises the center of gravity, and it acts like a weight on a stiff spring, we get the “humor” of watching a person who would be reckless enough to ride one of these vehicles. Don’t try riding one of these on your own, but let’s stick with the design considerations of the physics of this vehicle. Below I have drawn a diagram for one of the vehicles. In study of statics the sum of forces should equal zero, in the study of dynamics the sum of forces can be non-zero. For a game, the humor of the game is when the vehicle enters into a turn and overcomes the forces of friction of the wheels and the center of gravity no longer is directly over the centroid of the wheels (my definition of a centroid is the drawing of all the point forces that then yields a center point).
In the next entry I will go over the “static” or non-moving diagram of forces.
Schools in the Southern California region that have been invited to the Imagine Cup National Event in Boston are Cal State University, Los Angeles and Chapman University, so hopefully the teams will agree to attend. All reasonable expenses are paid for the students. | http://blogs.msdn.com/devschool/ | crawl-002 | refinedweb | 3,301 | 67.89 |
Justin Erenkrantz wrote:
>During some testing with flood (~30 threads), we ran into a stack
>corruption error in our code. We tracked it down to the fact that we
>were using a non-reentrant version of gethostbyname. This patch lets
>us call the reentrant version of gethostbyname and now we haven't
>been able to recreate the segfault.
>
>The only possible optimization would be the size of the temporary
>buffer (currently 256). Roy mentioned that the address array in
>hostent has a maximum of 10 entries. If so, the size of the
>structure plus the maximum size of the array (10 entries) may be
>sufficient. If we send in a too small buffer, we should
>receive ERANGE.
>
Is there a reason why we shouldn't just use the re-entrant versions
where it is available?
also you can't use APR_HAS_THREADS to check,
as someone could have threads turned on in BSD, which
doesnt have a gethostbyname_r function
(at least acording to cvs.apache.org's man pages)
..Ian
>
>
>Any reason we shouldn't commit? -- justin
>
>Index: network_io/unix/sa_common.c
>===================================================================
>RCS file: /home/cvs/apr/network_io/unix/sa_common.c,v
>retrieving revision 1.34
>diff -u -r1.34 sa_common.c
>--- network_io/unix/sa_common.c 2001/05/02 02:54:11 1.34
>+++ network_io/unix/sa_common.c 2001/07/20 02:29:30
>@@ -380,6 +380,11 @@
> struct hostent *hp;
> apr_sockaddr_t *cursa;
> int curaddr;
>+#if APR_HAS_THREADS
>+ char tmp[256];
>+ int hosterror;
>+ struct hostent hs;
>+#endif
>
> if (family == APR_UNSPEC) {
> family = APR_INET; /* we don't support IPv6 here */
>@@ -395,11 +400,17 @@
> }
> else {
> #endif
>+#if APR_HAS_THREADS
>+ hp = gethostbyname_r(hostname, &hs, tmp, 255, &hosterror);
>+#else
> hp = gethostbyname(hostname);
>+#endif
>
> if (!hp) {
> #ifdef WIN32
> apr_get_netos_error();
>+#elif APR_HAS_THREADS
>+ return (hosterror + APR_OS_START_SYSERR);
> #else
> return (h_errno + APR_OS_START_SYSERR);
> #endif
> | http://mail-archives.apache.org/mod_mbox/apr-dev/200107.mbox/%3C3B579D80.90101@cnet.com%3E | CC-MAIN-2016-40 | refinedweb | 291 | 66.03 |
TypeScript is wonderful. Been using it more and more and I love it. 🥰
There’s something magical about useful autocomplete suggestions, object blobs with property hints, and auto imports. That’s right, auto imports.
Press enter and VSCode adds
import { FieldTypes } from './types' at the top.
And check this out: I got a form builder that takes JavaScript blobs as configuration. VSCode is smart enough to tell me when they’re wrong. 👌
This works:
Got a field with a
name and a
placeholder. Remove one and o-oh.
The error is cryptic type vomit. You get used to that. Means that one of your blobs doesn’t match any known field type.
But get this, add
type: "email" and no need for a placeholder 😮
Whoa
So what’s going on here? What’s TypeScript doing to support this? And why do we need a
type property if we’re using a typed language?
Static analysis
Static analysis is where TypeScript shines. Its main design goal 👉 enable static analysis of JavaScript
Static program analysis is the analysis of computer software that is performed without actually executing programs, in contrast with dynamic analysis, which is analysis performed on programs while they are executing.
Static analysis uses static types to understand your code. Editors use this understanding to help you write better code.
Everything from autocompletion, hints on object properties, and squiggly lines when you get something wrong. Some editors even integrate with documentation and give you help right in the editor.
TypeScript with VSCode brings all that to JavaScript.
You get a better coding experience most of the time. Sometimes you fight the type system, but it’s got your back … mostly. Great for large teams and large codebases.
Know your code has at least a remote chance of being correct without running every single line? Love it ❤️
Dynamic analysis
In contrast to static analysis you have dynamic analysis. That’s JavaScript’s normal mode.
Dynamic program analysis is the analysis of computer software that is performed by executing programs on a real or virtual processor. For dynamic program analysis to be effective, the target program must be executed with sufficient test inputs to produce interesting behavior.
To analyze a dynamic language, you gotta run it. That’s where test driven development comes in.
You don’t have a static type system saving your butt for some classes of errors. You gotta run the thing and see if it works. And you better make sure you run every line of code.
If you don’t, I promise your users will 😉
Duck typing
Duck typing is a strange beast most popular in the land of Lisp. It falls under dynamic typing, but statically typed duck languages exist also. Wikipedia classifies it as the 4th major category next to static, dynamic, and nominal typing.
If it walks like a duck and it quacks like a duck, then it must be a duck
The duck test 🦆
You’re duck typing every time you write code like
if (object.property && object.property.value === 'something')
Verify the object is a duck, has a
property, then use it like a duck.
Type guards in TypeScript
That brings us to TypeScript’s biggest flaw.
From TypeScript Design Goals
Impose no runtime overhead on emitted programs.
Emit clean, idiomatic, recognizable JavaScript code.
TypeScript is a static analysis tool only. No types at runtime. No type checking. No validations. Nothing.
Great for program size and understandability. Not great for useful type system.
Say you’ve got a form builder with two field types like I mentioned before.
A union
FieldTypes type saves typing in a bunch of places.
Then we got a
CoreFieldProps interface that defines properties all fields share. Every field needs a
name, optionally an
initialValue too.
Specific field types extend the core props and add their own. Most importantly they add the
type field.
That’s how TypeScript knows what you mean when you write
Looks at the first two blobs, sees they match
TextFieldProps. They’ve got a name and a placeholder, no type.
The last blob uses
type: "email" so TypeScript knows it’s okay that there’s no placeholder. Optional in emails.
Duck typing at runtime
Static analysis worked great in the editor. What about when you want to render different fields based on their type?
You’re using a typed language right, how hard can it be.
Not so fast buster.
JavaScript has no idea about your types.
typeof props evaluates to
object. That’s not gonna match your artisanally crafted types you worked so hard to build 😉
Instead, you’ll have to use TypeScript Type Guards
Two types of guards prove useful in the wild:
- Duck typing
- Explicit
typeproperty
Duck typing
A duck typed type guard uses the duck test. If property exists on object, do the things.
An animal is a duck if it can both swim and fly. The
in operator checks for the existence of a key (or property) on an object.
Explicit type property
The other approach works best in an object blob situation. You provide a
type attribute, define types with hardcoded values, then make sure they’re defined.
Use those values at runtime to decide what to do
An object constructor can help too.
new EmailFieldProps() and it sets
this.type to email by default.
But I prefer blobs for passing data and use duck typing when dealing with actual objects. If it can do what I need, what do I care what type it is?
Quack
And that’s how you can use ducks to solve TypeScript’s biggest flaw – lack of type support at runtime.
Hope this was useful. | https://swizec.com/blog/typescripts-biggest-flaw-and-how-you-can-use-ducks-to-fix-it/swizec/9122 | CC-MAIN-2019-47 | refinedweb | 944 | 68.06 |
Function name as parameter?Works great, but so I can understand it, what do the * and & symbols mean in C++?
Function name as parameter?I want to do something like this, but I don't know how:
[code]// +-------------------------------...
Problem with Multiple "mains"This will work:
[code]#include <iostream>
using namespace std;
void secondmain();
void third...
What is a yellow blinker along the mouse pointerPerhaps you have the INSERT key on your keyboard toggled to ON? Try hitting the INSERT key and see i...
Using '\'Thanks, works perfectly. =]
Also, in VC++ 2008, isn't it \a for a beep? \b does nothing. :P
This user does not accept Private Messages | http://www.cplusplus.com/user/CheesyBeefy/ | CC-MAIN-2016-30 | refinedweb | 109 | 78.85 |
I have several scripts that work well for a specific coding scheme but are difficult to adapt for new schemes. The code names (i.e., positive affect, negative affect) are currently written in to the code body. I would like instead to be able to set the code names as a parameter at the beginning of the script; this way, it would be easier to adapt scripts when code names change. I am having trouble finding a method for calling code names. Any suggestions?
This is an example of one of the scripts I am trying to edit:
data_folder = '~/Merged Files'
output_file = '~/Outputs/CheckRel.csv'
id_column_name = 'ID'
episode_column_name = 'Episode'
behavior_column_name = 'Rel_Affect'
missing_value = ''
def getDatavyuFiles(path, recurse=false)
path = File.expand_path(path)
filter = (recurse)? '/.opf' : '.opf'
return Dir.chdir(path){ |dir| Dir.glob(filter) }
end
require 'Datavyu_API.rb'
begin
# Initialize array for our data
data = Hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) }
maxEpisodeLen = 0 # maximum number of behavior cells in an episode
# Get datavyu files
data_folder = File.expand_path(data_folder)
files = getDatavyuFiles(data_folder)
# Iterate over files
files.each do |file|
# Load the file
$db,$proj = loadDB(File.join(data_folder, file))
puts "Loaded file #{file}"
# Load columns from spreadsheet
colID = getVariable(id_column_name)
colEpisode = getVariable(episode_column_name)
colBehavior = getVariable(behavior_column_name)
# Iterate over ID cells
colID.cells.each do |idcell|
# Get ID codes
id_codes = [idcell.idnum]
temp = [] # store data for rest of this row
# Iterate over nested episode cells
colEpisode.cells.select{ |epcell| idcell.contains(epcell) }.each do |epcell|
# Initialize arrays for storing data for behavior cells in this episode
onsets = []
offsets = []
pos = []
neg = []
# Iterate over nested behavior cells
colBehavior.cells.select{ |bxcell| epcell.contains(bxcell) }.each do |bxcell|
onsets << bxcell.onset/1000.0
offsets << bxcell.offset/1000.0
pos << bxcell.positive
neg << bxcell.negative
end
# Store to hash
data[file][epcell.ordinal] = {
:onsets => onsets,
:offsets => offsets,
:pos => pos,
:neg => neg
}
maxEpisodeLen = [maxEpisodeLen, onsets.size].max
end
# Store to hash
data[file][:id] = id_codes
end
end
# Process the dataset to pad to maximum episode length
rows = []
data.each_pair do |key, val|
eps = val.reject{ |x, y| x == :id}
eps.each_pair do |jnk, ep|
ep.each_pair do |k,v|
if v.size < maxEpisodeLen
ep[k] += [missing_value] * (maxEpisodeLen-v.size)
end
end
end
rows << val[:id] + eps.values.map{ |x| x[:onsets] + x[:offsets] + x[:pos] + x[:neg] }.flatten
end
# Create header (assume 3 episodes)
header = ['ID']
for i in 1..3
for col in ['Ons', 'Off', 'Pos', 'Neg']
for j in 1..maxEpisodeLen
header << "E#{i}#{col}#{j}"
end
end
end
# Open output file
outfile = File.open(File.expand_path(output_file), 'w+')
outfile.puts header.join(',')
# Iterate over rows of data in cache and print to output file
rows.each{ |row| outfile.puts(row.join(',')) }
outfile.close
rescue StandardError => e
puts e.message
puts e.backtrace
end
asked
18 Jan '18, 16:52
Penina Backer
46●4●4●9
accept rate:
0%
I think for this specific script the easiest way to change it is to create variables at the top of the script (i.e., the parameter section) for each of the two codes. For example:
first_code_name = 'positive'
second_code_name = 'negative'
Then you would want to update the lines in the body section where the values are fetched from the cell:
pos << bxcell.positive
neg << bxcell.negative
to this instead:
pos << bxcell.get_code(first_code_name)
neg << bxcell.get_code(second_code_name)
answered
22 Jan '18, 09:
codenames ×1
question asked: 18 Jan '18, 16:52
question was seen: 1,365 times
last updated: 22 Jan '18, 09:58
First time here? Check out the FAQ! | http://datavyu.org/support/questions/1152/set-code-names-within-a-script?sort=oldest | CC-MAIN-2019-39 | refinedweb | 587 | 53.58 |
> ASYNC13.rar > WAITQUIE.C
/* A module of ASYNCx.LIB version 1.10 */ #include
#include "asyncdef.h" /* ** Wait for between t and t+1 18ths of a second to elapse without any ** characters arriving at port p. If max 18ths of a second elapse before ** a gap in the incomming data of t 18ths of a second has been found, a ** value of -1 is returned. If the gap is found within max 18ths of a ** second, a value of 0 is returned. If mode is set to 0, any characters ** that do arrive during the execution of this routine are discarded and ** the input buffer for the port p is empty when this routine returns. ** If mode is set to 1, characters arriving at the port are detected but ** not discarded. Be careful of buffer overflow if use mode 1. If the ** input buffer overflows, the least recent data will be lost and the ** newest data will be retained. */ int a_waitquiet(ASYNC *p,int t,int max,int mode) {unsigned long t0,t1,far *t2; int count0; if (!p) return -1; /* ** *t2 is the current time and is incrimented by the operating system ** 18.21 times per second. */ t2=(unsigned long far *)MK_FP(0x40,0x6c); /* ** t0 is the initial time. t1 is the time at which the last character ** was received. (Assume that a character was just received.) */ t0=t1=*t2; if (mode==0) while ((*t2)-t1<=(unsigned long)t && (*t2)-t0<=(unsigned long)max) {if (a_getc(p)!=-1) /* If another character has been received, */ t1=*t2; /* update t1. */ } else {count0=a_icount(p); /* count0 = # of chars in buffer */ while((*t2)-t1<=(unsigned long)t && (*t2)-t0<=(unsigned long)max) if (a_icount(p)!=count0) /* If more characters are received */ {t1=*t2; /* update t1 and */ count0=a_icount(p); /* the character counter. */ } } if ((*t2)-t1>=(unsigned long)t) return 0; else return -1; } /* end of int a_waitquiet(p,t,max,mode) */ | http://read.pudn.com/downloads9/sourcecode/comm/fax/32646/ASYNC13/WAITQUIE.C__.htm | crawl-002 | refinedweb | 318 | 75.4 |
Different sources have different explanations, and quite confused and I even asked this question before, and somebody already answered it And I think I understand what fields and instance variables are. But according to the explanation the book provides, I just wanna confirm to see if I really understand what it means.
Doesn't it mean that when we first create the variable inside class, that's called field.
public class Gradebook { private string courseName;
but after the object has been created, it is also known as an instance variable?
Gradebook object = new Gradebook();
But when the books mentions that "Each object(instance) of the class has a separate instance of the variable." I am quite confused about it. Does it mean that the instance object has another instance(object) from the variable? What is the different between instance variable and the instance of the variable? Are they the same? I don't really get it.
The book is written by P.J Deitel and H.M Deitel named visual C# how to program 2008.
This post has been edited by kenryuakuma: 15 October 2009 - 08:04 PM | https://www.dreamincode.net/forums/topic/132316-instance-variable-and-instance-of-the-variable/ | CC-MAIN-2018-26 | refinedweb | 188 | 66.84 |
This article shows you a useful technique to cache some of that page
data on the browser in-memory. Since we use Ajax, the page is not reloaded each
time. This prevents the cache from being invalidated on each round-trip.
Client-side caching is sometimes required for performance reasons and also to take
the load off of the DBMS. Since most modern PCs have plenty of RAM to spare, client-side
caching becomes an important weapon in the modern programmer's arsenal of tricks.
With the advent of Ajax, application data can be maintained on the client without
the use of ViewStates (aka hidden fields) or to a lesser degree, cookies. As any experienced developer will tell
you, ViewState is a double-edged sword. Indiscriminate use of ViewStates can really
have a detrimental effect on performance - what with the Viewstate payload ferried
to and from the server with every postback.
This begs the question: Can we use this technique without Ajax? AFAIK, the answer
is: "No." That is so because we are maintaining the cache as a page-level variable
on the client. The moment the page is refreshed via a full-page postback, the cache is invalidated. Keep this in mind while designing your application.
The accompanying code can be extended to use record data too, via Javascript and
the presentation logic can also be hived off to a Javascript routine on the client.
We could even pipe XML down to the client and it could be parsed and presented through
client-side script.
To keep this sample
code easy to comprehend, I have rendered the tabular data from within the Web Service
itself - which may not be architecturally optimal. Since this is not a treatise
on design best-practices, I have taken the liberty of cutting corners here and there for the sake of brevity.
imgWe
use JavaScript associative arrays to maintain our client-side cache. One thing to
be noted about JS associative arrays is that once you associate a string key with
an array, there is no way to iterate through the array using indexes. Supposing
you are using it like this:asarray["akey"] = <value> there is no
way you can revert to accessing the elements by their ordinal position like this:
var anyvar = asarray[0].
asarray["akey"] = <value>
var anyvar = asarray[0]
Let us examine the critical sections of the code that are absolutely necessary for
client-side caching to work. The rest of the code deals with presentation and layout
and a discussion on these aspects will be skipped.
For those who subscribe to the view that source-code is the ultimate documentation,
you may skip this section. For the others, we'll try to separate the wheat from
the chaff. Let us look at the most important pieces of code that makes client-side caching with Ajax and
Javascript possible. I am using XML data for demonstration purposes and this makes the project run without
having to change connection strings or even having SQL Server installed on your computer.
Create a New Website and choose "ASP.NET AJAX-Enabled Website". If you do not have .NET 2.0 Ajax Toolkit
installed, go here and download them. You cannot begin this exercise without it.
[ScriptService]
using System.Web.Script.Services
IMPORTANT:
You must have installed Microsoft ASP.NET Ajax 1.0 and the Ajax Toolkit for this sample to work.
Add a reference to AjaxControlToolkit.dll (not included in the distribution) for the code sample to work
You will find it here.
using System.Web.Script.Services;
...
[ScriptService]
public class DataAccess : System.Web.Services.WebService
{ ...
Flesh out your web method to do something useful. Our example does this:
[WebMethod]
public string FetchOrders(string key)
{
return LoadData(key);;
}
private string LoadData(string key)
{
DataSet ds = new DataSet();
ds.ReadXml(this.Context.Server.MapPath("App_Data\\northwind.xml"));
ds.Tables["Orders"].DefaultView.RowFilter = "customerid = '" + key + "'";
return RenderResultTable((ds.Tables["Orders"].DefaultView));
}
private string RenderResultTable(DataView rdr)
{
StringBuilder str = new StringBuilder();
str.AppendLine("<table cellspacing=\"0\" cellborder=\"=0\"
cellpadding=\"5\">");
str.AppendLine("<tr><td><b>Order Date</b></td><td><b>Order ID</b>
</td></tr>");
foreach(DataRowView drv in rdr)
{
str.AppendLine("<tr>");
str.AppendFormat("<td>{0}</td> <td>{1}</td>", drv["OrderDate"],
drv["OrderID"]);
str.AppendLine("</tr>");
}
str.AppendLine("</table>");
return str.ToString();
}
Now, we go to the client script that does the actual caching and retrieves data by making a call
to the web service. This employs rudimentary JavaScript - no surprises here.
var cacheData = new Array(); // This is our cache
var currSel = null;
var seedData = "0BFA4D6B-DD18-48aa-A926-B9FD80BFA5B7";
// Prime a cache item with a unique initial value
Add the needed JavaScript code now. We have a HTML button with the ID btnFetch.
In the OnClick event, we trigger either an Ajax asynchronous call to the server or render
from the cache.
btnFetch
function btnFetch_onclick()
{
currSel = document.getElementById("dlCustomers").value;
var status = document.getElementById("divStatus");
//var svc = new DataAccess();
if(cacheData[currSel]==null)
{
DataAccess.FetchOrders(currSel,OnCompleteCallback,OnErrorCallback,
OnTimeOutCallback);
cacheData[currSel] = seedData;
status.innerHTML = "[Live Result]";
}
else
{
status.innerHTML = "[Cached Result]";
var cacheobject = FetchDataFromCache(currSel);
RenderData(cacheobject);
}
document.getElementById("dlCustomers").focus();
}
One
point to take careful note of is that if you are using multiple cache arrays in
your page, you will have to maintain multiple states for the item currently selected.
In that case, you might have additional state variables like currProductSel, currCustSel etc. Of course, you will have to have multiple
cache arrays as well
currProductSel, currCustSel
If employed correctly, client-side caching can be a great tool to enhance the user experience
and make the web application more responsive. If your application is so designed, you may also
consider prefetching data through Ajax calls and plonking them into the cache. Prefetching requires
minimal code overhead and can be an additional boost to performance if your application warrants it.
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
var a = ["foo","bar","baz"];
a['newkey'] = 'newval';
var s = "";
for (var index in a) s += index + " is " + a[index] + "\n";
alert(s);
// results in:
// 0 is foo
// 1 is bar
// 2 is baz
// newkey is newval
for (var key in thing) { do-something }
for (var i = 0; i < thing.length; i++) { do-something }
a[1] == a["1"] == "bar";
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/18269/Using-Associative-Arrays-for-Client-side-Caching-u?msg=1996531 | CC-MAIN-2016-22 | refinedweb | 1,113 | 56.35 |
Thread
2004.10.01 13:21 "Re: [Tiff] BigTIFF & PDF & tifftools", by Frank Warmerdam
>Rob wrote:
Discussion was about tifftools, and if/when they would grow 'big' too.
Would these tools become bigtiff specific or would they handle bigtiff and classic tiff transparantly?
Linking them with both lib's could introduce namespace conflicts I guess.
Having separate tools for classic and big would give double code bases for every tool implying a serious synchronisation effort.
Joris wrote:
As far as I know, having LibTiff handle the classic/big issue transparently, is not just possible, but is also the way Frank intends to enhance LibTiff. It will enable to stick with a single copy of the tools and tools code. Tools will not need to grow big, neither will apps, they'll support BigTIFF by default simply by using the newer LibTiff.
Folks,
First, it will be Andrey who does the BigTIFF upgrade. While I am very keen on it, I am not really prepared to put in the time to ensure it is done right.
And yes, our intent is that we would have a single library that supports both. There will certainly be some ABI changes to libtiff with the upgrade to BigTIFF support, and there will presumably be some extra options available to control whether BigTIFF or classic TIFF should be generated. So I don't think it will be completely a transparent upgrade for write purposes if you want to be able to produce BigTIFF.
But reading BigTIFF or classic TIFF files should be transparent to the application at the source level. And I hopefully TIFF reading applications that don't dig in too deep should not require any source changes either.
The ABI changes are likely to include stuff like toff_t and tsize_t becoming 64 bit types on platforms which support them.
As for Robs first question, I have no idea if PDF supports file sizes larger than 4GB or if that would be supported by tiff2pdf. I can't honestly imagine wanting to produce such a large PDF file for some years to come.
Best regards,
--
---------------------------------------+--------------------------------------
I set the clouds in motion - turn up | Frank Warmerdam, warmerdam@pobox.com
light and sound - activate the windows |
and watch the world go round - Rush | Geospatial Programmer for Rent | https://www.asmail.be/msg0055490954.html | CC-MAIN-2020-05 | refinedweb | 381 | 77.16 |
Casting numbers of different types when the result type could easily be inferred can be a pain. In this talk, Rich Fox trades a small amount of type-safety for a great amount of convenience. Using Swift 2.0’s protocol extensions, pattern matching, generics, and operator overloading, Rich simplifies number arithmetic between types.
Hi, I’m Richard Fox. I write in my blog, and am an iOS developer at Propeller Labs, a dev. shop that specializes in MVPs and mobile (if interested, we are currently looking for Swift enthusiasts to join us). My talk today is about exploring Cast-Free Arithmetic in Swift.
Arithmetic Comparison (01:06)
In Objective-C, we have syntax like this:
float w = 5; double x = 10; int y = 15; CGFloat z = w + x + y;
In Swift, this is the equivalent:
let w:Float = 5 let x:Double = 10 let y:Int = 15 let z:CGFloat = CGFloat(w) + CGFloat(x) + CGFloat(y)
Strong typing is great, sometimes it is scary. It should be more concise.
Pre-Swift 2.0 (01:31)
Even before Swift 2.0, I tried to solve this problem for my personal use by a simple extension in number type, and adding getters. This works OK, except if you have five getters for each number type, you are repeating code:
extension Double { var c:CGFloat { return CGFloat(self) } //. . . } extension Int { var c:CGFloat { return CGFloat(self) } //. . . } extension Float { var c:CGFloat { return CGFloat(self) } //. . . } //let y:CGFloat = 1 + x.c
With Swift 2.0’s protocol extensions inspired me to make one protocol for all compatible number types; I could use simple dot syntax to convert each type, powered by pattern matching.
How Number Casting Works (02:54)
Each number type is a struct. In the definition of each of the number types, there is the initializer for each type that can be cast from. In the standard library definition you will see these initializers.
Get more development news like this
init(_ v: Float ), init(_ v: Double) let x: Float = 5.0 let y = Float(x) OR let y = Float.init(x)
You can even do float.init and cast it. If you Command-click on any part of the code, you can see exactly where it is in the standard library.
To make this definition work for us, we define our protocol with the initializers that are required to do casting. We can extend our number types to the number of convertible protocol. Since all of the number types already implement all of these inits, it should work without us adding anything, except in the case of
CGFloat.
CGFloat is a little different from the rest: it is not defined in the standard library — it’s part of Core Graphics. Unlike numbers in the standard library, it doesn’t have init conversions. Luckily it is easy to create one by simply creating an extension. We can extend it and
self = value its own type.
protocol NumberConvertible { init (_ value: Int) init (_ value: Float) init (_ value: Double) init (_ value: CGFloat) } extension CGFloat : NumberConvertible {} extension Double : NumberConvertible {} extension Float : NumberConvertible {} extension Int : NumberConvertible {} extension CGFloat{ public init(_ value: CGFloat){ self = value } }
Pattern Matching (05:02)
switch self { case let x as CGFloat: print("x is a CGFloat") case let x as Float: print("x is a CGFloat") case let x as Int: print("x is a CGFloat") case let x as Double: print("x is a CGFloat") default: print("x is unknown..") }
We use this pattern matching in our protocol to figure out what type self is. We need to know what type self is so that we can plug it into one of those initializers that we defined in the protocol. Casting to a type like so sometimes leaks memory but that is now fixed in Swift 2.1.
Creating the Extension (05:56)
extension NumberConvertible { private func convert<T: NumberConvertible>() -> T { switch self { case let x as CGFloat: return T(x) //T.init(x) case let x as Float: return T(x) case let x as Double: return T(x) case let x as Int: return T(x) default: assert(false, "NumberConvertible convert cast failed!") return T(0) } } public var c:CGFloat{ return convert() } //... }
Inside the extension, we will define the private function
convert(). Convert will return a generic type. We plug in the piece that finds out what type self is, and go through all of the compatible number types that have initializers. Once we determine which kind it is, we can call that initializer
T.init(x) since T conforms to
NumberConvertible. Now we can cast using our dot property getter syntax here. We can just add it in one place, in the extension here, along with all the other dot property getters.
Converting Without Casting (07:29)
We can now cast without declaring a type. If convert is not private we can take two number types, do
.convert(), and set it equal to Y, and it will figure out what type it is, without us telling what it should cast to.
let w: Double = 4.4 let x: Int = 5 let y: Float = w.convert() + x.convert()
But we can make it easier. This below is probably the simplest case. We have two different types that returned a third different type.
let x: Int = 5 let y: CGFloat = 10 let z: Double = x + y
We use operator overloading. We will overload our operator using three generics that conform to
NumberConvertible. We will take the
lhs and the
rhs of that operator, and use the
convert() on both of them so they are the same type. We will use the standard library definition (because they are the same type we can do that now), and solve the operation. We will use
convert() one more time to cast back to the generic return type. This is the solution:
func + <T:NumberConvertible, U:NumberConvertible, V:NumberConvertible>(lhs: T, rhs: U) -> V { let v: Double = lhs.convert() let w: Double = rhs.convert() return (v + w).convert() }
We have an operator for addition, and that solves the first case. Let’s now add a second operator and a third number. We have four types in total. However, it does not work as expected below.
func + <T:NumberConvertible, U:NumberConvertible, V:NumberConvertible>(lhs: T, rhs: U) -> V { let v: Double = lhs.convert() let w: Double = rhs.convert() return (v + w).convert() }
Which Operator Definition is the Compiler Using? (09:44)
The first operator seems to be using our custom operator, and the second is using the standard library definition of the operator. Since the return type of our custom operator is a generic type, the first operator has to have something to infer the third number’s type. Since the third number type is a float, when we do the second operation, we have a float and a float. For some reason the compiler is not smart enough to look at the return type, which is not a float…
Handling the Compiler (10:51)
The first thing I tried was compromising with the compiler.
public typealias PreferredType = Double public func + <T:NumberConvertible, U:NumberConvertible>(lhs: T, rhs: U) -> PreferredType { let v: PreferredType = lhs.convert() let w: PreferredType = rhs.convert() return v+w }
A single return type works, but it only returns a double. The compiler is happy, but that is not a great solution: you can only return one type.
We can give the compiler more options. We will take our definition, and duplicate it (try only using two generics where the
lhs and the
rhs are both the same type). Of course, we still have our inferred return type (our original definition).
Using both of these operators together, our scheme almost works. However, at some point the compiler is confused and does not know which one to use.
Now we remove that extra overload that we created. Adding a zero in there causes the compiler to stop complaining. It seemed to be an issue with having two operations together.
Optimizing the Operators (13:39)
extension NumberConvertible { private typealias CombineType = (Double,Double) -> Double private func operate<T:NumberConvertible,V:NumberConvertible>(b:T, @noescape combine:CombineType) -> V{ let x:Double = self.convert() let y:Double = b.convert() return combine(x,y).convert() } } public func + <T:NumberConvertible, U:NumberConvertible,V:NumberConvertible>(lhs: T, rhs: U) -> V { return lhs.operate(rhs, combine: + ) } public func - <T:NumberConvertible, U:NumberConvertible,V:NumberConvertible>(lhs: T, rhs: U) -> V { return lhs.operate(rhs, combine: - ) }
We can make it even nicer by doing even more extensions on protocols. I went back to number convertible. I threw in an extension for a function that takes in two doubles and returns a double. Then, I define this operate function that takes in a generic type. I also added a combine type alias
CombineType function, and returns another generic.
Inside the implementation, I convert self and the generic input into doubles, and then we can plug both of those into our combine function. With the result, we can convert it to the return type. Then, we can replace our previous implementation of the operator with one line: lhs.operate, rhs and a single, just one operator for the function. That is really nice to look at and easy to use in all of the other arithmetic operators.
“Expression Too Complex” (15:21)
The expression was too complex to be solved in a reasonable time. It suggests that we break up the expression in two distinct sub-expressions, or make multiple expressions (even more when I was using overloaded operators).
If you do get this error, maybe you can rage tweet Chis Lattner #ExpressionTooComplex. That might help if you find a case where you think it actually does not really seem that complex. You can file radar, but there is not much else you can do.
Conclusion (16:47)
In conclusion, we can get castless arithmetic working with some constraints. We have mild inference confusion that we can just add plus zero to fix. We do also have the potential for complex expression errors. Our original implementation, which was .property conversions, is not too bad. I use that method myself, even in production, as it doesn’t take too much away from type safety.
All of the code for cast-free arithmetic is available here.
Q&A (17:51)
Q: Swift has the ampersand operator to indicate performing arithmetic explicitly with the potential for overflow. Since with this approach we potentially throw data away, should we use another operator to be explicit about it?
Rich: I like that idea. I mostly did this for fun and exploration, but for readability purposes this could be a viable decision.
About the content
This content has been published here with the express permission of the author. | https://academy.realm.io/posts/richard-fox-casting-swift-2/ | CC-MAIN-2018-47 | refinedweb | 1,803 | 65.62 |
Lines and Stroke Caps
- PDF for offline use
-
- Sample Code:
-
- Related APIs:
-
Let us know how you feel about this
Translation Quality
0/250
last updated: 2017-03
Learn how to use SkiaSharp to draw lines with different stroke caps
In SkiaSharp, rendering a single line is very different from rendering a series of connected straight lines. Even when drawing single lines, however, it's often necessary to give the lines a particular stroke width, and the wider the line, the more important becomes the appearance of the end of the lines, called the stroke cap:
For drawing single lines,
SKCanvas defines a simple
DrawLine method whose arguments indicate the starting and ending coordinates of the line with an
SKPaint object:
canvas.DrawLine (x0, y0, x1, y1, paint);
By default, the
StrokeWidth property of a newly instantiated
SKPaint object is 0, which has the same effect as a value of 1 in rendering a line of one pixel in thickness. This appears very thin on high resolution devices such as phones, so you'll probably want to set the
StrokeWidth to a larger value. But once you start drawing lines of a sizable thickness, that raises another issue: How should the starts and ends of these thick lines be rendered?
The appearance of the starts and ends of lines is called a line cap or, in Skia, a stroke cap. The word "cap" in this context refers to a kind of hat — something that sits on the end of the line. You set the
StrokeCap property of the
SKPaint object to one of the following members of the
SKStrokeCap enumeration:
These are best illustrated with a sample program. The second section of the home page of the SkiaSharpFormsDemos program begins with a page titled Stroke Caps based on the
StrokeCapsPage class. This page defines a
PaintSurface event handler that loops through the three members of the
SKStrokeCap enumeration, displaying both the name of the enumeration member and drawing a line using that stroke.Center }; / 2; float xLine1 = 100; float xLine2 = info.Width - xLine1; float y = textPaint.FontSpacing; foreach (SKStrokeCap strokeCap in Enum.GetValues(typeof(SKStrokeCap))) { // Display text canvas.DrawText(strokeCap.ToString(), xText, y, textPaint); y += textPaint.FontSpacing; // Display thick line thickLinePaint.StrokeCap = strokeCap; canvas.DrawLine(xLine1, y, xLine2, y, thickLinePaint); // Display thin line canvas.DrawLine(xLine1, y, xLine2, y, thinLinePaint); y += 2 * textPaint.FontSpacing; } }
For each member of the
SKStrokeCap enumeration, the handler draws two lines, one with a stroke thickness of 50 pixels and another line positioned on top with a stroke thickness of 2 pixels. This second line is intended to illustrate the geometric start and end of the line independent of the line thickness and a stroke cap:
As you can see, the
Square and
Round stroke caps effectively extend the length of the line by half the stroke width at the beginning of the line and again at the end. This extension becomes important when it's necessary to determine the dimensions of a rendered graphics object.
The
SKCanvas class also includes another method for drawing multiple lines that is somewhat peculiar:
DrawPoints (SKPointMode mode, points, paint)
The
points parameter is an array of
SKPoint values and
mode is a member of the
SKPointMode enumeration, which has three members:
Pointsto render the individual points
Linesto connect each pair of points
Polygonto connect all consecutive points
The Multiple Lines page demonstrates this method. The
MultipleLinesPage XAML file instantiates two
Picker views that let you select a member of the
SKPointMode enumeration and a member of the
SKStrokeCap enumeration:
<ContentPage xmlns="" xmlns: <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Picker x: <Picker.Items> <x:String>Points</x:String> <x:String>Lines</x:String> <x:String>Polygon</x:String> </Picker.Items> <Picker.SelectedIndex> 0 </Picker.SelectedIndex> </Picker> <Picker x: <Picker.Items> <x:String>Butt</x:String> <x:String>Round</x:String> <x:String>Square</x:String> </Picker.Items> <Picker.SelectedIndex> 0 </Picker.SelectedIndex> </Picker> <skia:SKCanvasView x: </Grid> </ContentPage>
The
SelectedIndexChanged handler for both
Picker views simply invalidates the
SKCanvasView object:
void OnPickerSelectedIndexChanged(object sender, EventArgs args) { if (canvasView != null) { canvasView.InvalidateSurface(); } }
This handler needs to check for the existence of the
SKCanvasView object because the event handler is first called when the
SelectedIndex property of the
Picker is set to 0 in the XAML file, and that occurs before the
SKCanvasView has been instantiated.
The
PaintSurface handler accesses a generic method for obtaining the two selected items from the
Picker views and converting them to enumeration values:
void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) { SKImageInfo info = args.Info; SKSurface surface = args.Surface; SKCanvas canvas = surface.Canvas; canvas.Clear(); // Create an array of points scattered through the page SKPoint[] points = new SKPoint[10]; for (int i = 0; i < 2; i++) { float x = (0.1f + 0.8f * i) * info.Width; for (int j = 0; j < 5; j++) { float y = (0.1f + 0.2f * j) * info.Height; points[2 * j + i] = new SKPoint(x, y); } } SKPaint paint = new SKPaint { Style = SKPaintStyle.Stroke, Color = SKColors.DarkOrchid, StrokeWidth = 50, StrokeCap = GetPickerItem<SKStrokeCap>(strokeCapPicker) }; // Render the points by calling DrawPoints SKPointMode pointMode = GetPickerItem<SKPointMode>(pointModePicker); canvas.DrawPoints(pointMode, points, paint); } T GetPickerItem<T>(Picker picker) { if (picker.SelectedIndex == -1) { return default(T); } return (T)Enum.Parse(typeof(T), picker.Items[picker.SelectedIndex]); }
The screenshot shows a variety of
Picker selections on the three platforms:
The iPhone at the left shows how the
SKPointMode.Points enumeration member causes
DrawPoints to render each of the points in the
SKPoint array as a square if the line cap is
Butt or
Square. Circles are rendered if the line cap is
Round.
When you instead use
SKPointMode.Lines, as shown on the Android screen in the center, the
DrawPoints method draws a line between each pair of
SKPoint values, using the specified line cap, in this case
Round.
The Windows mobile device shows the result of the
SKPointMode.Polygon value. A line is drawn between the successive points in the array, but if you look very closely, you'll see that these lines are not connected. Each of these separate lines starts and ends with the specified line cap. If you select the
Round caps, the lines might appear to be connected, but they're really not connected.
Whether lines are connected or not connected is a crucial aspect of working with graphics paths.. | https://developer.xamarin.com/guides/xamarin-forms/advanced/skiasharp/paths/lines/ | CC-MAIN-2017-30 | refinedweb | 1,066 | 53.92 |
What's the correct way to convert bytes to a hex string in Python 3?
Since Python 3.5 this is finally no longer awkward:
b'\xde\xad\xbe\xef'.hex()'deadbeef'
and reverse:
bytes.fromhex('deadbeef')b'\xde\xad\xbe\xef'
works also with the mutable
bytearray type.
Reference:
Use the
binascii module:
import binascii binascii.hexlify('foo'.encode('utf8'))b'666f6f'binascii.unhexlify(_).decode('utf8')'foo'
See this answer:Python 3.1.1 string to hex
Python has bytes-to-bytes standard codecs that perform convenient transformations like quoted-printable (fits into 7bits ascii), base64 (fits into alphanumerics), hex escaping, gzip and bz2 compression. In Python 2, you could do:
b'foo'.encode('hex')
In Python 3,
str.encode /
bytes.decode are strictly for bytes<->str conversions. Instead, you can do this, which works across Python 2 and Python 3 (s/encode/decode/g for the inverse):
import codecscodecs.getencoder('hex')(b'foo')[0]
Starting with Python 3.4, there is a less awkward option:
codecs.encode(b'foo', 'hex')
These misc codecs are also accessible inside their own modules (base64, zlib, bz2, uu, quopri, binascii); the API is less consistent, but for compression codecs it offers more control. | https://codehunter.cc/a/python/whats-the-correct-way-to-convert-bytes-to-a-hex-string-in-python-3 | CC-MAIN-2022-21 | refinedweb | 202 | 52.76 |
J.Pietschmann wrote:
> Nicola Ken Barozzi wrote:
>
>>> [top-level tasks]
>>
>> It has been accepted, and personally I find it very useful; I am able
>> now do do all sorts of initialization stuff, also in imported files,
>> and for example I can xslt-transform a project before importing it.
>> It's quite powerful, and not confusing at all.
>
>
> As for XSLT-then-import: what's the advantage over
> <project ...>
> <target name="default"
> <style src="..." dst="build2.xml" .../>
> <ant src="build2.xml">
> </target>
> </project>
> (sorry, can't be bothered looking up the correct syntax).
It's a big difference, because in your example you setup a new instance
of ant and it *really* slows down things, and also you create it a
nested context, not in the same context in which other tasks are run.
For example, with xslt I am able to construct a classpath using complex
logic quite easily, and import it in the buildfile right away as a
toplevel reference, where everyone can use it.
Basically it's preprocessing, like there is in C code, only that it's
done at runtime, not in two steps.
>>> [QNames]
>>
>> This is the current use:
>>
>> ${jxpath:/references/}
>> ${velocity:$mystuff}
>>
>> They tell Ant that the property must be resolved not directly but
>> using a defined interceptor; sort of the protocol in inet urls.
>
>
> If the semantic of the jxpath prefix is hardwired or defined by
> something like
> <bind prefix="jxpath" handler="whatever.class.necessary.Handler"/>
> it's ok.
> If it aquires it's semantic by
> <project xmlns:
> then it's abuse.
I'm safe then =;-)
<taskdef classname="org.apache.tools.ant.taskdefs.optional.JXPath"
name="jxpath" />
<jxpath/>
> Note that it would be legal to have the namespace declaration above
> if it doesn't define how ${jxpath:/references/} is interpreted, for
> example in case someone wants to have a <jxpath:mytask> somewhere
> (though this is hardly recommended). I hope you see the pattern.
Yes, I do now.
Fine then, it's ok.
>>> [scoping rules] [property namespaces]
>>
>> Any more concrete hint on how these should be?
>
> Ahem, perhaps using ${project-name.property-name} or something.
> Every method other than using xmlns:scope-name="..." would be fine.
Ok, rom the above I think I now get what you mean.
>>> What's the expectation: is X from B executed or not?
>>> Is it executed before or after X from A?
>>
>> :-/
>
> Oha! Caught?
Yes.
I think you are right, we must avoid including multiple times the same
target from different files in the same file.
>> We're defining it as we discuss.
>
> Ah, ok. A dedicated effort would still be a nice idea, I think.
You've found yourself an occupation then I guess ;> | http://mail-archives.apache.org/mod_mbox/ant-dev/200209.mbox/%3C3D7CFF8A.9040105@apache.org%3E | CC-MAIN-2015-11 | refinedweb | 446 | 65.93 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.