text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
Hello everyone. I am working on creating a stub that would allow me to swap out various sorting algorithms so that I can "plug in" the algorithms and run the various sorts. The below code is for Insertion Sort (yes, I know it is the slowest possible sort), but once I get it to work, I plan on doing Heap Sort, Merge Sort, Quick Sort, Radix Sort, and TimSort while collecting times from each one. The input file I am using has approximately 1/2 million values in order to give a better example of the variences in time.
I have included code for a timer to start just before the sorting algorithm and end just after the algorithm, then outputting the total amount of time the sort took. This information will be used to show quantifiable data for explaining the differences between the various choices of algorithms.
I've never seen the "Vector Subscript Out of Range Error" and can't determine the issue from researching C++ Forums or Daniweb. Can you point me in the right direction?
Thank you,
#include<iostream> #include<iterator> #include<fstream> #include<vector> #include<ctime> using namespace std; int main() { int i=0, j=0, key=0; std::vector<int> a; int start_s=clock(); //start timer ifstream readFile; readFile.open("inputData.txt");//open file if (readFile.is_open()) { while (!readFile.eof()) while (readFile >> a[i]) { for (int i=1; i<a.size(); ++i) // use pre-increment to avoid unneccessary temporary object { key= a[i]; j = i-1; while((j >= 0) && (a[j] > key)) { a[j+1] = a[j]; j -= 1; } a[j+1]=key; } } } readFile.close(); //close file int stop_s=clock();//stop timer cout <<"time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000 << endl;//output timer return 0; } | https://www.daniweb.com/programming/software-development/threads/452447/vector-subscript-out-of-range-error | CC-MAIN-2018-22 | refinedweb | 290 | 59.03 |
>>."
!Good (Score:2, Troll)
Oracle should use their Java related patents to stop this from happening,
Oh wait...
Re:!Good (Score:5, Interesting).
Java won't die anytime soon. (Score:3, Insightful)
From what I've seen, it's still largely popular as a web application language for the server-side. Usually an alternative to
Re: (Score:2). (Score:5, Insightful)
The article you link says it became the number one server side scripting language in 2002. While there isn't a really clear boundary of what is and isn't a "scripting" language, Java isn't included in any of the definitions generally used for that category, so in a discussion of Java, PHP's position among "scripting" languages -- server side or otherwise -- is pretty much irrelevant.
Re: (Score:2, Insightful)
And before we get into *that* argument again
... Java is no more compiled than converting a word doc to a pdf is "compiling" it. You cannot execute the resulting class files directly - they need to be interpreted by the run-time (originally, they were supposed to be interpreted by a special "Java chip" - "write once, run anywhere" was the exact opposite of the original design goals).
Re: (Score:2)
Java is an interpreted scripting language. It's also nowhere near number one - most hosting providers don't even offer it.
And before we get into *that* argument again
... Java is no more compiled than converting a word doc to a pdf is "compiling" it.
Java source is compiled to either native object format, or bytecode. The Gnu gcj compiler is an example of a "native" Java compiler. There are also a few commercial compilers that do the same thing.
You cannot execute the resulting class files directly - they need to be interpreted by the run-time (originally, they were supposed to be interpreted by a special "Java chip" - "write once, run anywhere" was the exact opposite of the original design goals).
You should explain why the original versions of Java had a VM, and why the "Java chip" never went anywhere (hint: there were implementations, but they didn't really offer anything compelling).
If Sun had had any brains, they would have fixed the slowness of Java by including the ability to compile down to native code. Then they could have arguably had the best of both worlds.
I guess you're too uninformed to know that one of the big reasons gcj hasn't taken off, is because the HotSpot type VMs ou
Re: (Score:3, Interesting)
Java is an interpreted scripting language.
Wow, your ignorance of Java is astonishing.
Java is no more compiled than converting a word doc to a pdf is "compiling" it. You cannot execute the resulting class files directly
It's compiled for the virtual machine. Your choice of PDF as an example is rather interesting. Had you instead chosen PostScript, you'd have had greybeards provide countless counterexamples.
But no matter how you want to look at it, it's absurd to maintain that Java isn't compiled.
Re: (Score:2)
Most of the times J2EE involves using JSP, the Java scripting equivalent of PHP. I've worked on many Java environments in the enterprise, and I've never seen a Java web server without JSP of some sort. PHP displacing JSP and ASP speaks volumes... I doubt those environments are replacing their JSP/Java with PHP/Java.
Re: (Score:2)
The servers that it did take over are now directly threatened (as are the database servers that they communicate with via java) by map-reduce and nosql. Much more scalable, no dependence on Oracle for anything, runs fine on commodity hardware, much easier to synchronize as well as build in transaction isolation and rollback.
10 years. That's an eternity in internet time, but not in human time, and the continued growth of data stores and
Re: (Score:2)
Re:!Good (Score:4, Interesting)
Dream on if yo believe that the JIT is competitive. Even if it were able to pre-compile everything to native methods, you still lack some of the essential programming models that people have been using for decades to make things go faster.
Re: (Score:3, Interesting)
I wasn't asking for proof that native code will be faster than Java, I was asking for proof of your original statement that that Java (I assume you meant the JVM) is a lot slower than Dalvik. hardwar
Re:!Good (Score:5, Insightful)
... anybody wanting to write truly high performance software had really better get used to writing in lower-level languages, or at the very least, understanding their stack right down to the hardware level.
This has always been the case.
Re: (Score:3, Insightful)
In c, it means that you get in the habit of typing free() right after typing malloc(), then asking yours
Re:: (Score:3, Insightful)
No, and no. If you are doing multithreaded programming, you can use reference counting. It's not at all hard to do explicit retain/release unless your program is crap by design. In many case
Re: (Score:2)
If it were easy, everyone would be doing it. But the performance benefits of not needing things like reference counts, garbage collectors, etc., make it worth it. After all, you fix the problem once, and reap the benefits the billions of times that code executes.
If we were to truly cost out the cos
Re: (Score:3, Interesting)
The C version is easy to understand when you are in total control and total understanding of the program flow. However, it's a nightmare for people trying to enhance or restructure the code because they can so easily cause the free() to not get called, get double called or to simply not realize all the places cleanup code is required. This is particularly true for all kinds of exception-like flows, that everything is cleared up in all varieties.
If you strictly adhere to RAII in C++ then things are fairly ok
Re: (Score:2)
Ok, so basically your reason why C is better than Java is that if you write perfect code, you never have to worry about memory issues.
Why not just write in FORTRAN? Or Assembly, even?
Re: +
Re: (Score:2) hardware level. m
Re: (Score:3, Insightful) manipulate individual bits (in registers or in memory) and are extremely useful (efficient!) for implementing things like a Bloom Hash, or just implementing bit arrays. In C the best we can do is use clunky full-word operations that can not get optimized down to BT, BTR, or BTS for multiple technical reasons.
Is this a joke? Anything that isn't assembly is a high level language? News to me.
C is very obviously a low level language. It's not exactly controversial.
Re: .
Re: (Score:3, Funny)
I'm not confusing lack of features (abstractions) with low level - abstractions are exactly what makes a language high level. Yes, C making you reference memory directly makes it low level. High level languages take you far, far away from such interactions.
Pointers are an abstraction
Apparently you didnt fucking know this, but C is a programming language defined by a standardized abstract machine which itself was tailored specifically for the purposes of abstracting operating system memory management.
Furthermore, C does not 'make' you reference memory directly. C 'allows' you to reference memory directly.
Did you not realize that BASIC qualifies as 'low level' under your definition of direct memory referencing I guess its PEEK and POKE for the win, eh?
Re:!Good (Score:5, Insightful)
you can't even consider using some algorithms that c programmers use all the time
Like buffer overruns.
Re: (Score:2)
Try such basic stuff as pointer arithmetic.
Re: (Score:2, Informative)
Re: (Score:2)
Re: (Score:3, Informative)
Re: (Score:3, Informative)
Re: (Score:2): (Score:2)
This is why sensible programmers moved to C++ and use range-checked, auto-growing container objects.
Re:!Good (Score:5, Funny)
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)!):
Re: (Score:2)
Just enum RED_LIGHT=0, YELLOW_LIGHT, GREEN_LIGHT then either jump to the offset at LIGHT_FUNCS+light*PTR_SIZE, or if you've created an array of function pointers, set lights[NORTH_SOUTH] = light_funcs[light]; Your code becomes more generic, even though the code for handling a red light may b
Re: (Score:3, Informative)
Call me back when your operating system is written in Java. Oh wait, Sun tried that - another failure.
You're an idiot.
Re: (Score:2)
... g
Re: (Score:2)
Java will eventually lose ground there as well for several reasons:
#2 is currently the big issue. Once a Java project passes a certain
Loss of confidence (Score:5, Informative)
Looks like we're seeing a new loss of confidence in Java, much like the loss of confidence in mono, for which patent concerns stunted its uptake.
So where to next?
And where is my replacement for open office?
Re:Loss of confidence (Score:5, Insightful)
No, we are seeing a loss of confidence in Oracle. Unfortunately, Oracle now owns Java. That means its future is a little foggy. Oracle has a serious hard-on for Java, which you can see because it is the only major database I know of that allows you to use Java in place of PL/SQL. Disclaimer: I haven't actually done this, but I did read about it while googling some issues I was having with an Oracle database.
I think there is room for two cross-platform environments such as
.NET and Java. Right now, those are the players. I don't see the F/OSS community putting all their eggs in Microsoft's basket, even if people do use Mono to some extent. If Oracle succeeds in making Java their pool boy and effectively neutering OSS implementations of the language and JFC, another environment will need to rise to to the occasion. I think it would be a community effort to some degree, but driven largely by Google. I could see them forking Java and realizing that due to trademark and patent concerns they would need to make large changes, so they would make major changes, add a bunch of stuff, and turn it into one hell of a platform for mobile and network development. That was Java's original goal, but it has since bloated up well beyond that and I do mean bloat, not grow. Why do we need a total of three implementations of core JFC classes to do stuff like "read a JPEG," and two of them either don't work at all or only work if you drink unicorn blood while coding? Why are there two GUI implementations, and the one that makes sense is still a zombie built on top of decaying pieces of the AWT corpse?
Sun had so many opportunities to grow the JFC, add value, etc. but due to their intense fear of breaking backwards compatibility, they just layered more and more band-aids and duct tape on top of each other. At some point you need to do it right with new implementations and say "upgrade to version X, and deprecated crap is being removed. You are now warned."
Also, Java EE needs to be merged into Java SE. There should be two Javas. One for memory-constrained devices (embedded), and one for everywhere else. Java EE has been a pain in my ass for some time. Java doesn't need the extra complexity.
Re: (Score:2): (Score:2) propriet
Re: (Score:2)
Re:Loss of confidence (Score:5, Informative)
Re: (Score:2)
Re: (Score:2, Interesting) G
Re: (Score:2)
Lose-lose situation (Score:3, Insightful)
Yes, you're missing something (Score:2)
Re:Lose-lose situation (Score:5, Interesting)
Am I missing some great strategic outcome Oracle is hoping for?
Yes, they need Google patents for their database product to not become obsolete in the next few years. Buying Sun got them two things - a) hardware fast enough to get them over the gap b) leverage for patent cross-licensing agreements.
This is a [software] patent (government) problem.
I was confused when they bought Sun... (Score:2)
I don't know what they hope to achieve with this but maybe this lawsuit is connected with the purchase, ie. they planned it from the beginning.
Re:Lose-lose situation (Score:5, Insightful)
Re: (Score:2)
Can Oracle's reputation get any worse?
Re:Lose-lose situation (Score:5, Interesting).
Troll? Really? (Score:2)
How the hell is the OP a troll? Or did some fucking idiot mod once again misread "troll" as "I don't like what you're saying!"?
Re: (Score:2, Insightful)
Re: (Score:3, Interesting)
While the reputation of Oracle might mean something to yourself, myself or others on slashdot, the average joe on the streets of the world do not give a rats backend as to the "reputation" of Oracle.
All they care about is how well their phones work. Ergo, Oracle has very little to lose, since they already have inhouse lawyers anyway, and potentially something nice to gain; a nice chunk of leverage to be used in discussions with Google. righ
Re: (Score:2)
The "average Joe" doesn't give a dime to Oracle. It's the IT/software professionals that give millions of dollars of their departmental budgets to Oracle. The kind with an anti-Microsoft slant are even more likely to be doing this.
Ergo, Oracle should be VERY concerned of the opinion on Slashdot.).: (Score:2, Interesting),
Re: (Score:2)? (Score:5, Interesting)? (Score:5, Insightful)
> In summary, open source Java is fine, open source almost-Java is not.
Where is the difference? Isn't that legal newspeak of corporate lawyers... and why we have a free software movement? I can't see how this sentence makes any sense to an open source developer.
Re: (Score:3, Insightful)
Re: (Score:2)
Dalvik still wouldn't run JVM bytecodes, so I don't think it would a conforming implementation regardless. I haven't read the spec however, so I don't know if the bytecode is specified there or separately. pr
Re: (Score:2): (Score:2)
I've never got the whole "death to java" thing - can you explain why you think its demise is way over due?
For bunnies sakes ... (Score:4, Insightful)
Do you have a bank account?
Most likely the back office operations are using Java in one way or another.
That is just for starters.
People saying that Java is dead and then refer to what is happening on their home computer simply show a degree og ignorance that is short of embarrasing.
Re: (Score:3, Informative)
They're just as likely to be using COBOL but most people regard that as 'dead'.
Re:I'm glad (Score:5, Insightful)
Java's death means
.NET and Windows in the server arena. Do you really want that?
Java is the defacto standard for most server apps these days as portals are replacing terminals and Java is used for industrial websites as well. This is truly horrible and no php or perl can not just replace it for mission critical servers. It is not hte language but the 200,000 methods and api's to choose from. Only
.NET comes close ... not Mono.
Unintended consequences (Score:3, Interesting)
>: (Score:2): (Score:2)
You can use the JVM with other languages... Scala, Groovy, Clojure, Python, Ruby and more.
"Java" doesn't mean only the language, there's also the platform.
Re: (Score:3, Interesting)
Don't get me started on the platform.
Okay, I'm game. What's wrong with the platform?
Re: (Score:2)
So was it a good thing or a bad thing when Microsoft did a Google (or rather...) with their version of Java?: (Score:3, Insightful)
Same language? C# and Javascript have nearly identical syntax. I think it's completely unreasonable to expect someone to invent a brand new syntax for every programming language.
Some of the same classes? Look at how many other languages have analogous classes in their libraries. It's irresponsible not to provide string utilities, for one.
Re: num
Re: (Score:3, Insightful)
The similarity of android's dev language with Java is only superficial
You mean, aside from the fact that they are exactly the same language and both provide a large number of the same classes in the java.* namespace, they are completely different?
Damn, I'm going to do it -- I'm going to make a car analogy. I'm sorry in advance, because I *know* someone is going to helpfully correct it and take it far beyond the point I was trying to prove.
Let's say all cars had a single engine they used. They could manufacture this engine themselves, but it had to conform to the agreed-upon specs if they wanted to call it a "car engine". So Ford and Chevy and Toyota are all happily marketing cars with Genuine Car Engines; they have different trim and options, b
Re: (Score:2)
It's funny how Java and dalvik are more compatible than different vendors' implementations of C++ when I was in college. Heck, even C or Pascal in the 80's.
Re: (Score:2)
Re: (Score:2)
It wont actually die, it will just become an in-house language for oracle application development.
Re: (Score:2)
There's nothing inherently wrong with Java
So where are all the desktop applications...?
Re: (Score:2)
Re: (Score:2)
Re: (Score:3, Informative)
Oracle is sueing for patent infringement, not trademark infringement.: (Score:2)
Perhaps if you did some research you'd see what the problem is. You can't claim to allow use of the Java programming language and not follow the rules of the company that owns the rights to it. Google borrowed the trademark and
Re: (Score:2)
Your point being what exactly?
You program Android applications in the Java programming language. That doesn't make it a Java platform. And if you meant to imply that every implementation of the Java language has been design
Re: (Score:2)
Re: : (Score:2)
The part you quote no more suggests that Android is Java than the references to Eclipse in the documentation suggest that Android is Eclipse.
Google are saying that you can use the language part of Java, known as the "Java Language", to develop applications for Android. The issue here is that the same word, Java, is used for both Sun's language and Sun's platform, and you're interpreting the comment as meaning the latter.
Substitute C for Java in the part you quote, and pretend it's Microsoft's documenta
Re: (Score:2)
> So where do you see that they're not calling it Java?
Where do you see that Google is selling anything called Java? A trademark is not a copyright. Oracle would certainly be alleging trademark infringement if they thought that they stood any chance of convincing the court that their trademark was being infringed. As far as I can tell they are not. | https://developers.slashdot.org/story/10/08/28/0119257/Google-Backs-Out-of-JavaOne | CC-MAIN-2017-17 | refinedweb | 3,190 | 63.39 |
Opened 7 years ago
Closed 7 years ago
Last modified 6 years ago
#14487 closed (fixed)
Stop leaking unittest2 as 'unittest' from django.test.simple
Description
This is especially dangerous for cases of
from django.test.simple import * where a
import unittest comes before.
Change History (3)
comment:1 Changed 7 years ago by
comment:2 Changed 7 years ago by
Although this bug technically exists in 1.2 as well, I'm not going to backport, The issue isn't as critical with 1.2 because there isn't a second unittest causing problems; plus, this could break code in production. That code probably *should* break, since it's relying on imports that it shouldn't, but it's a breakage that we don't need to enforce.
comment:3 Changed 6 years ago by
Milestone 1.3 deleted
(In [14258]) Fixed #14487 -- Prevented unittest from leaking into scope via a 'from django.test.testcases import *' import. Thanks to Jannis for the report. | https://code.djangoproject.com/ticket/14487 | CC-MAIN-2017-43 | refinedweb | 164 | 66.54 |
Spring 3, Spring 3.0, Spring Framework, Spring Framework Tutorial
makes it very useful. The Spring 3 framework allows the
developers...Spring 3
In this tutorial we will learn Spring 3 Framework with the help of many
articles and example. We have developed the tutorials covering major spring
Spring Framework Tutorials
useful. Moreover, the Spring MVC components can be utilized for the development... the Spring Framework topics given belows:
Spring 3 Tutorial
Spring 3.0...Spring Tutorials
The Spring Framework is an open source Java platform, which
Tutorial for spring - Spring
Tutorial for spring Hi Deepak,
Iam new to SpringFramework,give some.... Hi friend,
I am sending book name of spring framework.
1. Beginning Spring Framework 2.
2. Spring in Action, Second Edition
Beginning... to another technology, it is very difficult. But, as Spring
offers modules for aall...
SPRING Framework... AN
INTRODUCTION
Java programming tutorial for very beginners
Java programming tutorial for very beginners Hi,
After completing my 12th Standard in India I would like to learn Java programming language. Is there any Java programming tutorial for very beginners?
Thanks
Hi
Spring Bean Example, Spring Bean Creation
Basic Bean Creation
The Spring bean can typically be POJO(Plain Old Java Object) in the IoC
container. Here in this tutorial you will see at first a simple...;">
Objective C Tutorial
Objective C Tutorial
In this Objective C Tutorial we will provide you
step-by-step information in detail. You will find this object c tutorial very
useful. You can quickly
Spring Tutorial
Spring Tutorial
In this section we will read about the Spring framework.
This section will describe about the various aspects of Spring framework... and many more. At the
time of writing this tutorial latest version of Spring is 3.2.
JSP Tutorials Resource - Useful Jsp Tutorials Links and Resources
;
JSP
Tutorial
The prerequisites for the tutorial.... You should be able to program in Java.
This tutorial teaches JSP by progressing from very simple
examples to complex examples.
For best progress
| - Spring
spring hi,
I need sample example user update profile using spring with hibernate and spring jsp.
I need the sample code very urgently.
Please... the following link:
About Hibernate, Spring and JSF Integration Tutorial
About Hibernate, Spring and JSF Integration Tutorial
This tutorial...
tier. Spring integrates Hibernate very well.
Flow of the application
Hibernate and Spring
Hibernate and Spring
In this section we will discuss Hibernate and Spring... business. Hibernate and Spring are
excellent technologies and can be used....
In this page you will find excellent tutorial links for integrating Hibernate
Tutorial
Tutorial suggest me some good spring material for begginer
Integrate Struts, Hibernate and Spring
are using one of the
best technologies (Struts, Hibernate and Spring). This tutorial...://.
We are using hibernate-3.1.3 for this tutorial.
Download Spring...
Integrate Struts, Hibernate and
Spring Web Annotation Classes
below.
@Controller - In Spring MVC you can make controller class very easily...Spring Web Annotation
Annotation is introduced since java 5. It is a new kind... and it is not a part of your program.
Spring framework also provides a wide range... application easy work.
In this Spring tutorial series we will learn Spring...
Spring 3 Tutorial
The Spring 3.0 framework has been released with major
Spring JDBC Introduction
Spring JDBC Introduction
The Spring's DAO(Data access object) make it easy... catching exception that are related
to each technology.
This tutorial provide a
brief introduction about Spring DAO JDBC. The following table describe
Perl and CGI Miscellaneous Very short delay Tutorial
If you want to emulate very short delay in your program, with duration less than
1 second, you should use select function (if your system supports it).
Function ussually used to monitor operations on file handles.
Syntax
Roseindia Spring Tutorial
tutorial examples helps to understand the practical aspects of spring framework... in Spring
Spring 3 Tutorial
Spring 3 Hello World Example
@configuration...Roseindia Spring tutorials provide you complete coverage of wide range examples - Spring
Spring examples Hi,
I need the sample example for how to retrieve the values from jdbc using spring.
Please send the sample example immediately.
Its very urgent.
Thanks,
Valarmathi P Hi Friend,
Please
wml tutorial
on top of the SMS technology. This SMS tutorial will provide you useful...
WAP Tutorial
WAP
Tutorial
The WAP protocol is the leading... our WAP tutorial you will learn about WAP and WML, and how to convert your HTML
Spring Tutorial for Beginners
The Spring Framework is an open source Java platform through which...
for the Java platform.
Spring Framework was first written by Rod Johnson in his... then, many advance
versions of Spring were released namely Spring Framework 1.0
Spring AOP tutorials and example codes.
Spring AOP (Aspect Oriented Programming)
What is Spring AOP (Aspect Oriented Programming)?
Spring AOP is a new programming paradigm, which is implemented... time, run
time load time. In spring framework weaving is performed at run time
Questions on Spring - Spring
Questions on Spring 1> what is Spring Framework ? why does... in Spring ?
3> what is Spring - Aspect Oriented Programming,Please explain with a working Example for Spring - Aspect oriented Programming Concept.?
Spring 2.5 MVC File Upload
Spring 2.5 MVC File Upload
Spring 2.5 MVC File Upload
This tutorial explains how to upload file in Spring 2.5 MVC Framework.
Spring MVC module of Spring framework
XML Tutorial
XML Tutorial
XML
Tutorial:
XML stands for EXtensible Markup Language. In our XML tutorial you will learn what XML is and the difference between... school
Tutorial:
At W3Schools you will find all the Web-building
Getting started with the Spring MVC framework.
Spring MVC Getting Started - Getting started with Spring
MVC... Spring MVC Framework
In this we will quickly start developing the application using Spring
MVC module. We will also see what all configuration and code...://
Hibernate Video Tutorial
as the online training material, which is very
useful in learning the Hibernate... application.
Hibernate is very useful ORM tool which can be used to develop...Easy to learn Hibernate Video Tutorial by Deepak Kumar
In this section
SPRING WITH DATABASE
SPRING WITH DATABASE I need any Spring MVC project that connects... how to create spring project and how to connect with the oracle database. I MVC, Spring MVC Module Tutorial
Spring MVC - Spring MVC Introduction
In this example we will give you quick overview of
Spring MVC Framework. The Spring MVC framework is the MVC stack for the
development of web interception on the page in my application Jee, the page must be accessible
Utility of Linux
;
Linux is a very useful Server... in workstation. Windows
have also desktop configuration.
Linux is very... efficiency.
Linux has a very wide range of inclusive software
Reduce Java Code commenting effort using JAutodoc (eclipse plugin)
;
INTRODUCTION
Summary
JAutodoc is a very useful eclipse plugin which helps in generating javadoc style comments very easily. Apart from adding...
/*
* ****************************************************
* * SPRING REFERENCE APPLICATION
Dynamic Proxies - Short Tutorial
(this is not a
java.lang.Security tutorial, so please excuse the following
very...Dynamic Proxies - Short Tutorial
2001-01-18 The Java Specialists' Newsletter [Issue 005] - Dynamic Proxies - Short Tutorial
Author:
Dr. Christoph G
Tutorial, Java Tutorials
technologies. All the tutorials are very useful for programmers. You can learn
these tutorials very fast. These tutorials are well written and supported with
good...
Java Testing
JSON Tutorial
Spring login form application
Spring login form application Hi Please give me the Spring login form application so that i can understand its flow ?
Hi please find the link of the tutorial
Spring Applications
Know About Outsourcing, More About Outsourcing, Useful Information Outsourcing
and offshoring. For them, both terms mean the same, but this is not very accurate
Spring Validation
Spring Validation
In this tutorial you will see an example of how to perform validation in
spring-core. The spring provide Validator interface.../beans/spring-beans-3.0.xsd">
<bean id="personBean ResourceLoaderAware
Spring ResourceLoaderAware
We use the ResourceLoader when your application object need to access
different type of file resources. In this tutorial you...://">
<
Logging Tutorial - Part 1
Logging Tutorial - Part 1
2000-12-14 The Java Specialists' Newsletter [Issue...
in this newsletter useful.
I drew some fire from respectable quarters that some.... Unit tests have saved my butt a number of times,
because I am not a very
What is EJB 3.0?
Specification but still very powerful. Now there is no
need to write home... developed your enterprise application very fast.
Dependency...
Persistence of the entity objects are now very simple through the
introduction
Form Handling in Spring Framework
Form Handling in Spring Framework I have created spring project.I... empty. Can you send me some code for handling form in spring framework.
Please visit the following links:
ApplicationContextAware in spring
.style1 {
background-color: #FFFFCC;
}
ApplicationContextAware in spring
In this tutorial you will see and example of using...://">
<bean
The registerShutdownHook in spring
.style1 {
background-color: #FFFFCC;
}
The registerShutdownHook in spring
If you are using Spring IoC in non web application and want...://">
</beans>
Why Web Development with PHP Is Useful
.
The PHP language is very easy for a search engine to read. This comes from how....
The code is very easy to use because it is not going to be too crowded
@Component Annotation in Spring, Spring Autoscan
@Component Annotation in Spring
In Spring normally if there is bean we need... can scan all your bean
through spring auto scan feature. The @Component.../schema/beans/spring-beans-2.5.xsd
Spring AOP Question
Spring AOP Question What is point cut in Spring AOP?
... distinguishes it from older technology offering interception.
Spring supports... pointcut matches. It is more useful pointcut. And Intersection means the method
Spring Resource Example
Spring Resource Example
The Resource interface is used as an argument type... how to use Resource
interface in spring framework.
AppMain.java
package.../schema/beans
Spring Lazy Initialization, Spring Lazy Loading example
Spring Lazy Initialization
In general all bean are initialized at startup. To stop such unnecessary
initialization we use lazy initialization which create.../spring-beans.xsd">
<bean id="studentBean"...://
Spring Framework, Spring Framework in Java
tutorial on
the Spring Framework. We have created many examples to help... Framework Tutorials
Spring 3 Tutorial...Spring Framework
Welcome to the Spring Framework tutorials, here we
Learn Spring Framework from where?
Hi,
Please see the following tutorials:
Spring 3.2
Spring Tutorial...Learn Spring Framework from where? I want to learn the Spring... for beginners.
Could someone suggest me the best url to start learning
spring hi
how can we make spring bean as prototype
how can we load applicationcontext in spring
what is dependency injection
regarding header files - Spring
regarding header files i am working on linux platform. i a using spring framework 2.5.4.while comlinig the client program i.e from demo which given in tutorial.
error is these two package does not exist
import
Spring MVC XmlViewResolver Example
Spring web VelocityViewResolver.../schema/beans/spring-beans-3.0.xsd
http
Beginners Java Tutorial
Beginners Java Tutorial
This tutorial will introduce you with the Java Programming language. This
tutorial is for beginners, who wants
spring
spring how to upgrade from struts2 to spring
spring
spring javascript browse image in spring progrme
spring
spring Access JSP files in Spring
Spring asm Dependency
Spring 3 ASM - Spring asm Dependency
In earlier version of Spring (Spring version 2.5) the asm library was
included. But the current version of Spring">
Electronic spreadsheets are useful in situation
Electronic spreadsheets are useful in situation Electronic spreadsheets are useful in situation where relatively ---- data must be input..
1. Small, 2.Large, 3. No, 4. All of the above 5. None is true
Answer:1. Small
Spring MVC Controller hierarchy
. In
Spring MVC DispatcherServlet plays very important role. It handles the
user...
Spring MVC Controllers - Controllers hierarchy in Spring MVC
Controllers hierarchy in Spring MVC
Spring Framework Install
Spring Framework Install
Spring Framework Install - a quick tutorial to install
Spring... the latest version of Spring framework (spring-framework-2.5.1-with-dependencies.zip
Spring Override Bean
Spring Override Bean
The support of inheritance is present in the Spring framework and common
values or configuration is shared among beans. The child bean.../beans"
spring
spring sir how to access multiple jsp's in spring | http://www.roseindia.net/tutorialhelp/comment/91760 | CC-MAIN-2013-48 | refinedweb | 2,035 | 50.02 |
So here is the scenario. I currently have an overburdened DC (2003 SP2, not R2) that, among other things, is also my primary file server. I have already moved the files over to another DC (2008 R2) and I want to set up DFS replication on it. My goal is to have DC's on each of my three remote sites replicating the file share so that it decreases loading time, provides me with a ghetto backup, and decreases load over the VPN.
Since I have an existing file structure, what is the best way to go about this? Do I point the Namespace at the directory just above my root share? Are there any gotchas to watch out for in setting this up?
With replication, which method should I use, Multi-purpose, or group? Group seems like the logical choice from some of what it says, but it isn't very clear, and Microsoft's Step-By-Step guide is not very clear on the differences.
Any suggestions for how/when to add in my remote servers?
Thanks in advance.
Aug 16, 2010 at 3:53 UTC
I am assuming you have checked this out:
http:/
You may also reference this:
http:/
The latter is for 2003 R2, however, some of the same principles apply.
14 Replies
Aug 16, 2010 at 3:53 UTC
I am assuming you have checked this out:
http:/
You may also reference this:
http:/
The latter is for 2003 R2, however, some of the same principles apply.
Aug 17, 2010 at 12:51 UTC
ACTS360 is an IT service provider.
Make sure that after you add a DFS server you go to each of the other DFS servers and add the new namespace server. I believe you open up dfs management, then click on the server and it is the second tab over. If you don't add all the servers to all the DFS servers then they won't fail over and that can cause some really strange errors, including file loss (I speak from painful experience on this one).
Aug 17, 2010 at 4:33 UTC
You may want to take a view on this topic with some DFS related links:
Aug 17, 2010 at 7:05 UTC
Are there any plans to replace the 2003 non-R2 box? R2 added some great features and completely redesigned DFS, and that is really what you would want to use for this kind of job.
Aug 17, 2010 at 8:53 UTC
@Imba & Jeremy - Thanks for the links, I'm reading through them now.
@Josh - Thanks for the heads up. I'll make sure to handle that one.
@Christopher - The 2003 Server is just a DC. It won't directly be a part of the DFS structure. I listed it just so that you all had a complete picture of what was going on just in case it was going to be an issue. If it is going to affect the deployment then I'll have to hold off on the whole project since it is the classic "eggs-in-one-basket" server for the company that I'm trying to get away from, and some of the eggs aren't ready to be moved.
Thank for all the input.
Aug 17, 2010 at 9:22 UTC
+1 to josh's comment. I have made that mistake before.
Aug 17, 2010 at 9:28 UTC
How well does the DFS structure handle one of the servers having its IP changed? The reason I ask is that it would be much more convenient for me to set up each of these servers here at my office and then move them and re-IP them when they're up and going, instead of working at the remote site trying to deal with anything that comes up.
Aug 17, 2010 at 9:31 UTC
Shouldn't matter as long as your DNS is setup correctly.
Aug 17, 2010 at 9:39 UTC
Cool. Thanks for the quick response.
Aug 17, 2010 at 10:18 UTC
Don't forget you can setup replication without a namespace
If you are just looking for replication and not the full DFS bit
Just create a replication group etc
It takes some load off the servers and WANs as well
Aug 18, 2010 at 7:13 UTC
Is there any way to set up a namespace pointed at an existing folder structure without it blowing away your permissions? I'm not sure what I'm doing wrong, but I've tried this twice now, and it has reset all of my permissions both times.
Aug 18, 2010 at 7:31 UTC
Are you actually using the namespace features or do you just want the folders to replicate?
setting up replication will not hjange the permissions unless you direct it to
Aug 19, 2010 at 7:46 UTC
For DFS and file permission settings see:
http:/
http:/
You can set where the permissions are inherited from.
Aug 20, 2010 at 9:51 UTC
Thanks for all the input guys. I'm going to have to shelve the project for a bit since the fires burn hot... | https://community.spiceworks.com/topic/107820-dfs-setup-questions | CC-MAIN-2017-22 | refinedweb | 863 | 84.51 |
New Relic's APM (Application Performance Monitoring) Python agent (Learn More) is a powerful tool you can utilize to monitor and instrument the performance of your complex GIS ETL processes and custom Python based services. Deploying APM to your existing Python processes is easy. Even easier if you already utilize functions, as the agent instruments the execution of functions via a Python decorator.
It's important to understand that short processes, those lasting only a minute or less, are not ideal candidates for instrumentation. Think of your large, mission critical data sync jobs that cycle services, copy data, add columns, perform spatial analysis, calculate fields, etc. Those that tend to run for several minutes and execute multiple steps. We can gain insights beyond what we write to log files and see how resource intense each step is, the response times of the service calls our ETLs make, which services are slowing down our ETLs, and be able to monitor performance before and after changes to code, data or services.
Check out some sample executions and then I'll explain how to get the Python agent installed and instrumenting.
DISCLAIMER: Things like corporate firewalls, security settings, and proxy servers can make configuring any tools difficult. The steps outlined below assume those items have been negotiated already.
Assumptions: You are running your ETLs on a Microsoft Windows machine. The New Relic agent works natively with Linux also, but the steps below are for Windows.
1. New Relic Account
To get started instrumenting your own processes, you'll first need a New Relic account. You can sign up for one at.
2. Install "pip"
Next, you'll need the Python package manager "pip" installed on the machine that you wish to run the instrumented ETL from. You can learn more about installing pip here:.
Tip: If you have multiple Python installations or do not have Python's directory included in you path, you may have to explicitly call Python from the location ArcGIS' installer placed it, e.g. "c:\Python27\ArcGIS10.4\python.exe c:\path\get-pip.py"
3. Install the New Relic Python Agent
With pip installed, we need to install the New Relic agent. As with installing pip, from a command line execute some manner of the following;
python -m pip install newrelic
or
c:\Python27\ArcGIS10.4\python.exe -m pip install newrelic
Tip: For Windows pip users, we have to pass the "-m" parameter to call the pip module. Linux based Python does not need the module parameter.
4. Create a New Relic agent configuration file
Your agent will need a configuration file created for each individual ETL process. The configuration contains settings such as your license key, application name, logging settings, and proxy settings.
Here is a basic ini file to get you started:
[newrelic]
license_key = <your key goes here>
app_name = <your ETL name goes here>
monitor_mode = true
log_file = C:\PATH\newrelic.log
log_level = error
ssl = true
high_security = false
#proxy_scheme = http
#proxy_host =
#proxy_port =
#proxy_user =
transaction_tracer.enabled = true
transaction_tracer.transaction_threshold = apdex_f
transaction_tracer.record_sql = obfuscated
transaction_tracer.stack_trace_threshold = 0.5
transaction_tracer.explain_enabled = true
transaction_tracer.explain_threshold = 0.5
transaction_tracer.function_trace =
error_collector.enabled = true
error_collector.ignore_errors =
browser_monitoring.auto_instrument = true
thread_profiler.enabled = true
[newrelic:development]
monitor_mode = false
[newrelic:test]
monitor_mode = false
[newrelic:staging]
monitor_mode = true
[newrelic:production]
monitor_mode = true
Place the ini somewhere central to your ETL scripts as we'll need to reference it from the code.
The important parts are the license key which you'll get from New Relic and the app name which you choose. I included the proxy settings commented out just in case you have that obstacle too.
For more information on the agent configuration file, see the New Relic documentation here.
5. Add the agent to your ETL script
Adding the agent is as simple as importing and initializing the module.
Import:
import newrelic.agent
Initialize:
newrelic.agent.initialize('C:\\PATH\\newrelic.ini')
6. Add the Python decorator to your functions
With the agent initialized, we need to identify the functions we want to measure the performance of. We do so by wrapping the function in a Python decorator.
The decorator code looks like:
@newrelic.agent.background_task()
Adding it to a function is as easy as placing it on the line directly before your function definition. See the following example.
Without:
def setworkspace():
# Set the workspace
env.workspace = "C:/Temp/GISData.gdb"
# Set a variable for the workspace
workspace = env.workspace
outputGDB = "C:/Temp/OutputData.gdb"
print "Workspace set"
With:
@newrelic.agent.background_task()
def setworkspace():
# Set the workspace
env.workspace = "C:/Temp/GISData.gdb"
# Set a variable for the workspace
workspace = env.workspace
outputGDB = "C:/Temp/OutputData.gdb"
print "Workspace set"
Here is a complete sample with basic functions to demonstrate how it works. (I know, it's quick and ugly.)
# Instrumentation test
# New Relic Python ETL Test
import newrelic.agent, time, arcpy, arcpy.da
from arcpy import env
import shutil, os
@newrelic.agent.background_task()
def copyfiles(src, dst):
shutil.copytree(src, dst)
@newrelic.agent.background_task()
def setworkspace():
# Set the workspace
env.workspace = "C:/Temp/GISData2.gdb"
# Set a variable for the workspace
workspace = env.workspace
outputGDB = "C:/Temp/GISOutput.gdb"
@newrelic.agent.background_task()
def setenvironment():
#Turn on overwriting of logs
arcpy.env.overwriteOutput = True
@newrelic.agent.background_task()
def copydata():
# Function grabbed here
for gdb, datasets, features in arcpy.da.Walk(env.workspace):
for dataset in datasets:
for feature in arcpy.ListFeatureClasses("*","POLYLINE",dataset):
arcpy.CopyFeatures_management(feature,os.path.join(outputGDB, dataset))
if __name__ == "__main__":
newrelic.agent.initialize('C:\\PATH\\newrelic.ini')
copyfiles('C:/Temp/GISData1.gdb','C:/Temp/GISData2.gdb')
setworkspace()
setenvironment()
copydata()
Check out my other how-to articles to this series showing you how to:
Application Performance Monitoring for Complex ETLs
Instrument Portal for ArcGIS Server
Instrument ArcGIS Data Store | https://community.esri.com/people/aaron.lee/blog/2017/06/02/application-performance-monitoring-for-complex-etls | CC-MAIN-2019-13 | refinedweb | 957 | 50.12 |
17159/spring-configuration-file
What is a Spring configuration file?
A Spring configuration file is an XML file that contains the classes information. It describes how those classes are configured as well as introduced to each other. The XML configuration files, however, are verbose and cleaner. If it’s not planned and written correctly, it becomes very difficult to manage in big projects.
@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
public void ...READ MORE
You can use Java Runtime.exec() to run python script, ...READ MORE
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class WriteFiles{
...READ MORE
You can use readAllLines and the join method to ...READ MORE
Using nio we can check whether file ...READ MORE
Configuration metadata can be provided to Spring container in ...READ MORE
The @Autowired annotation provides more accurate control over where ...READ MORE
There are basically two types of IOC ...READ MORE
Here, I have listed down few differences. ...READ MORE
Well, below I have listed down few ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/17159/spring-configuration-file?show=17160 | CC-MAIN-2020-10 | refinedweb | 185 | 63.76 |
This action might not be possible to undo. Are you sure you want to continue?
Haskell's Standard Prelude (in Appendix A of the Report and the standard libraries (found in the Library Report [5]) contain lots of useful examples of Haskell code. This will not only give the reader a feel for what real Haskell code looks like. we encourage a thorough reading once this tutorial is completed. TYPES.2 2 VALUES. but will also familiarize her with Haskell's standard set of prede. AND OTHER GOODIES other hand.
C. the Haskell web site. This is in stark contrast to the organization of the Report. Modula. or even ML. or Scheme.] Haskell is a typeful programming language:1 types are pervasive.1" refer to sections in the Report).org. the adjustment should be easier but still not insigni. and the newcomer is best o becoming well aware of the full power and complexity of Haskell's type system from the outset.ned functions and types. For those whose only experience is with relatively \untypeful" languages such as Perl. although the Report remains the authoritative source for details (references such as \x2. [We have also taken the course of not laying out a plethora of lexical syntax rules at the outset. as with this paragraph. and enclose them in brackets. has a wealth of information about the Haskell language and its implementations. Rather. we introduce them incrementally as our examples demand. this may be a diÆcult adjustment. Tcl.. Finally. for those familiar with Java.
all computations are done via the evaluation of expressions (syntactic terms) to yield values (abstract entities that we regard as answers). Just as expressions denote values. \typeful programming" is part of the Haskell programming experience.) Examples of expressions include atomic values such as the integer 5. and Other Goodies Because Haskell is a purely functional language. and cannot be avoided. 2 Values.2. as well as structured values such as the list [1. we can think of types as sets of values. and the function \x -> x+1. Types.cant. type expressions are syntactic terms that denote type values (or just types).4). In any case. Every value has an associated type. since Haskell's type system is dierent and somewhat richer than most. the character 'a'.3] and the pair ('b'. (Intuitively. Examples of type expressions include the atomic types Integer (in.
All Haskell values are \. Integer->Integer (functions mapping Integer to Integer). as well as the structured types [Integer] (homogeneous lists of integers) and (Char. Char (characters).Integer) (character.
the function inc can be de. For example.ned by a series of equations.
ned by the single equation: inc n = n+1 An equation is an example of a declaration. with which we can declare an explicit typing for inc: inc :: Integer -> Integer We will have much more to say about function de. Another kind of declaration is a type signature declaration (x4.4.1).
nitions in Section 3. we will write: e1 For example. For pedagogical purposes. or \reduces. note that: ) e2 inc (inc 3) ) 5 Haskell's static type system de. when we wish to indicate that an expression e1 evaluates." to another expression or value e2 .
that is. For example. so the expression 'a'+'b' is ill-typed. Still. The static type system ensures that Haskell programs are type safe. an expression such as 1/0 is typable but its evaluation will result in an error at execution time.3). The main advantage of statically typed languages is wellknown: All type errors are detected at compile-time. that the programmer has not mismatched types in some way.nes the formal relationship between types and values (x4. the type system .1. we cannot generally add together two characters. Not all errors are caught by the type system.
The type system also ensures that user-supplied type signatures are correct. and also permits a compiler to generate more eÆcient code (for example.nds many program errors at compile time. no run-time type tags or tests are required). aids the user in reasoning about programs. since type signatures are a very eective form of documentation and help bring programming errors to light. Haskell's type system is powerful enough to allow us to avoid writing any type signatures at all.2 we say that the type system infers the correct types for us. In fact. Nevertheless. [The reader will note that we have capitalized identi. judicious placement of type signatures such as that we gave for inc is a good idea.
ers that denote speci.
c types. but not identi. such as Integer and Char.
such as inc. This is not just a convention: it is enforced by Haskell's lexical syntax. and fOO are all distinct identi. fOo. In fact.ers that denote values. the case of the other characters matters. too: foo.
] 2.ers.1 Polymorphic Types Haskell also incorporates polymorphic types|types that are universally quanti.
(8a)[a] is the family of types consisting of. for every type a. the type of lists of a.ed in some way over all types. Lists of 2 With a few exceptions to be described later. For example. Polymorphic type expressions essentially describe families of types. .
g.3]). however.4 2 VALUES.'c']). [1.. (Note.'b'. etc. AND OTHER GOODIES integers (e. TYPES.) [Identi. since there is no single type that contains both 2 and 'b'.2. even lists of lists of integers.'b'] is not a valid example. lists of characters (['a'. that [2. are all members of this family..
In other words. and thus we simply write [a] in the example above.cation. all type variables are implicitly universally quanti.
The list [1.2. and are a good vehicle for explaining the principles of polymorphism.ed.] Lists are a commonly used data structure in functional languages. where [] is the empty list and : is the in.3] in Haskell is actually shorthand for the list 1:(2:(3:[])).
x operator that adds its .
rst argument to the front of its second argument (a list). As an example of a user-de.3 Since : is right associative. we can also write this list as 1:2:3:[].
consider the problem of counting the number of elements in a list: length length [] length (x:xs) :: [a] -> Integer = 0 = 1 + length xs This de.ned function that operates on lists.
nition is almost self-explanatory. We can read the equations as saying: \The length of the empty list is 0. and the length of a list whose .
" (Note the naming convention used here. and should be read that way. binding x to the . The left-hand sides of the equations contain patterns such as [] and x:xs..) Although intuitive. xs is the plural of x. this example highlights an important aspect of Haskell that is yet to be explained: pattern matching.
De. the next equation is tried. an error results. If it fails. and if all equations fail.rst element and xs to the rest of the list). If the match succeeds. the right-hand side is evaluated and returned as the result of the application.
2. [Char]. The length function is also an example of a polymorphic function.3] length ['a'. Function head returns the . or [[Integer]].[2]. we will return to this issue in Section 4.[3]] ) ) ) 3 3 3 Here are two other useful polymorphic functions on lists that will be used later. and the user should become familiar with the various kinds of patterns that are allowed. length [1.ning functions by pattern matching is quite common in Haskell. for example [Integer].'c'] length [[1].'b'. It can be applied to a list containing elements of any type.
function tail returns all but the .rst element of a list.
.rst. respectively. 3 : and [] are like Lisp's cons and nil.
2 User-De.5 2.
these functions are not de.ned Types head head (x:xs) :: [a] -> a = x tail tail (x:xs) :: [a] -> [a] = xs Unlike length.
ned for all possible values of their argument. With polymorphic types. A runtime error occurs when these functions are applied to an empty list. we .
nd that some types are in a sense strictly more general than others in the sense that the set of values they de.
the type [a] is more general than [Char]. the latter type can be derived from the former by a suitable substitution for a. For example. Haskell's type system possesses two important properties: First. and second.3). In comparison to a monomorphically typed language such as C. With regard to this generalization ordering. the principal type can be inferred automatically (x4. every well-typed expression is guaranteed to have a unique principal type (explained below). In other words.ne is larger. the reader will .1.
An expression's or function's principal type is the least general type that.nd that polymorphism improves expressiveness. whereas something like [Integer]->Integer is too speci. \contains all instances of the expression". or even a are correct types. the principal type of head is [a]->a. and type inference lessens the burden of types on the programmer. intuitively. For example. but too general. [b]->a. a->a.
2 User-De. Miranda. ML. which forms the basis of the type systems of Haskell.c.4 and several other (mostly functional) languages. The existence of unique principal types is the hallmark feature of the Hindley-Milner type system. 2.
ned Types We can de.
An important prede.2. which we introduce via a series of examples (x4.ne our own types in Haskell using a data declaration.1).
ned type in Haskell is that of truth values: data Bool = False | True The type being de.
Similarly. and True and False are (also nullary) data constructors (or just constructors. and it has exactly two values: True and False. we might wish to de. Type Bool is an example of a (nullary) type constructor. for short).ned here is Bool.
ne a color type: data Color = Red | Green | Blue | Indigo | Violet Both Bool and Color are examples of enumerated types. since they consist of a .
Ltd.nite number of nullary data constructors. Here is an example of a type with just one data constructor: data Point a = Pt a a Because of the single constructor. since it is essentially 4 \Miranda" is a trademark of Research Software. . a type like Point is often called a tuple type.
AND OTHER GOODIES just a cartesian product (in this case binary) of other types. More importantly. however. such as Bool and Color.5 In contrast. Point is an example of a polymorphic type: for any type t. it de. are called (disjoint) union or sum types. TYPES. multi-constructor types.6 2 VALUES.
whereas the latter happens at compile-time and is part of the type system's process of ensuring type safety. (In the same sense. -> is a type constructor: given two types t and u. Similarly. using the list example given earlier. [Type constructors such as Point and data constructors such as Pt are in separate namespaces.nes the type of cartesian points that use t as the coordinate type. an expression such as Pt 'a' 1 is ill-typed because 'a' and 1 are of dierent types.0 Pt 'a' 'b' Pt True False :: Point Float :: Point Char :: Point Bool On the other hand. t->u is the type of functions mapping elements of type t to elements of type u. The Haskell syntax allows [] t to be written as [t]. It is important to distinguish between applying a data constructor to yield a value.) Note that the type of the binary data constructor Pt is a -> a -> Point a. the former happens at run-time and is how we compute things in Haskell. and applying a type constructor to yield a type. Given any type t we can \apply" [] to yield a new type [t].0 3. The Point type can now be seen clearly as a unary type constructor. and thus the following typings are valid: Pt 2. This allows the same name to be used for both a type constructor and data constructor. as in the following: data Point a = Point a a While this may seem a little confusing at . [] is also a type constructor. since from the type t it constructs a new type Point t.
1 Recursive Types Types can also be recursive. as in the type of binary trees: data Tree a = Leaf a | Branch (Tree a) (Tree a) Here we have de.2.rst. it serves to make the link between a type and its data constructor more obvious.] 2.
or internal nodes (\branches") containing (recursively) two sub-trees. When reading data declarations such as this. whereas Branch and Leaf are data constructors. the above declaration is essentially de.ned a polymorphic binary tree type whose elements are either leaf nodes containing a value of type a. Aside from establishing a connection between these constructors. remember again that Tree is a type constructor..
suppose we wish to de.ning some interesting (recursive) functions that use it. For example.
ne a function fringe that returns a list of all the elements in the leaves of a tree from left to right. It's usually helpful to write down the type of new functions .
for any type a. in this case we see that the type should be Tree a -> [a]. That is. A suitable de.rst. fringe is a polymorphic function that. maps trees of a into lists of a.
nition follows: fringe :: Tree a -> [a] fringe (Leaf x) = [x] fringe (Branch left right) = fringe left ++ fringe right Here ++ is the in.
x operator that concatenates two lists (its full de.
1). the fringe function is de.nition will be given in Section 9. As with the length example given earlier.
ned using pattern matching. except that here we see patterns involving user-de.
ned constructors: Leaf and Branch. [Note that the formal parameters are easily identi.
3 Type Synonyms For convenience.] 2.ed as the ones beginning with lower-case letters. Haskell provides a way to de.
e. Type synonyms are created using a type declaration (x4.Address) String None | Addr String Type synonyms do not de.ne type synonyms. names for commonly used types. i. Here are several examples: type type type data String Person Name Address = = = = [Char] (Name.2).2.
The new names are often shorter than the types they are synonymous with. the above examples highlight this. For example. integers. the type Person -> Name is precisely equivalent to (String. 2. but this is not the only purpose of type synonyms: they can also improve readability of programs by being more mnemonic. indeed. and characters.ne new types.b)] This is the type of \association lists" which associate values of type a with those of type b.Address) -> String. We can even give new names to polymorphic types: type AssocList a b = [(a.4 Built-in Types Are Not Special Earlier we introduced several \built-in" types such as lists. tuples. We have also shown how new user-de. but simply give new names for existing types.
ned types can be de.
are the built-in types in any way more special than the user-de.ned. Aside from special syntax.
The special syntax is for convenience and for consistency with historical convention. We can emphasize this point by considering what the type declarations would look like for these built-in types if in fact we were allowed to use the special syntax in de.ned ones? The answer is no. but has no semantic consequences.
ning them. For example. the Char type might be written as: .
. to .. | '1' | '2' | '3' | .. AND OTHER GOODIES data Char = 'a' | 'b' | 'c' | ...Haskell code! These constructor names are not syntactically valid.This is not valid -.8 2 VALUES. TYPES. | 'A' | 'B' | 'C' | . -.....
writing \pseudo-Haskell" code in this way helps us to see through the special syntax.. In any case.x them we would have to write something like: data Char = Ca | Cb | Cc | . they are quite unconventional for representing characters.. | C1 | C2 | C3 | ..... . Thinking of Char in this way makes it clear that we can pattern-match against characters in function de. | CA | CB | CC | .. We see now that Char is just an enumerated type consisting of a large number of nullary constructors.. Even though these constructors are more concise.
nitions. the characters -.] Similarly. just as we would expect to be able to do so for any of a type's constructors. we could de.and all subsequent characters to the end of the line are ignored. [This example also demonstrates the use of comments in Haskell. Haskell also permits nested comments which have the form {-: : :-} and can appear anywhere (x2.2).
ne Int (.
.. are the maximum and minimum . say.more pseudo-code data Integer = .. where -65532 and 65532. -2 | -1 | 0 | 1 | 2 .. | 65532 -.. | -1 | 0 | 1 | ....xed precision integers) and Integer by: data Int = -65532 | .
Int is a much larger enumeration than Char.xed precision integers for a given implementation. but it's still .
the pseudo-code for Integer is intended to convey an in.nite! In contrast.
Tuples are also easy to de.nite enumeration.
-.b. = (a. .c) = (a.b.b. .d) .c) data (a.d) .b. .b) data (a.ne playing this game: data (a.c.c.b) = (a. .more pseudo-code Each declaration above de.
with (...nes a tuple type of a particular length. The vertical dots after the last declaration are intended to convey an in.) playing a role in both the expression syntax (as data constructor) and type-expression syntax (as type constructor).
Lists are also easily handled. re ecting the fact that tuples of all lengths are allowed in Haskell.nite number of such declarations. and : is the in.more pseudo-code We can now see clearly what we described about lists earlier: [] is the empty list. and more interestingly. they are recursive: data [a] = [] | a : [a] -.
x .
4 Built-in Types Are Not Special list constructor.) The type of [] is [a]. (: is right associative.2. [The way \:" is de.3] must be equivalent to the list 1:2:3:[]. thus [1. and the type of : is a->[a]->[a].9 2.
ned here is actually legal syntax|in.
x constructors are permitted in data declarations. and are distinguished from in.
x operators (for pattern-matching purposes) by the fact that they must begin with a \:" (a property trivially satis.
] At this point the reader should note carefully the dierences between tuples and lists. which the above de.ed by \:").
note the recursive nature of the list type whose elements are homogeneous and of arbitrary length.nitions make abundantly clear. In particular. and the non-recursive nature of a (particular) tuple type whose elements are heterogeneous and of .
Besides generators. of which more than one is allowed.3). lists are pervasive in Haskell.tn )." The similarity to set notation is not a coincidence. : : : . if xs is [1. Aside from the constructors for lists just discussed. n 2. Guards place constraints on the elements generated.ys ] This list comprehension forms the cartesian product of the two lists xs and ys. if ti is the type of ei . : : : .(1.y) | x <. there is yet more syntactic sugar to aid in their creation.4.4)].4].xs.2] and ys is [3.xs is called a generator. The typing rules for tuples and lists should now also be clear: For (e1 . 2.4). as in: [ (x.en ].1 List Comprehensions and Arithmetic Sequences As with Lisp dialects. n 0. For example.xs ] This expression can intuitively be read as \the list of all f x such that x is drawn from xs. here is a concise de.e2 . y <. each ei must have the same type t.xed length.t2 .en ). thus. boolean expressions called guards are permitted. Haskell provides an expression known as a list comprehension that is best explained by example: [ f x | x <. The elements are selected as if the generators were \nested" from left to right (with the rightmost generator varying fastest). For [e1 . the result is [(1. and as with other functional languages. The phrase x <. : : : .3).(2.(2. then the type of the tuple is (t1 . and the type of the list is [t].e2 .
3.7.] ) ) ) [1..9] [1.10] [1..7.10] [1.nition of everybody's favorite sorting algorithm: quicksort [] quicksort (x:xs) = = ++ ++ [] quicksort [y | y <.3.3. y>=x] To further support the use of lists. y<x ] [x] quicksort [y | y <.10] [1.9.xs.5.2.3.5. . Haskell has special syntax for arithmetic sequences. which are best explained by a series of examples: [1.. (in.8.9.4.7.5..6..xs.3.
nite sequence) More will be said about arithmetic sequences in Section 8.2. and \in.
nite lists" in Section 3.4. .
the type of "hello" is String. we note that the literal string "hello" is actually shorthand for the list of characters ['h'.10 3 FUNCTIONS 2.'o'].'l'. Indeed. where String is a prede.'l'.4.2 Strings As another example of syntactic sugar for built-in types.'e'.
ned type synonym (that we gave as an earlier example): type String = [Char] This means we can use prede.
one would expect functions to play a major role.ned polymorphic list functions to operate on strings. First. In this section. consider this de. and indeed they do. For example: "hello" ++ " world" 3 "hello world" ) Functions Since Haskell is a functional language. we look at several aspects of functions in Haskell.
Indeed. In other words. and is equivalent to (add e1 ) e2 .nition of a function which adds its two arguments: add add x y :: Integer -> Integer -> Integer = x + y This is an example of a curried function.e. Integer->Integer->Integer. we can de. which is equivalent to Integer->(Integer->Integer).6 An application of add has the form add e1 e2 . This is consistent with the type of add. applying add to one argument yields a new function which is then applied to the second argument. -> associates to the right. i. using add. since function application associates to the left.
ne inc in a dierent way from earlier: inc = add 1 This is an example of the partial application of a curried function..
x operator.] The map function is polymorphic and its type indicates clearly that its . and thus the right-hand side of the second equation parses as (f x) : (map f xs).
we could use a tuple. As an example of the use of map.rst argument is a function.4] 6 The name curry derives from the person who popularized the idea: Haskell Curry.3. To get the eect of an uncurried function. as in: add (x.y) = x + y But then we see that this version of add is really just a function of one argument! . we can increment the elements in a list: map (add 1) [1. note also that the two a's must be instantiated with the same type (likewise for the b's).3] ) [2.2.
11 3.1 Lambda Abstractions These examples demonstrate the .
rst-class nature of functions. 3.1 Lambda Abstractions Instead of using equations to de. which when used in this way are usually called higher-order functions.
ne functions. we can also de.
2 In.ne them \anonymously" via a lambda abstraction. given that x has type t1 and exp has type t2 . In fact. the equations: inc x add x y = x+1 = x+y are really shorthand for: inc add = \x -> x+1 = \x y -> x+y We will have more to say about such equivalences later. In general. a function equivalent to inc could be written as \x -> x+1. For example. Similarly. then \x->exp has type t1 ->t2 . the function add is equivalent to \x -> \y -> x+y. 3. Nested lambda abstractions such as this may be written using the equivalent shorthand notation \x y -> x+y.
x Operators In.
and can also be de.x operators are really just functions.
here is a de.ned using equations. For example.
in.nition of a list concatenation operator: (++) [] ++ ys (x:xs) ++ ys :: [a] -> [a] -> [a] = ys = x : (xs++ys) [Lexically.
" as opposed to normal identi.x operators consist entirely of \symbols.
Haskell has no pre.4).ers which are alphanumeric (x2.
with the exception of minus (-).x operators. which is both in.
x and pre.
] As another example. an important in.x.
1 Sections Since in.) f . g :: (b->c) -> (a->b) -> (a->c) = \ x -> f (g x) 3.2.x operator on functions is that for function composition: (.
In Haskell the partial application of an in.x operators are really just functions. it makes sense to be able to partially apply them as well.
For example: (x+) (+y) (+) \y -> x+y \x -> x+y \x y -> x+y .x operator is called a section.
12 3 FUNCTIONS [The parentheses are mandatory.] The last form of section given above essentially coerces an in.
and is handy when passing an in.x operator into an equivalent functional value.
2.x operator as an argument to a function. We can now see that add de.3] (the reader should verify that this returns a list of functions!). It is also necessary when giving a function type signature.) given earlier. as in the examples of (++) and (. as in map (+) [1.
and inc is just (+1)! Indeed.ned earlier is just (+). these de.
nitions would do just .
ne: inc add = (+ 1) = (+) We can coerce an in.
x operator into a functional value. but can we go the other way? Yes|we simply enclose an identi.
x `add` y is the same as add x y.er bound to a functional value in backquotes.7 Some functions read better this way. For example. An example is the prede.
" [There are some special rules regarding sections involving the pre. the expression x `elem` xs can be read intuitively as \x is an element of xs.ned list membership predicate elem.
x/in.
4). the reader may be confused at having so many ways to de.x operator -.x3. see (x3.] At this point.5.
in the treatment of in. and partly re ects the desire for consistency (for example.ne a function! The decision to provide these mechanisms partly re ects historical conventions.
regular functions).2 Fixity Declarations A .2.x vs. 3.
xity declaration can be given for any in.
x operator or constructor (including those made from ordinary identi.
This declaration speci. such as `elem`).ers.
es a precedence level from 0 to 9 (with 9 being the strongest. and left-. normal application is assumed to have a precedence level of 10). the . For example. right-. or non-associativity.
are: infixr 5 ++ infixr 9 .xity declarations for ++ and . the . Both of these specify right-associativity.
the other 9.rst with a precedence level of 5. Left associativity is speci.
Also.ed via infixl. the . and non-associativity by infix.
xity of more than one operator may be speci.
ed with the same .
If no .xity declaration.
(See x5. it defaults to infixl 9.xity declaration is given for a particular operator.9 for a detailed de.
nition of the associativity rules.3 Functions are Non-strict Suppose bot is de.) 3.
i. not apostrophes as used in the syntax of characters.ned by: 7 Note carefully that add is enclosed in backquotes.e. whereas `f` is an in. 'f' is a character.
Fortunately. .x operator. most ASCII terminals distinguish these much better than the font used in this manuscript.
13 3.4 \In.
such as an end-of-. bot is a non-terminating expression. Errors encountered by the I/O system. such as 1/0. we denote the value of a nonterminating expression as ? (read \bottom").nite" Data Structures bot = bot In other words. Expressions that result in some kind of a run-time error. also have this value. Such an error is not recoverable: programs will not continue past these errors. Abstractly.
the constant 1 function.le error. when applied to a nonterminating expression. are recoverable and are handled in a dierent manner. Much more will be said about exceptions in Section 7.) A function f is said to be strict if. de. For most programming languages. it also fails to terminate. all functions are strict. But this is not so in Haskell. In other words. consider const1. As a simple example. (Such an I/O error is really not an error at all but rather an exception. f is strict i the value of f bot is ?.
Since error and nonterminating values are semantically the same in Haskell. An important example of this is a possibly in. Operationally speaking. the above argument also holds for errors. Computationally expensive values may be passed as arguments to functions without fear of them being computed if they are not needed.ned by: const1 x = 1 The value of const1 bot in Haskell is 1. For this reason. The main advantage is that they free the programmer from many concerns about evaluation order. since const1 does not \need" the value of its argument. const1 (1/0) also evaluates properly to 1. it never attempts to evaluate it. or \by need". and are said to evaluate their arguments \lazily". For example. and thus never gets caught in a nonterminating computation. non-strict functions are also called \lazy functions". Non-strict functions are extremely useful in a variety of contexts.
nite data structure. Another way of explaining non-strict functions is that Haskell computes using de.
Read a declaration such as v = 1/0 as `de.nitions rather than the assignments found in traditional languages.
Only if the value (de.ne v as 1/0' instead of `compute 1/0 and store the result in v'.
By itself. this declaration does not imply any computation.nition) of v is needed will the division by zero error occur. De. Programming using assignments requires careful attention to the ordering of the assignments: the meaning of the program depends on the order in which the assignments are executed.
4 \In. are much simpler: they can be presented in any order without aecting the meaning of the program.nitions. in contrast. 3.
since constructors are really just a special kind of function (the distinguishing feature being that they can be used in pattern matching).nite" Data Structures One advantage of the non-strict nature of Haskell is that data constructors are non-strict. Non-strict constructors permit the de. the constructor for lists. too. (:). This should not be surprising. is non-strict. For example.
nition of (conceptually) in.
nite data structures. Here is an in..
^ is the in.nite list of squares: squares = map (^2) (numsfrom 0) (Note the use of a section.
x exponentiation operator.) Of course. eventually we expect to extract some .
nite portion of the list for actual computation. and there are lots of prede.
ned functions in Haskell that do this sort of thing: take. filter. takeWhile. The de. and others.
nition of Haskell includes a large set of built-in functions and types| this is called the \Standard Prelude". see the portion named PreludeList for many useful functions involving lists. take removes the . For example. The complete Standard Prelude is included in Appendix A of the Haskell report.
9.1.4.16] The de.rst n elements from a list: take 5 squares ) [0.
thus saving space. since an implementation can be expected to implement the list as a true circular structure.nition of ones above is an example of a circular list. For another example of the use of circularity. the Fibonacci sequence can be computed eÆciently as the following in. In most circumstances laziness has an important impact on eÆciency.
y) : zip xs ys = [] Note how fib.
nite list. is de.
For another application of in." Indeed.ned in terms of itself. we can draw a picture of this computation as shown in Figure 1. as if it were \chasing its tail.
4.nite lists. see Section 4. .
Indeed.15 3.5 The Error Function 3. Thus this function is useful when we wish to terminate a program when something has \gone wrong. semantically that is exactly what value is always returned by error (recall that all errors have value ?). the actual de. we can expect that a reasonable implementation will print the string argument to error for diagnostic purposes.5 The Error Function Haskell has a built-in function called error whose type is String->a. This is a somewhat odd function: From its type it looks as if it is returning a value of a polymorphic type about which it knows nothing." For example. there is one value \shared" by all types: ?. However. since it never receives a value of that type as an argument! In fact.
nition of head taken from the Standard Prelude is: head (x:xs) head [] 4 = x = error "head{PreludeList}: head []" Case Expressions and Pattern Matching Earlier we gave several examples of pattern matching in de.
8 Patterns are not \.17).ning functions|for example length and fringe. In this section we will look at the pattern-matching process in greater detail (x3.
rst-class." there is only a .
xed set of dierent kinds of patterns. both length and fringe de. We have already seen several examples of data constructor patterns.
the former on the constructors of a \built-in" type (lists). the latter on a userde.ned earlier use such patterns.
matching is permitted using the constructors of any type. user-de.ned type (Tree). Indeed.
etc. Technically speaking. Char. Patterns such as formal parameters that never fail to match are said to be irrefutable. here's a contrived function that matches against a tuple of \constants:" contrived :: ([a]. strings. two of which we will introduce now (the other we will delay until Section 4. For this reason patterns in any one equation are not allowed to have more than one occurrence of the same formal parameter (a property called linearity x3.ned or not.3. This includes tuples. formal parameters9 are also patterns|it's just that they never fail to match a value. in contrast to refutable patterns which may fail to match. 2. Float). 8 Pattern matching in Haskell is dierent from that found in logic programming languages such as Prolog. For example. The pattern used in the contrived example above is refutable. whereas Prolog allows \two-way" matching (via uni. True) = False This example also demonstrates that nesting of patterns is permitted (to arbitrary depth). numbers.0). (Int.4).4. it can be viewed as \one-way" matching. String. There are three other kinds of irrefutable patterns. x4. x3. "hi". 'b'. characters. the formal parameter is bound to the value it is being matched against. As a \side eect" of the successful match. (1.17. in particular.2). Bool) -> Bool contrived ([].
along with implicit backtracking in its evaluation mechanism. 9 The Report calls these variables. .cation).
a function that duplicates the .16 4 CASE EXPRESSIONS AND PATTERN MATCHING As-patterns. Sometimes it is convenient to name a pattern for use on the right-hand side of an equation. For example.
we might prefer to write x:xs just once. which we can achieve using an as-pattern as follows:10 f s@(x:xs) = x:s Technically speaking. as-patterns always result in a successful match. the functions head and tail de. of course. Another common situation is matching against a value we really care nothing about.rst element in a list might be written as: f (x:xs) = x:x:xs (Recall that \:" associates to the right. fail. For example. although the sub-pattern (in this case x:xs) could. To improve readability.) Note that x:xs appears both as a pattern on the left-hand side. and an expression on the right-hand side. Wild-cards.
de. 4. But what drives the overall process? In what order are the matches attempted? What if none succeeds? This section addresses these questions. how some are refutable. and the next equation is then tried. If all equations fail. if [1. (Recall that bot. left-to-right. for this reason more than one is allowed in an equation. the value of the function application is ?. Each wild-card independently matches anything. each binds nothing. succeed or diverge.2] is matched against [0. but in contrast to a formal parameter. so the result is a failed match. etc. then 1 fails to match 0.1 can be rewritten as: head (x:_) tail (_:xs) = x = xs in which we have \advertised" the fact that we don't care what a certain part of the input is. The matching process itself occurs \top-down. Pattern matching can either fail.1 Pattern-Matching Semantics So far we have discussed how individual patterns are matched.ned in Section 2. some are irrefutable. and results in a run-time error." Failure of a pattern anywhere in one equation results in failure of the whole equation.bot]. Divergence occurs when a value needed by the pattern contains an error (?). For example. A successful match binds the formal parameters in the pattern.
ned earlier.0]. is a variable bound to ?. ?).) But if [1. as in this de. The other twist to this set of rules is that top-level patterns may also have a boolean guard. then matching 1 against bot causes divergence (i.2] is matched against [bot.e.
and the . they are evaluated top-down.nition of a function that forms an abstract version of a number's sign: sign x | x > 0 | x == 0 | x < 0 = 1 = 0 = -1 Note that a sequence of guards may be provided for the same pattern. as with patterns.
. 10 Another advantage to doing this is that a naive implementation might completely reconstruct x:xs rather than re-use the value being matched against.rst that evaluates to True results in a successful match.
2 An Example 4. For example.17 4.2 An Example The pattern-matching rules can have subtle eects on the meaning of functions. consider this de..
ned" with respect to its second argument. whereas take1 is more de.
ned with respect to its .
rst. It is diÆcult to say in this case which de.
nition is better. it may make a dierence. (The Standard Prelude includes a de. Just remember that in certain applications.
) 4.nition corresponding to take. In many circumstances we don't wish to de.3 Case Expressions Pattern matching provides a way to \dispatch control" based on structural properties of a value.
but so far we have only shown how to do pattern matching in function de.ne a function every time we need to do this.
Haskell's case expression provides a way to solve this problem. Indeed. the meaning of pattern matching in function de.nitions.
nitions is speci.
In particular.ed in the Report in terms of case expressions. a function de. which are considered more primitive.
is semantically equivalent to: f x1 x2 : : : xk = case (x1. : : : .nition of the form: f p11 : : : p1k = e1 ::: f pn1 : : : pnk = en where each pij is a pattern. : : : . p1k ) -> e1 ::: (pn1 . pnk ) -> en where the xi are new identi. xk) of (p11 . : : : .
see x4. (For a more general translation that includes guards.2.) For example.ers. the de.4.
nition of take given earlier is equivalent to: .
x:xs) -> x : take (n-1) xs A point not made earlier is that. the types of the right-hand sides of a case expression or set of equations comprising a function de._) -> [] (_.[]) -> [] (n. for type correctness.18 4 CASE EXPRESSIONS AND PATTERN MATCHING take m ys = case (m.ys) of (0.
more precisely. they must all share a common principal type. The pattern-matching rules for case expressions are the same as we have given for function de.nition must all be the same.
other than to note the convenience that case expressions oer. In Haskell. if-then-else when viewed as a function has type Bool->a->a->a. In other words. Lazy patterns are irrefutable: matching a value v against ~pat always succeeds.4 Lazy Patterns There is one other kind of pattern allowed in Haskell. Indeed.nitions. conditional expressions have the familiar form: if e1 then e2 else e3 which is really short-hand for: case e1 of True -> e2 False -> e3 From this expansion it should be clear that e1 must have type Bool. and has the form ~pat. so there is really nothing new to learn here. there's one use of a case expression that is so common that it has special syntax: the conditional expression. if an identi. regardless of pat. 4. and e2 and e3 must have the same (but otherwise arbitrary) type. Operationally speaking. It is called a lazy pattern.
Lazy patterns are useful in contexts where in. and ? otherwise. it will be bound to that portion of the value that would result if v were to successfully match pat.er in pat is later \used" on the right-hand-side.
nite data structures are being de.
ned recursively. in. For example.
and in this context the in.nite lists are an excellent vehicle for writing simulation programs.
and server replies to each request with some kind of response. This situation is shown pictorially in Figure 2.. Let us further assume that the structure of the server and client look something like this: client init (resp:resps) = init : client (next resp) resps server (req:reqs) = process req : server reqs .) Using streams to simulate the message sequences. where client sends a sequence of requests to server. (Note that client also takes an initial message as argument.
and process is a function that processes a request from the client. determines the next request.19 4. Unfortunately. this program has a serious problem: it will not produce any output! The problem is that client. attempts a match on the response list before it has submitted its .4 Lazy Patterns Figure 2: Client-Server Simulation where we assume that next is a function that. as used in the recursive setting of reqs and resps. given a response from the server. returning an appropriate response.
rst request! In other words." One way to . the pattern matching is being done \too early.
x this is to rede.
this solution does not read as well as that given earlier.. the match will immediately succeed.
rst response to be generated. if we de. and the recursion takes care of the rest. the engine is now \primed". As an example of this program in action.
1.ne: init next resp process req then we see that: = 0 = resp = req+1 take 10 reqs ) [0.4.2.8.7.6.9] As another example of the use of lazy patterns. consider the de.5.3.
since it is available in \destructured" form on the left-hand side as tfib.nition of Fibonacci given earlier: fib = 1 : 1 : [ a+b | (a.zip fib (tail fib) ] We might try rewriting this using an as-pattern: fib@(1:tfib) = 1 : 1 : [ a+b | (a.zip fib tfib ] This version of fib has the (small) advantage of not using tail on the right-hand side.b) <.b) <.e. [This kind of equation is called a pattern binding because it is a top-level equation in which the entire left-hand side is a pattern. both fib and tfib become bound within the scope of the declaration. i.] .
5 Lexical Scoping and Nested Forms It is often desirable to create a nested scope within an expression. re ecting the most common behavior expected of pattern bindings. pattern bindings are assumed to have an implicit ~ in front of them. however.6 Layout The reader may have been wondering how it is that Haskell programs avoid the use of semicolons.20 4 CASE EXPRESSIONS AND PATTERN MATCHING Now. The same properties and constraints on bindings in let expressions apply to those in where clauses. which requires a where clause: f x y | y>z | y==z | y<z where z = x*x = . Where Clauses. or some other kind of terminator. some kind of \block-structuring" form. whereas a where clause is not|it is part of the syntax of function declarations and case expressions. to mark the end of equations.. declarations.e. function bindings. they carry an implicit ~).. As a simple example.. for the purpose of creating local bindings not seen elsewhere|i. and avoiding some anomalous situations which are beyond the scope of this tutorial. it does. 4. These two forms of nested scope seem very similar. Haskell's let expressions are useful whenever a nested set of bindings is required. = . For example. but remember that a let expression is an expression. consider: let y = a*b f x = (x+y)/y in f c + f d The set of bindings created by a let expression is mutually recursive. In Haskell there are two ways to achieve this: Let Expressions. Sometimes it is convenient to scope bindings over several guarded equations. consider this let expression from the last section: let y = a*b f x = (x+y)/y in f c + f d ..e. which only scopes over the expression which it encloses. we should be led to believe that this program will not generate any output. Curiously. Thus we see that lazy patterns play an important role in Haskell. etc. and pattern bindings. A where clause is only allowed at the top level of a set of equations or case expression. using the same reasoning as earlier. and the reason is simple: in Haskell. Note that this cannot be done with a let expression.. if only implicitly.. 4. and pattern bindings are treated as lazy patterns (i. = . The only kind of declarations permitted are type signatures.
etc.7. the next character following any of the keywords where. f x = (x+y)/y } in f c + f d Note the explicit curly braces and semicolons. or of is what determines the starting column for the declarations in the where. this is a valid expression: let y = a*b. Thus we can begin the declarations on the same line as the keyword.11 Layout is actually shorthand for an explicit grouping mechanism. let. to be discussed later. z = a/b f x = (x+y)/z in f c + f d For another example of the expansion of layout into explicit delimiters.21 How does the parser know not to parse this as: let y = a*b f x = (x+y)/y in f c + f d ? The answer is that Haskell uses a two-dimensional syntax called layout that essentially relies on declarations being \lined up in columns. but in practice. The use of layout greatly reduces the syntactic clutter associated with declaration lists. for example. or case expression being written (the rule also applies to where used in the class and instance declarations to be introduced in Section 5). 5 Type Classes and Overloading There is one . Just remember two things: First.7. note that y and f begin in the same column. which deserves mention because it can be useful under certain circumstances. use of layout is rather intuitive. and its use is encouraged. thus enhancing readability." In the above example. also uses layout). let. (The do keyword. xB.3). Second. the next line. The let example above is equivalent to: let { y = a*b . It is easy to learn. One way in which this explicit notation is useful is when more than one declaration is desired on a line. just be sure that the starting column is further to the right than the starting column associated with the immediately surrounding clause (otherwise it would be ambiguous). The \termination" of a declaration happens when something appears at or to the left of the starting column associated with that binding form. The rules for layout are spelled out in detail in the Report (x2. see x2.
nal feature of Haskell's type system that sets it apart from other programming languages. Here are some examples of ad hoc polymorphism: 11 Haskell observes the convention that tabs count as 8 blanks. . The kind of polymorphism that we have talked about so far is commonly called parametric polymorphism. There is another kind called ad hoc polymorphism. better known as overloading. thus care must be taken when using an editor which may observe some other convention.
are often used to represent both . etc. 2.22 5 TYPE CLASSES AND OVERLOADING The literals 1.
Numeric operators such as + are often de.xed and arbitrary precision integers.
The equality operator (== in Haskell) usually works on numbers and many other (but not all) types. Note that these overloaded behaviors are dierent for each type (in fact the behavior is sometimes unde.ned to work on many dierent kinds of numbers.
There are many types for which we would like equality de. but important. Let's start with a simple. or error). In Haskell. type classes provide a structured way to control ad hoc polymorphism. example: equality. for example. whereas in parametric polymorphism the type truly does not matter (fringe.ned. really doesn't care what kind of elements are found in the leaves of a tree). or overloading.
but some for which we would not.ned.12 To highlight the issue. whereas we often want to compare two lists for equality. For example. comparing the equality of functions is generally considered computationally intractable. consider this de.
1.nition of the function elem which tests for membership in a list: x `elem` [] x `elem` (y:ys) = False = x==y || (x `elem` ys) [For the stylistic reason we discussed in Section 3. we have chosen to de.
ne elem in in.
x form. == and || are the in.
even though we just said that we don't expect == to be de.] Intuitively speaking. the type of elem \ought" to be: a->[a]->Bool.x operators for equality and logical or. respectively. But this would imply that == has type a->a->Bool.
Furthermore. even if == were de. as we have noted earlier.ned for all types.
comparing two lists for equality is very dierent from comparing two integers. In this sense. and to provide de. Type classes conveniently solve both of these problems. They allow us to declare which types are instances of which class.ned on all types. we expect == to be overloaded to carry on these various tasks.
For example. let's de.nitions of the overloaded operations associated with a class.
ne a type class containing an equality operator: class Eq a where (==) :: a -> a -> Bool Here Eq is the name of the class being de.
of the appropriate type. and == is the single operation in the class. de. This declaration may be read \a type a is an instance of the class Eq if there is an (overloaded) operation ==.ned.
ned on it." (Note that == is only de.
the eect of the above class declaration is to assign the following type to ==: (==) 12 :: (Eq a) => a -> a -> Bool The kind of equality we are referring to here is \value equality. and thus does not sit well in a purely functional language. and is called a context. Pointer equality is not referentially transparent. Contexts are placed at the front of type expressions." and opposed to the \pointer equality" found. For example. for example. but rather it expresses a constraint on a type. with Java's ==.) The constraint that a type a must be an instance of the class Eq is written Eq a. .ned on pairs of objects of the same type. Thus Eq a is not a type expression.
== has type a->a->Bool". This is just what we want|it expresses the fact that elem is not de. elem has type a->[a]->Bool". and indeed the constraint imposed by the context propagates to the principal type for elem: elem :: (Eq a) => a -> [a] -> Bool This is read. \For every type a that is an instance of the class Eq.23 This should be read. This is the type that would be used for == in the elem example. \For every type a that is an instance of the class Eq.
and the actual behavior of == on each of those types? This is done with an instance declaration.ned on all types. But how do we specify which types are instances of the class Eq. For example: instance Eq Integer where x == y = x `integerEq` y The de. just those for which we know how to compare elements for equality. So far so good.
nition of == is called a method. just as for any other function de..
". If the context were omitted from the instance declaration. contains a wealth of useful examples of type classes.rst line|this is necessary because the elements in the leaves (of type a) are compared for equality in the second line. a static type error would result. a class Eq is de. The Haskell Report. especially the Prelude. The additional constraint is essentially saying that we can compare trees of a's for equality as long as we know how to compare a's for equality.
ned that is slightly larger than the one de.
ned earlier: class Eq a where (==). then the default one de. in this case for the inequality operation /=. (/=) x /= y :: a -> a -> Bool = not (x == y) This is an example of a class with two operations. the other for inequality. If a method for a particular operation is omitted in an instance declaration. one for equality. It also demonstrates the use of a default method.
is used instead. the three instances of Eq de. if it exists.ned in the class declaration. For example.
yielding just the right de.ned earlier will work perfectly well with the above class declaration.
.nition of inequality that we want: the logical negation of equality.
24 5 TYPE CLASSES AND OVERLOADING Haskell also supports a notion of class extension. we may wish to de. For example.
We say that Eq is a superclass of Ord (conversely. and any type which is an instance of Ord must also be an instance of Eq. (>=). (>) :: a -> a -> Bool max. min :: a -> a -> a Note the context in the class declaration.ne a class Ord which inherits all of the operations in Eq. (In the next Section we give a fuller de. Ord is a subclass of Eq). but in addition has a set of comparison operations and minimum and maximum functions: class (Eq a) => Ord a where (<). (<=).
nition of Ord taken from the Prelude.) One bene.
the principal typing of quicksort de. For example.t of such class inclusions is shorter contexts: a type expression for a function that uses operations from both the Eq and Ord classes can use the context (Ord a). rather than (Eq a. methods for subclass operations can assume the existence of methods for superclass operations. since Ord \implies" Eq. More importantly. the Ord declaration in the Standard Prelude contains this default method for (<): x < y = x <= y && x /= y As an example of the use of Ord. Ord a).
ned in Section 2.1 is: quicksort :: (Ord a) => [a] -> [a] In other words.4. This typing for quicksort arises because of the use of the comparison operators < and >= in its de. quicksort only operates on lists of values of ordered types.
the declaration class (Eq a. creates a class C which inherits operations from both Eq and Show. They share the same namespace as ordinary variables. Contexts are also allowed in data declarations. see x4. Class methods are treated as top level declarations in Haskell. Haskell also permits multiple inheritance. Class methods may have additional class constraints on any type variable except the one de.nition. Show a) => C a where . a name cannot be used to denote both a class method and a variable or methods in dierent classes. since classes may have more than one superclass.2... For example.1.
we have been using \. So far. For example. However. the method m could not place any additional class constraints on type a.ning the current class. in this class: class C a where m :: Show b => a -> b the method m requires that type b is in class Show. These would instead have to be part of the context in the class declaration.
But Tree by itself is a type constructor. For example. the type constructor Tree has so far always been paired with an argument. and as such takes a type as an argument and returns a type as a result. There are . as in Tree Integer (a tree containing Integer values) or Tree a (representing the family of trees containing a values).rst-order" types.
is an instance of Functor.. The type T a b is parsed as (T a) b. To begin. Thus we would expect it to be bound to a type such as Tree which can be applied to an argument. (. but such \higher-order" types can be used in class declarations. (->) is a type constructor. and so on. Type expressions are classi. and other data types. For functions. how does Haskell detect malformed type expressions? The answer is a second type system which ensures the correctness of types! Each type has an associated kind which ensures that the type is used correctly. Similarly.. the types [a] and [] a are the same. the type Tree Int Int should produce some sort of an error since the Tree type takes only a single argument. But what about errors due to malformed type expressions? The expression (+) 1 2 3 results in a type error since (+) takes only two arguments.).25 no values in Haskell that have this type. system detects typing errors in expressions.] As we know. This capability is quite useful. allowing functions such as fmap to work uniformly over arbitrary trees. and here demonstrates the ability to describe generic \container" types. For tuples. lists. So. the type constructors (as well as the data constructors) are (. Types such as tuples which use special syntax can be written in an alternative style which allows currying. [Type applications are written in the same manner as function applications. Similarly. the types f -> g and (->) f g are the same. rather than Tree a.).
. The compiler infers kinds before doing type checking without any need for `kind declarations'. since Integer has the kind . If 1 and 2 are kinds. the kind of v must be . then 1 ! 2 is the kind of types that take a type of kind 1 and return a type of kind 2 . a kinding error would result from an declaration such as instance Functor Integer where .ed into dierent kinds which take one of two possible forms: The symbol represents the kind of type associated with concrete data objects. See x4.. if the value v has type t . the type Tree Int has the kind . Kinds do not appear directly in Haskell programs.1.1 and x4. Members of the Functor class must all have the kind ! .6 for more information about kinds. Kinds stay in the background of a Haskell program except when an erroneous type signature leads to a kind error. That is. Kinds are simple enough that compilers should be able to provide descriptive error messages when kind con icts occur. The type constructor Tree has the kind ! . .
The . it is worth pointing out two other views of Haskell's type classes. Before going on to further examples of the use of type classes.26 5 TYPE CLASSES AND OVERLOADING A Dierent Perspective.
A particular object may be an instance of a class. and permitting inheritance of operations/methods. simply substituting type class for class. A default method may also be associated with an operation. and in particular there is no notion of an object's or type's internal mutable state. it should be clear that types are not objects. methods are not \looked up" at runtime but are simply passed as higher-order functions. forming notions of superclasses and subclasses. and type for object.rst is by analogy with objectoriented programming (OOP). A dierent perspective can be gotten by considering the relationship between parametric and ad hoc polymorphism. Classes may be arranged hierarchically. In the following general statement about OOP. and will have a method corresponding to each operation. An advantage over some OOP languages is that methods in Haskell are completely type-safe: any attempt to apply a method to a value whose type is not in the required class will be detected at compile time instead of at runtime. In other words. We have shown how parametric polymorphism is useful in de. yields a valid summary of Haskell's type class mechanism: \Classes capture common sets of operations." In contrast to OOP.
that universal quanti. however. Sometimes.ning families of types by universally quantifying over all types.
such as those types whose elements can be compared for equality. The classes used by Haskell are similar to those used in other object-oriented languages such as C++ and Java. we can think of parametric polymorphism as a kind of overloading too! It's just that the overloading occurs implicitly over all types instead of a constrained set of types (i. Type classes can be seen as providing a structured way to do just this. there are some signi. Indeed. Comparison to Other Languages.e.cation is too broad|we wish to quantify over some smaller set of types. a type class). However.
cant dierences: Haskell separates the de.
nition of a type from the de.
nition of the methods associated with that type. A class in C++ or Java usually de.
nes both a data structure (the member variables) and the functions associated with the structure (the methods). In Haskell.. a Haskell class declaration de. Haskell classes are roughly similar to a Java interface.
nes a protocol for using an object rather than de.
Haskell does not support the C++ overloading style in which functions with dierent types share a common name. . there is no universal base class such as Object which values can be projected into or out of.ning an object itself. The type of a Haskell object cannot be implicitly coerced.
the module system must be used to hide or reveal components of a class. through the type system. 6 Types. Instead. such information is attached logically instead of physically to values. In Haskell. There is no access control (such as public or private class constituents) built into the Haskell class system. 6. Again Here we examine some of the more advanced aspects of type declarations.1 The Newtype Declaration A common programming practice is to de.27 C++ and Java attach identifying information (such as a VTable) to the runtime representation of an object.
This would not be possible if Natural were de. Indeed.fromNatural y in if r < 0 then error "Unnatural subtraction" else toNatural r x * y = toNatural (fromNatural x * fromNatural y) Without this declaration. . For example. In Haskell. the newtype declaration creates a new type from an existing one. whose only constructor contains a single Integer. the whole purpose of this type is to introduce a dierent Num instance.y = let r = fromNatural x .ne a type whose representation is identical to an existing one but which has a separate identity in the type system. Natural would not be in Num. natural numbers can be represented by the type Integer using the following declaration: newtype Natural = MakeNatural Integer This creates an entirely new type. Instances declared for the old type do not carry over to the new one. Natural.
. However.ned as a type synonym of Integer. The use of newtype avoids the extra level of indirection (caused by laziness) that the data declaration would introduce. the data declaration incurs extra overhead in the representation of Natural values. All of this works using a data declaration instead of a newtype declaration.
AGAIN See section 4.28 6 TYPES. the newtype declaration uses the same syntax as a data declaration with a single constructor containing a single .2. and type declarations. [Except for the keyword.3 of the report for a more discussion of the relation between newtype. data.
eld. This is appropriate since types de.
ned using newtype are nearly identical to those created by an ordinary data declaration.] 6.2 Field Labels The .
elds within a Haskell data type can be accessed either positionally or by name using .
Consider a data type for a two-dimensional point: data Point = Pt Float Float The two components of a Point are the .eld labels .
A function such as pointx pointx (Pt x _) :: Point -> Float = x may be used to refer to the .rst and second arguments to the constructor Pt.
but. it becomes tedious to create such functions by hand. for large structures. Constructors in a data declaration may be declared with associated .rst component of a point in a more descriptive way.
These .eld names . enclosed in braces.
eld names identify the components of constructor by name rather than by position. This is an alternative way to de.
pointy :: Float} This data type is identical to the earlier de.ne Point: data Point = Pt {pointx.
However. this declaration also de. The constructor Pt is the same in both cases.nition of Point.
nes two .
These .eld names. pointx and pointy.
The expression Pt {pointx=1. In this example. pointy=2} is identical to Pt 1 2. use of .eld names can be used as selector functions to extract a component from a structure.
eld names in the declaration of a data constructor does not preclude the positional style of .
eld access. both Pt {pointx=1. pointy=2} and Pt 1 2 are allowed. When constructing a value using .
some .eld names.
elds may be omitted. these absent .
elds are unde.
ned. Pattern matching using .. then p {pointx=2} is a point with the same pointy as p but with pointx replaced by 2. If p is a Point.ll in components of a new structure.
lling in the speci.
ed .
[The braces used in conjunction with .elds with new values.
However.eld labels are somewhat special: Haskell syntax usually allows braces to be omitted using the layout rule (described in Section 4. the braces associated with .6).
In a type with multiple constructors.] Field names are not restricted to types with a single constructor (commonly called `record' types).eld names must be explicit. selection or update operations using .
A . Field labels share the top level namespace with ordinary variables and class methods. This is similar to the behavior of the head function when applied to an empty list.eld names may fail at runtime.
the same . within a data type.eld name cannot be used in more than one data type in scope. However.
g :: Float} | C2 {f :: Int.eld name can be used in more than one of the constructors so long as it has the same typing in all cases. in this data type data T = C1 {f :: Int. For example. h :: Bool} the .
Field names does not change the basic nature of an algebraic data type. They make constructors with many components more manageable since . then x {f=5} will work for values created by either of the constructors in T. Thus if x is of type T. they are simply a convenient syntax for accessing the components of a data structure by name rather than by position.eld name f applies to both constructors in T.
elds can be added or removed without changing every reference to the constructor. For full details of .
2. if evaluated. would lead to an error or fail to terminate. each . 6. This permits structures that contain elements which.1.3 Strict Data Constructors Data structures in Haskell are generally lazy : the components are not evaluated until needed. Internally. see Section x4. Lazy data structures enhance the expressiveness of Haskell and are an essential aspect of the Haskell programming style.eld labels and their semantics.
eld of a lazy data object is wrapped up in a structure commonly referred to as a thunk that encapsulates the computation de.
ning the .
To avoid these overheads. and they cause the garbage collector to retain other structures needed for the evaluation of the thunk.eld value. The 'a' may be used without disturbing the other component of the tuple. strictness ags in . thunks which contain errors (?) do not aect other elements of a data structure. For example. There are a number of overheads associated with thunks: they take time to construct and evaluate. the tuple ('a'. they occupy space in the heap. Most programming languages are strict instead of lazy: that is. This thunk is not entered until the value is needed.?) is a perfectly legal Haskell value. all components of a data structure are reduced to values before being placed in the structure.
30 7 INPUT/OUTPUT data declarations allow speci.
c .
elds of a constructor to be evaluated immediately. A . selectively suppressing laziness.. Structure components that are simple to evaluate and never cause errors.
For example.ned values are not meaningful. the complex number library de.. of the complex number as being strict.nition marks the two components.
ned component. totally unde. 1 :+ ? for example.
As there is no real need for partially de.ned (?)..ned complex numbers. !. The strictness ag.
2.nitions. See x4. They should be used with caution: laziness is one of the fundamental properties of Haskell and adding strictness ags may lead to hard to . It is diÆcult to present exact guidelines for the use of strictness ags. There is no corresponding way to mark function arguments as being strict.1 for further details. although the same eect can be obtained using the seq or !$ functions.
nd in.
programs proceed via actions which examine and modify the current state of the world. In imperative languages. yet has all of the expressive power found in conventional programming languages. writing . Typical actions include reading and setting global variables.nite loops or have other unexpected consequences. 7 Input/Output The I/O system in Haskell is purely functional.
reading input. Such actions are also a part of Haskell but are cleanly separated from the purely functional core of the language. Haskell's I/O system is built around a somewhat daunting mathematical foundation: the monad . and opening windows.les. However. Rather. understanding of the underlying monad theory is not necessary to program using the I/O system. monads are a conceptual structure into which I/O happens to .
t. . A detailed explanation of monads is found in Section 9. It is no more necessary to understand monad theory to perform Haskell I/O than it is to understand group theory to do simple arithmetic.
31 7.1 Basic I/O Operations The monadic operators that the I/O system is built upon are also used for other purposes. For now. we will look more deeply into monads later. It's best to think of the I/O monad as simply an abstract data type. Actions are de. we will avoid the term monad and concentrate on the use of the I/O system.
Evaluating the de.ned rather than invoked within the expression language of Haskell.
the invocation of actions takes place outside of the expression evaluation we have considered up to this point. as de. Rather.nition of an action doesn't actually cause the action to happen. Actions are either atomic.
The I/O monad contains primitives which build composite actions. a process similar to joining statements in sequential order using `. the return value is `tagged' with IO type. Actions are sequenced using an operator that has a rather cryptic name: >>= (or `bind'). Thus the monad serves as the glue which binds together the actions in a program. A statement is either an action. the type of the function getChar is: getChar :: IO Char The IO Char indicates that getChar.1 Basic I/O Operations Every I/O action returns a value. to hide these sequencing operators under a syntax resembling more conventional languages.' in other languages. when invoked. performs some action which returns a character. the putChar function: putChar :: Char -> IO () takes a character as an argument but returns nothing useful. or a set of local de. (). Actions which return no interesting values use the unit type. Instead of using this operator directly. For example. 7. as described in x3. The do notation can be trivially expanded to >>=. we choose some syntactic sugar. For example. the do notation.ned in system primitives. or are a sequential composition of other actions. a pattern bound to the result of an action using <-. The keyword do introduces a sequence of statements which are executed in order. distinguishing actions from other values.14. The unit type is similar to void in other languages. In the type system.
Here is a simple program to read and then print a character: main main :: IO () = do c <.getChar putChar c The use of the name main is important: main is de.nitions introduced using let. The do notation uses layout in the same manner as let or where so we can omit braces and semicolons with proper indentation.
usually IO (). and must have an IO type. we will have more to say about modules later.ned to be the entry point of a Haskell program (similar to the main function in C). (The name main is special only in the module Main.) This program performs two actions in sequence: .
rst it reads in a character. binding the result to the variable c. and then prints the character. Unlike a let expression where variables are scoped over all de.
nitions. the variables de.
.ned by <.are only in scope in the following statements.
getChar c == 'y' -. We are now ready to look at more complicated I/O functions.32 7 INPUT/OUTPUT There is still one missing piece. Debugging packages (like Trace) often make liberal use of these `forbidden functions' in an entirely safe manner. the function getLine: getLine getLine :: IO String = do c <. What about the other direction? Can we invoke some I/O actions within an ordinary expression? For example. some unsafe functions available to get around this problem but these are better left to advanced programmers. First. The return function does just that: return :: a -> IO a The return function completes the set of sequencing primitives.Bad!!! This doesn't work because the second statement in the `do' is just a boolean value. 7. This fact is often quite distressing to programmers used to placing print statements liberally throughout their code during debugging. how can we say x + print y in an expression so that y is printed out as the expression evaluates? The answer is that we can't! It is not possible to sneak into the imperative universe while in the midst of purely functional code. consider the ready function that reads a character and returns True if the character was a `y': ready ready :: IO Bool = do c <. placed in structures. The last line of ready should read return (c == 'y'). There are. Any intervening construct. Each do introduces a single chain of statements. and used as any other Haskell value. in fact. A function such as f :: Int -> Int -> Int absolutely cannot do any I/O since IO does not appear in the returned type. The return function admits an ordinary value such as a boolean to the realm of I/O actions. We need to take this boolean and create an action that does nothing but return the boolean as its result. Any value `infected' by the imperative world must be tagged as such.2 Programming With Actions I/O actions are ordinary Haskell values: they may be passed to functions. such as the if.getChar if c == '\n' then return "" else do l <. must use a new do to initiate further sequences of actions. not an action.getLine return (c:l) Note the second do in the else clause. Consider this list of actions: . but how do we return a value from a sequence of actions? For example. We can invoke actions and examine their results using do.
do c <. do putChar 'b' putChar 'c'. To join these actions into a single action.3 Exception Handling todoList :: [IO ()] todoList = [putChar 'a'. a function such as sequence_ is needed: sequence_ :: [IO ()] -> IO () sequence_ [] = return () sequence_ (a:as) = do a sequence as This can be simpli.33 7.getChar putChar c] This list doesn't actually invoke any actions|it simply holds them.
y is expanded to x >> y (see Section 9.ed by noting that do x.1). This pattern of recursion is captured by the foldr function (see the Prelude for a de.
a better de.nition of foldr).
3 Exception Handling So far. The folding operation in sequence_ uses the >> function to combine all of the individual actions into a single action.nition of sequence_ is: sequence_ sequence_ :: [IO ()] -> IO () = foldr (>>) (return ()) The do notation is a useful tool but in this case the underlying monadic operator. An understanding of the operators upon which do is built is quite useful to the Haskell programmer. 7. one for each character in the string. In an imperative language. The sequence_ function can be used to construct putStr from putChar: putStr putStr s :: String -> IO () = sequence_ (map putChar s) One of the dierences between Haskell and conventional imperative programming can be seen in putStr. Instead it creates a list of actions. In Haskell. What would happen if getChar encounters an end of . These are usually generalized to arbitrary monads. is more appropriate. The return () used here is quite necessary { foldr needs a null action at the end of the chain of actions it creates (especially if there are no characters in the string!). any function with a context including Monad m => works with the IO type. we have avoided the issue of exceptions during I/O operations. the map function does not perform any action. The Prelude and the libraries contains many functions which are useful for sequencing I/O actions. however. mapping an imperative version of putChar over the string would be suÆcient to print it. >>.
le?13 To deal with exceptional conditions such as `.
13 . can be caught and handled within the I/O monad.le not found' We use the term error for ?: a condition which cannot be recovered from such as non-termination or pattern match failure. Exceptions. on the other hand.
similar in functionality to the one in standard ML. No special syntax or semantics are used. a handling mechanism is used. exception handling is part of the de.34 7 INPUT/OUTPUT within the I/O monad.
the function isEOFError :: IOError -> Bool determines whether an error was caused by an end-of-. For example. Predicates allow IOError values to be queried. IOError.nition of the I/O sequencing operations. This type represents all possible exceptions that may occur within the I/O monad. Errors are encoded using a special data type. This is an abstract type: no constructors for IOError are available to the user.
le condition. The function isEOFError is de. By making IOError abstract. new sorts of errors may be added to the system without a noticeable change to the data type.
If an error occurs.ned in a separate library. and must be explicitly imported into a program. An exception handler has type IOError -> IO a. its result is returned without invoking the handler. The catch function associates an exception handler with an action or set of actions: catch :: IO a -> (IOError -> IO a) -> IO a The arguments to catch are an action and a handler. this version of getChar returns a newline when an error is encountered: getChar' getChar' :: IO Char = getChar `catch` (\e -> return '\n') This is rather crude since it treats all errors in the same manner. IO. If the action succeeds. If only end-of-. it is passed to the handler as a value of type IOError and the action associated with the handler is then invoked. For example.
we can rede. Nested calls to catch are permitted. and produce nested exception handlers. Using getChar'.le is to be recognized. The type of ioError is ioError :: IOError -> IO a It is similar to return except that it transfers control to the exception handler instead of proceeding to the next I/O action..
ne getLine to demonstrate the use of nested handlers: getLine' getLine' where :: IO String = catch getLine'' (\err -> return ("Error: " ++ show err)) getLine'' = do c <.getLine' return (c:l) .getChar' if c == '\n' then return "" else do l <.
and Handles 35 The nested error handlers allow getChar' to catch end of . Channels.7.4 Files.
Haskell provides a default exception handler at the topmost level of a program that prints out the exception and terminates the program. Channels. I/O facilities in Haskell are for the most part quite similar to those in other languages.le while any other error results in a string starting with "Error: " from getLine'. 7. Opening a . and Handles Aside from the I/O monad and the exception handling mechanism it provides. many of these functions are discussed in the Library Report instead of the main report.4 Files. For convenience. Many of these functions are in the IO library instead of the Prelude and thus must be explicitly imported to be in scope (modules and importing are discussed in Section 11). Also.
Closing the handle closes the associated .le creates a handle (of type Handle) for use in I/O transactions..
and stderr (standard error). The getChar function used previously can be de. Character level I/O operations include hGetChar and hPutChar. which take a handle as an argument.ned. including stdin (standard input). stdout (standard output).
ned as: getChar = hGetChar stdin Haskell also allows the entire contents of a .
le or channel to be returned as a single string: getContents :: Handle -> IO String Pragmatically. it may seem that getContents must immediately read an entire .
However. this is not the case.e.le or channel. whose elements are read \by demand" just like any other list. The key point is that getContents returns a \lazy" (i. An implementation can be expected to implement this demand-driven behavior by reading one character at a time from the . non-strict) list of characters (recall that strings are just lists of characters in Haskell). resulting in poor space and time performance under certain conditions.
le as they are required by the computation. In this example. a Haskell program copies one .
le to another: .
36 7 INPUT/OUTPUT main = do fromHandle <.hGetContents fromHandle hPutStr toHandle contents hClose toHandle putStr "Done. the entire contents of the .getAndOpenFile "Copy to: " WriteMode contents <.getAndOpenFile "Copy from: " ReadMode toHandle <.".
le need not be read into memory all at once. If hPutStr chooses to buer the output by writing the string in .
xed sized blocks of characters. only one block of the input .
The input .le needs to be in memory at once.
le is closed implicitly when the last character has been read.5 Haskell and Imperative Programming As a . 7.
An experienced functional programmer should be able to minimize the imperative component of the program. For example. return c:l}} So. I/O programming raises an important issue: this style looks suspiciously like ordinary imperative programming. The I/O monad constitutes a small imperative sub-language inside Haskell. in the end.getLine return (c:l) bears a striking similarity to imperative code (not in any real language) : function getLine() { c := getChar(). In particular. equational reasoning in Haskell is not compromised. the getLine function: getLine = do c <. The imperative feel of the monadic code in a program does not detract from the functional aspect of Haskell.getChar if c == '\n' then return "" else do l <. if c == `\n` then return "" else {l := getLine(). and thus the I/O component of a program may appear similar to ordinary imperative code. has Haskell simply re-invented the imperative wheel? In some sense. yes. But there is one important dierence: There is no special semantics that the user needs to deal with. only using .nal note.
37 the I/O monad for a minimal amount of top-level sequencing. In contrast. The monad cleanly separates the functional and imperative program components. imperative languages with functional subsets do not generally have any well-de.
8 Standard Haskell Classes In this section we introduce the prede.ned barrier between the purely functional and imperative worlds.
ned standard type classes in Haskell. We have simpli.
1 Equality and Ordered Classes The classes Eq and Ord have already been discussed. the Haskell report contains a more complete description. some of the standard classes are part of the standard Haskell libraries. The de. Also.ed these classes somewhat by omitting some of the less interesting methods in these classes. 8..
so that. for instance. the arithmetic sequence expression [1. This includes not only most numeric types. user-de. for example.3..'z'] denotes the list of lower-case letters in alphabetical order.] stands for enumFromThen 1 3 (see x3.ne all other methods (via defaults) in this class and is the best way to create Ord instances. ['a'. but also Char..2 The Enumeration Class Class Enum has a set of operations that underlie the syntactic sugar of arithmetic sequences. Furthermore.10 for the formal translation). 8. We can now see that arithmetic sequence expressions can be used to generate lists of any type that is an instance of Enum.
Indigo. If so: [Red . Violet] Note that such a sequence is arithmetic in the sense that the increment between values is constant. Most types in Enum can be mapped onto .ned enumerated types like Color can easily be given Enum instance declarations. Green. Violet] ) [Red.. even though the values are not numbers. Blue.
The class Read provides operations for parsing character strings to obtain the values they may represent.3 The Read and Show Classes The instances of class Show are those types that can be converted to character strings (typically for I/O).xed precision integers. the fromEnum and toEnum convert between Int and a type in Enum. for these. 8. The simplest function in the class Show is show: .
as in show (2+2). show takes any value of an appropriate type and returns its representation as a character string (list of characters). This is . which results in "4".38 8 STANDARD HASKELL CLASSES show :: (Show a) => a -> String Naturally enough.
ne as far as it goes. all that concatenation gets to be a bit ineÆcient. Speci. as in "The sum of " ++ show x ++ " and " ++ show y ++ " is " ++ show (x+y) ++ "." and after a while. but we typically need to produce more complex strings that may have the representations of many values in them.
1 as a string.2.cally. the function shows is provided: shows :: (Show a) => a -> String -> String shows takes a printable value and a string and returns that string with the value's representation concatenated at the front. and show can now be de. let's consider a function to represent the binary trees of Section 2. To restore linear complexity. showTree is potentially quadratic in the size of the tree.. The second argument serves as a sort of string accumulator.
ned as shows with the null accumulator. This is the default de.
nition of show in the Show class de.
nition: show x = shows x "" We can use shows to de.
and also avoid amassing parentheses at the right end of long constructions. Functions . ('|':) .). Second. but the presentation of this function (and others like it) can be improved. by using functional composition: showsTree :: (Show a) => Tree a -> ShowS showsTree (Leaf x) = shows x showsTree (Branch l r) = ('<':) . showsTree l . We can think of the typing as saying that showsTree maps a tree into a showing function. ('>':) Something more important than just tidying up the code has come about by this transformation: we have raised the presentation from an object level (in this case. First. let's create a type synonym: type ShowS = String -> String This is the type of a function that returns a string representation of something followed by an accumulator string.ne a more eÆcient version of showTree. showsTree r . strings) to a function level. we can avoid carrying accumulators around.
String) pairs [9].3 The Read and Show Classes 39 like ('<' :) or ("a string" ++) are primitive showing functions. Now that we can turn trees into strings. however. containing a value of type a that was read from the input string and the remaining string that follows what was parsed.8. The standard function reads is a parser for any instance of Read: reads :: (Read a) => ReadS a We can use this function to de. If no parse was possible. and if there is more than one possible parse (an ambiguity).String)] Normally. The Prelude provides a type synonym for such functions: type ReadS a = String -> [(a. which is a function that takes a string and returns a list of (a. and we build up more complex functions by function composition. a parser returns a singleton list. the resulting list contains more than one pair. let's turn to the inverse problem. the result is the empty list. The basic idea is a parser for a type a.
readsTree s. List comprehensions give us a convenient idiom for constructing such parsers:14 readsTree readsTree ('<':s) readsTree s :: (Read a) => ReadS (Tree a) = [(Branch l r.reads s] Let's take a moment to examine this function de.t) <. t) | (x.ne a parsing function for the string representation of binary trees produced by showsTree. '>':u) <. u) | (l. (r. '|':t) <.readsTree t ] = [(Leaf x.
nition in detail. There are two main cases to consider: If the .
we have a leaf. In the . otherwise.rst character of the string to be parsed is '<'. we should have the representation of a branch.
calling the rest of the input string following the opening angle bracket s. and u is the tail. The string remaining from that parse begins with '>'. Notice the expressive power we get from the combination of pattern matching with list comprehension: the form of a resulting parse is given by the main expression of the list comprehension. the . The tree l can be parsed from the beginning of the string s. 4. The string remaining (following the representation of l) begins with '|'. any possible parse must be a tree Branch l r with remaining string u.rst case. The tree r can be parsed from the beginning of t. 3. 2. Call the tail of this string t. subject to the following conditions: 1.
rst two conditions above are expressed by the .
The second de. and the remaining conditions are expressed by the second generator. '|':t) is drawn from the list of parses of s").rst generator (\(l.
.ning equation above just says that to parse the representation of a leaf..
"")] [] There are a couple of shortcomings in our de. e)).: (reads "5 golden rings") :: [(Integer.String)] ) [(5. " golden rings")] With this understanding.g. providing a reads that behaves as one would expect.
nition of readsTree. this lack of uniformity making the function de. One is that the parser is quite rigid. allowing no white space before or between the elements of the tree representation. the other is that the way we parse our punctuation symbols is quite dierent from the way we parse leaf values and subtrees.
nition harder to read. We can address both of these problems by using the lexical analyzer provided by the Prelude: lex :: ReadS String lex normally returns a singleton list containing a pair of strings: the .
The lexical rules are those of Haskell programs. t) | (x. readsTree t. lex u. we would automatically then be able to parse and display many other types containing trees as components. u) ("|". but also does not begin with a valid lexeme after any leading whitespace and comments. w) (">"."")]. This would allow us to use the generic overloaded functions from the Prelude to parse and display trees. t) <<<<<- lex s. our tree parser now looks like this: readsTree readsTree s :: (Read a) => ReadS (Tree a) = [(Branch l r. Moreover. if the input is not empty in this sense.rst lexeme in the input string and the remainder of the input. including comments. If the input string is empty or contains only whitespace and comments. readsTree and showsTree are of almost the right types to be Show and Read methods The showsPrec and readsPrec methods are parameterized versions of shows and reads. v) (r.reads s ] We may now wish to use readsTree and showsTree to declare (Read a) => Tree a an instance of Read and (Show a) => Tree a an instance of Show. along with whitespace. lex w ] <. t) (l. readsTree v. The extra parameter is a precedence level. [Tree Integer]. As it turns out. for example. x) | ("<". Using the lexical analyzer. which lex skips. lex returns []. x) ++ [(Leaf x. used to properly parenthesize expressions containing in. lex returns [("".
x constructors. the precedence can be ignored. For types such as Tree. The Show and Read instances for Tree are: instance Show a => Show (Tree a) where showsPrec _ x = showsTree x instance Read a => Read (Tree a) where readsPrec _ s = readsTree s .
4 Derived Instances Alternatively.41 8. the Show instance could be de.
however. will be less eÆcient than the ShowS version.ned in terms of showTree: instance Show a => Show (Tree a) where show t = showTree t This. Note that the Show class de.
allowing the user to de.nes default methods for both showsPrec and show.
an instance declaration that de. Since these defaults are mutually recursive.ne either one of these in an instance declaration.
such a declaration is simple|and boring| to produce: we require that the element type in the leaves be an equality type. then. Read. Instances of Ord. comments and whitespace)..4 Derived Instances Recall the Eq instance for trees we presented in Section 5. We can test the Read and Show instances by applying (read .. we don't need to go through this tedium every time we need equality operators for a new type. Ix. and Show can also be generated by the deriving clause. Other classes such as Num also have these \interlocking defaults". Enum. respectively. Any other two trees are unequal: instance (Eq a) => Eq (Tree a) where (Leaf x) == (Leaf y) = x == y (Branch l r) == (Branch l' r') = l == l' && r == r' _ == _ = False Fortunately. show) (which should be the identity) to some trees. 8.nes neither of these functions will loop when called. [More than one class name can be speci. and two branches are equal i their left and right subtrees are equal.
] .
this is the full declaration: data [a] = [] | a : [a] deriving (Eq. "cat" < "catalog". In fact.42 9 ABOUT MONADS the data declaration. In practice. are ordered as determined by the underlying Char type. in particular.) The derived Eq and Ord instances for lists are the usual ones.pseudo-code (Lists also have Show and Read instances. rather than user-de. Recall that the built-in list type is semantically equivalent to an ordinary two-constructor type. character strings. for example. which are not derived. Eq and Ord instances are almost always derived. and the arguments of a constructor are compared from left to right. as lists of characters. with an initial substring comparing less than a longer string. Ord) -.
ned. In fact. we should provide our own de.
for example.nitions of equality and ordering predicates only with some trepidation. An intransitive (==) predicate. confusing readers of the program and confounding manual or automatic program transformations that rely on the (==) predicate's being an approximation to de. could be disastrous. being careful to maintain the expected algebraic properties of equivalence relations and total orders.
(Read and Show instances for most of the standard types are provided by the Prelude. Wednesday . such as the function type (->). Friday] [Monday.) The textual representation de. Thursday. Wednesday. have a Show instance but not a corresponding Read. probably the most important example is that of an abstract data type in which dierent concrete values may represent the same abstract value..nitional equality.. and here again. the ordering is that of the constructors in the data declaration. Friday] ) ) Derived Read (Show) instances are possible for all types whose component types also have Read (Show) instances. Nevertheless. it is sometimes necessary to provide Eq or Ord instances dierent from those that would be derived. For example: data Day = Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday deriving (Enum) Here are some simple examples using the derived instances for this type: [Wednesday . Some types. An enumerated type can have a derived Enum instance.] [Wednesday. Friday] [Monday.
For example.ned by a derived Show instance is consistent with the appearance of constant Haskell expressions of the type in question. Monads are frequently encountered in Haskell: the IO system is constructed using a monad.. .Wednesday]" About Monads Many newcomers to Haskell are puzzled by the concept of monads. Wednesday] 9 ) "[Monday. we obtain show [Monday . In this section we explore monadic programming in more detail. above. if we add Show and Read to the deriving clause for type Day.Tuesday. and the standard libraries contain an entire module dedicated to monads. a special syntax for monads has been provided (do expressions).
Here we address not only the language features that involve monads but also try to reveal the bigger picture: why monads are such an important tool and how they are used.1 Monadic Classes The Prelude contains a number of classes de.org. Another good introduction to practical programming using monads is Wadler's Monads for Functional Programming [10]. more explanations can be found at haskell. There is no single way of explaining monads that works for everyone.1 Monadic Classes This section is perhaps less \gentle" than the others.43 9. 9.
ning monads are they are used in Haskell. it is not necessary to delve into abstract mathematics to get an intuitive understanding of how to use the monadic classes. whilst the category theoretic terminology provides the names for the monadic classes and operations. These classes are based on the monad construct in category theory. A monad is constructed on top of a polymorphic type such as IO. The monad itself is de.
we hope to give a feel for how monads are used. already discussed in section 5. x /= y and not (x == y) ought to be the same for any type of values being compared. by laws. In the same sense. The Functor class. and MonadPlus. The monad laws give insight into the underlying structure of monads: by examining these laws. None of the monadic classes are derivable. but ought be obeyed by any instances of a monadic class. monads are governed by set of laws that should hold for the monadic operations. This idea of laws is not unique to monads: Haskell includes other operations that are governed. Monad. For example.ned by instance declarations associating the type with the some or all of the monadic classes. In addition to IO. two other types in the Prelude are members of the monadic classes: lists ([]) and Maybe. Mathematically. at least informally. de. Functor. there is no guarantee of this: both == and /= are separate methods in the Eq class and there is no way to assure that == and =/ are related in this manner. the monadic laws presented here are not enforced by Haskell. However.
The Monad class de. returning a container of the same shape. These laws apply to fmap in the class Functor: fmap id = id fmap (f . g) = fmap f . The map function applies an operation to the objects inside a container (polymorphic types can be thought of as containers for values of another type).nes a single operation: fmap. fmap g These laws ensure that the container shape is unchanged by fmap and that the contents of the container are not re-arranged by the mapping operation.
nes two basic operators: >>= (bind) and return. combine two monadic values while the return operation injects . >> and >>=. >>= class Monad m where (>>=) :: (>>) :: return :: fail :: m >> k = m a -> m a -> a -> m String (a -> m b) -> m b m b -> m b a -> m a m >>= \_ -> k The bind operations. infixl 1 >>.
The result is to combine ma and mb into a monadic value containing b. The signature of >>= helps us to understand this operation: ma >>= \v -> mb combines a monadic value ma containing values of type a and a function which operates on a value v of type a. returning the monadic value mb.44 9 ABOUT MONADS a value into the monad (container). The >> function is used when the function does not need the value produced by the .
passing the result of the . of course. on the monad. x >>= y performs two actions sequentially. For example. The precise meaning of binding depends.rst monadic operator. in the IO monad.
e2 = e1 >> e2 e1 >>= \p -> e2 When the pattern in this second form of do is refutable. lists and the Maybe type.. _ -> fail "s") where "s" is a string identifying the location of the do statement for possible use in an error message. in turn. e2 = do p <. an action such as 'a' <. the zero value is []. The I/O monad has no zero element and is not a member of this class. the empty list. This. these monadic operations can be understood in terms of passing zero or more values from one calculation to the next. The laws which govern >>= and return are: return a >>= k = k a m >>= return = m xs >>= return . This may raise an error (as in the IO monad) or return a \zero" (as in the list monad). The essential translation of do is captured in the following two rules: do e1 . For the other built-in monads. .rst into the second. pattern match failure calls the fail operation. terminates the program since in the I/O monad fail calls error.getChar will call fail if the character typed is not 'a'. We will see examples of this shortly. The laws governing the mplus operator are as follows: m `mplus` mzero = m mzero `mplus` m = m The mplus operator is ordinary list concatenation in the list monad. Thus the more complex translation is do p <.e1. The do syntax provides a simple shorthand for chains of monadic operations. in the I/O monad. e2 = e1 >>= (\v -> case v of p -> e2. For example.e1.
45 9. When used with lists. The return function creates a singleton list. binding applies this function to each of the a's in the input and returns all of the generated b's concatenated into a list. the signature of >>= becomes: (>>=) :: [a] -> (a -> [b]) -> [b] That is. For lists.2 Built-in Monads 9.2 Built-in Monads Given the monadic operations and the laws that govern them. These operations should already be familiar: list comprehensions can easily be expressed using the monadic operations de. monadic binding involves joining together a set of calculations for each value in the list. given a list of a's and a function that maps an a onto a list of b's. what can we build? We have already examined the I/O monad in detail so we start with the two other built-in monads.
3] .3] True <.3] y <.y) | x <.2.return (x /= y) return (x.2.[1. These following three expressions are all dierent syntax for the same thing: [(x.y) [1. x /= y] do x <.[1.y) _ -> fail ""))) This de.3].3] >>= (\ x -> [1. y <.ned for lists.3] >>= (\y -> return (x/=y) >>= (\r -> case r of True -> return (x.[1.2.2.2.[1.2.
nition depends on the de.
3] invokes the remainder of the monadic computation three times.is generating a set of values which is passed on into the remainder of the monadic computation. (x.4] [] ) ) ) [11.b]) "ab" "cd" mvLift2 (*) [1.20. The returned expression. For example.2. returning a value for each possible combination of the two input arguments.30] mvLift2 (\a b->[a.21. will be evaluated for all possible combinations of bindings that surround it. For example.13. Essentially."ad".2. this function: mvLift2 mvLift2 f x y :: (a -> b -> c) -> [a] -> [b] -> [c] = do x' <.[1. The monad de. the list monad can be thought of as describing functions of multi-valued arguments. f. once for each element of the list. You can think of it as transporting a function from outside the list monad. In this sense.31.nition of fail in this monad as the empty list. mvLift2 (+) [1."bc".y).3] [10.y return (f x' y') turns an ordinary function of two arguments (f) into a function over multiple values (lists of arguments). into the list monad in which computations take on multiple values."bd"] [] This function is a specialized version of the LiftM2 function in the monad library.33] ["ac".23. each <. Thus x <.x y' <.
.ned for Maybe is similar to the list monad: the value Nothing serves as [] and Just x as [x].
3 Using Monads Explaining the monadic operators and their associated laws doesn't really show what monads are good for. by de. What they really provide is modularity. That is.46 9 ABOUT MONADS 9.
the state monad. and then build a more complex monad with a similar de. We will start with a monad taken directly from this paper. Wadler's paper [10] is an excellent example of how monads can be used to construct modular programs.ning an operation monadically. we can hide underlying machinery in a way that allows new features to be incorporated into the monad transparently.
s)) -. Brie y.s1) = c1 s0 SM c2 = fc2 r in c2 s1) return k = SM (\s -> (k.s)) -.The monadic type instance Monad SM where -.alters the state updateSM f = SM (\s -> ((). f s)) -.run a computation in the SM monad runSM :: S -> SM a -> (a. a state monad built around a state type S looks like this: data SM a = SM (S -> (a.S)) -.S) runSM s0 (SM c) = c s0 This example de.nition.defines state propagation SM c1 >>= fc2 = SM (\s0 -> let (r.extracts the state from the monad readSM :: SM S readSM = SM (\s -> (s.updates the state of the monad updateSM :: (S -> S) -> SM () -.
to be a computation that implicitly carries a type S.nes a new type. SM. a computation of type SM t de. That is.
nes a value of type t while also interacting with (reading and writing) the state of type S. The de.
nition of SM is simple: it consists of functions that take a state and produce two results: a returned value (of any type) and an updated state. The newtype declaration is often used here instead of data. We can't use a type synonym here: we need a type name like SM that can be used in instance declarations. This instance declaration de.
nes the `plumbing' of the monad: how to sequence two computations and the de.
nition of an empty computation. Sequencing (the >>= operator) de.
the state coming out of c1 is passed into c2 and the overall result is the result of c2. c2. then passes the value coming out of this computation. to the function that returns the second computation. into c1. The de. r. s0.nes a computation (denoted by the constructor SM) that passes an initial state. Finally.
. A monadic primitive is simply an operation that uses the insides of the monad abstraction and taps into the `wheels and gears' that make the monad work.nition of return is easier: return doesn't change the state at all. While >>= and return are the basic monadic sequencing operations. it only serves to bring a value into the monad. we also need some monadic primitives. For example. in the IO monad.
a change to the de. Note that these depend on the inner structure of the monad . Similarly.3 Using Monads 47 operators such as putChar are primitive since they deal with the inner workings of the IO monad. our state monad uses two primitives: readSM and updateSM.9.
nition of the SM type would require a change to these primitives. The de.
we need a function that runs computations in the monad. (We could also have used writeSM as a primitive but update is often a more natural way of dealing with state).nition of readSM and updateSM are simple: readSM brings the state out of the monad for observation while updateSM allows the user to alter the state in the monad. runSM. This takes an initial state and a computation and yields both the returned value of the computation and the . Finally.
what we are trying to do is de. Looking at the bigger picture.nal state.
the use (or non-use) of the state is hidden: we don't invoke or sequence our computations dierently depending on whether or not they use S. We de. However. sequenced using >>= and return. Rather than present any examples using this simple state monad.ne an overall computation as a series of steps (functions with type SM a). These steps may interact with the state (via readSM or updateSM) or may ignore the state. we proceed on to a more complex example that includes the state monad.
to build a library of operations and types speci. functions and types. Such languages use the basic tools of Haskell. That is.ne a small embedded language of resourceusing calculations. we build a special purpose language implemented as a set of Haskell types and functions.
consider a computation that requires some sort of resource. when the resource is unavailable. the computation suspends. In this example. We use the type R to denote a computation using resources controlled by our monad.cally tailored to a domain of interest. If the resource is available. computation proceeds. The de.
nition of R is as follows: data R a = R (Resource -> (Resource. capturing the work done up to the point where resources were exhausted. Right (pc1 >>= fc2))) return v = R (\r -> (r. of type R a. Right pc1) -> (r'. coupled with either a result. Left v) -> let R c2 = fc2 v in c2 r' (r'. The Monad instance for R is as follows: instance Monad R where R c1 >>= fc2 = R (\r -> case c1 r of (r'. or a suspended computation. (Left v))) The Resource type is used in the same manner as the state in the state monad. Either a (R a))) Each computation is a function from available resources to remaining resources. of type a. This de.
and resources remaining at the point of suspension. c1 and fc2 (a function producing c2). pass the initial resources into c1. and remaining resources. . The result will be either a value. which are used to determine the next computation (the call fc2 v). pc1. v. or a suspended computation.nition reads as follows: to combine two `resourceful' computations..
This monad could be used to control many types of resource or implement many dierent types of resource usage policies.nes the basic structure of the monad but does not determine how resources are used. We will demonstrate a very simple de.
the step function suspends the current computation (this suspension is captured in c) and passes this suspended computation back into the monad. If no steps are available. This function continues computation in R by returning v so long as there is at least one computational step resource available. we have the tools to de.nition of resources as an example: we choose Resource to be an Integer. Right c)) The Left and Right constructors are part of the Either type. representing available computation steps: type Resource = Integer This function takes a step unless no steps are available: step step v :: a -> R a = c where c = R (\r -> if r /= 0 then (r-1. Left v) else (r. So far.
i step (iValue+1) This de. we need to address how computations in this monad are expressed. Finally. Consider an increment function in our monad: inc inc i :: R Integer -> R Integer = do iValue <.ne a sequence of \resourceful" computations (the monad) and we can express a form of resource usage using step.
is necessary to pull the argument value out of the monad.nes increment as a single step of computation. This de. The <. the type of iValue is Integer instead of R Integer.
though. compared to the standard de.nition isn't particularly satisfying.
These bring existing functionality into the monad. Consider the de.nition of the increment function. Can we instead \dress up" existing operations like + so that they work in our monadic world? We'll start with a set of lifting functions.
f. inc becomes inc inc i :: R Integer -> R Integer = lift1 (i+1) This is better but still not ideal. Using lift1. First. we add lift2: . and creates a function in R that executes the lifted function in a single step.ra1 step (f a1) This takes a function of a single argument.nition of lift1 (this is slightly dierent from the liftM1 found in the Monad library): lift1 lift1 f :: (a -> b) -> (R a -> R b) = \ra1 -> do a1 <.
Using lift2.3).3 Using Monads lift2 lift2 f :: (a -> b -> c) -> (R a -> R b -> R c) = \ra1 ra2 -> do a1 <. fromInteger The fromInteger function is applied implicitly to all integer constants in a Haskell program (see Section 10.49 9..ra2 step (f a1 a2) Notice that this function explicitly sets the order of evaluation in the lifted function: the computation yielding a1 occurs before the computation for a2.ra1 a2 <. this de.
We can now.nition allows integer constants to have the type R Integer. . <.nally. The idea of providing new de. Since we can't use if (it requires that the test be of type Bool instead of R Bool). To express interesting computations in R we will need a conditional..
Monads are particularly useful for encapsulating the semantics of these embedded languages in a clean and modular way.nitions for existing operations like + or if is an essential part of creating an embedded language in Haskell. .
We can now compute run 10 (fact 2) run 10 (fact 20) ) ) Just 2 Nothing Finally. returning the value of the . Consider the following function: (|||) :: R a -> R a -> R a This runs two computations in parallel.nishing in the allotted number of steps. we can add some more interesting functionality to this monad.
One possible de.rst one to complete.
either returning an evaluated value or passing the remainder of the computation into f. The oneStep function takes a single step in its argument. it evaluates c2 |||'. returning its value of c1 complete or. Left v) -> (r+r'-1. Right c1') -> -. The de. Left v) (r'.r' must be 0 let R next = f c1' in next (r+r'-1)) This takes a step in c1. if c1 returns a suspended computation (c1').
nition of oneStep is simple: it gives c1 a 1 as its resource argument. If a .. We can now evaluate expressions like run 100 (fact (-1) ||| (fact 3)) without looping since the two calculations are interleaved. (Our de.
Many variations are possible on this basic structure. allowing computations in M to interact with the outside world. it serves to illustrate the power of monads as a tool for de. We could also embed this monad inside the standard IO monad. we could extend the state to include a trace of the computation steps. For example.nition of fact loops for -1). While this example is perhaps more advanced than others in this tutorial.
ning the basic semantics of a system. We also present this example as a model of a small Domain Speci.
c Language. something Haskell is particularly good at de.
Of particular interest are Fran. a language of computer music. a language of reactive animations. see haskell. Many other DSLs have been developed in Haskell. .ning. and Haskore.org for many more examples.
however. based on those of Scheme [7].51 10 Numbers Haskell provides a rich collection of numeric types.) The standard types include . (Those languages. are dynamically typed. which in turn are based on Common Lisp [8].
(-). (*) negate. multiplication. negation.and double-precision real and complex oating-point. but not of Ord. these include. We also note that Num is a subclass of Eq.1 Numeric Class Structure The numeric type classes (class Num and those that lie below it) account for many of the standard Haskell classes. this is because the order predicates do not apply to complex numbers.xed. The subclass Real of Num. among others.and arbitrary-precision integers. We outline here the basic characteristics of the numeric type class structure and refer the reader to x6. ratios (rational numbers) formed from each integer type. and single. abs :: (Num a) => a -> a -> a :: (Num a) => a -> a [negate is the function applied by Haskell's only pre. 10.4 for details. subtraction. however. addition. The Num class provides several basic operations common to all numeric types. is a subclass of Ord as well. and absolute value: (+).
we can't call it (-). (Pre. -x*y is equivalent to negate (x*y). because that is the subtraction function. minus. For example.x operator. so this name is provided instead.
x minus has the same syntactic precedence as in.
machine integers. two dierent kinds of division operators are provided in two non-overlapping subclasses of Num: The class Integral provides whole-number division and remainder operations. this means that there is no attempt to provide Gaussian integers. also known as \bignums") and Int (bounded.a) :: (Fractional a. logarithmic.x minus. and a collection of functions that round to integral values by diering rules: properFraction truncate. Integral b) => a -> (b. which. Integral b) => a -> b . and exponential functions. Note that Integral is a subclass of Real. which decomposes a number into its whole and fractional parts. floor. with a range equivalent to at least 29-bit signed binary). A particular Haskell implementation might provide other integral types in addition to these.)] Note that Num does not provide a division operator. The standard instances of Integral are Integer (unbounded or mathematical integers. which provides the ordinary division operator (/). All other numeric types fall in the class Fractional. is lower than that of multiplication. The RealFrac subclass of Fractional and Real provides a function properFraction. ceiling: :: (Fractional a. of course. The further subclass Floating contains trigonometric. rather than of Num directly. round.
the exponent and signi.52 10 NUMBERS The RealFloat subclass of Floating and RealFrac provides some specialized functions for eÆcient access to the components of a oating-point number.
The others are made from these by type constructors. The standard types Float and Double fall in class RealFloat. Instead of a data constructor like :+. Complex (found in the library Complex) is a type constructor that makes a complex type in class Floating from a RealFloat type: data (RealFloat a) => Complex a = !a :+ !a deriving (Eq. rationals use the `%' function to form a ratio from two integers. but have a canonical (reduced) form that the implementation of the abstract data type must maintain. however.2 Constructed Numbers Of the standard numeric types. 10. ratios are not unique. Float. respectively. it is not necessarily the case. Integer. We can also see from the data declaration that a complex number is written x :+ y . Notice the context RealFloat a. for instance. denominator :: (Integral a) => Ratio a -> a Why the dierence? Complex numbers in cartesian form are unique|there are no nontrivial identities involving :+. Instead of pattern matching. the type constructor Ratio (found in the Rational library) makes a rational type in class RealFrac from an instance of Integral. 10. is an abstract type constructor. Since :+ is a data constructor. these were discussed in Section 6. although the real part of x:+y is always x. On the other hand.3 Numeric Coercions and Overloaded Literals The Standard Prelude and libraries provide several overloaded functions that serve as explicit coercions: .) Ratio. which restricts the argument type. thus.cand. component extraction functions are provided: (%) :: (Integral a) => a -> a -> Ratio a numerator. that numerator (x%y) is equal to x. and Double are primitive. we can use it in pattern matching: conjugate conjugate (x:+y) :: (RealFloat a) => Complex a -> Complex a = x :+ (-y) Similarly. (Rational is a type synonym for Ratio Integer. Int. the standard complex types are Complex Float and Complex Double. the arguments are the cartesian real and imaginary parts. Text) The ! symbols are strictness ags.3.
a oating numeral (with a decimal point) is regarded as an application of fromRational to the value of the numeral as a Rational. for example: halve halve x :: (Fractional a) => a -> a = x * 0. Num b) => a -> b (RealFrac a. Fractional b) => a -> b fromIntegral fromRealFrac = fromInteger . This means that we can use numeric literals in generic numeric functions.4 Default Numeric Types fromInteger fromRational toInteger toRational fromIntegral fromRealFrac :: :: :: :: :: :: (Num a) => Integer -> a (Fractional a) => Rational -> a (Integral a) => a -> Integer (RealFrac a) => a -> Rational (Integral a.53 10. 7 has the type (Num a) => a.3 has the type (Fractional a) => a.5 This rather indirect way of overloading numerals has the additional advantage that the method of interpreting a numeral as a number of a given type can be speci. toInteger = fromRational . Thus. Similarly. and 7. toRational Two of these are implicitly used to provide overloaded numeric literals: An integer numeral (without a decimal point) is actually equivalent to an application of fromInteger to the value of the numeral as an Integer.).
In this manner. even user-de.ned to produce a complex number whose real part is supplied by an appropriate RealFloat instance of fromInteger.
recall our . As another example.ned numeric types (say. quaternions) can make use of overloaded numerals.
rst de.
The explicit type signature is legal.nition of inc from Section 2: inc inc n :: Integer -> Integer = n+1 Ignoring the type signature. the most general type of inc is (Num a) => a->a. since it is more speci. however.
and in this case would cause something like inc (1::Float) to be ill-typed.4 Default Numeric Types Consider the following function de. 10.c than the principal type (a more general type signature would cause a static error). The type signature has the eect of restricting inc's type.
there . Integral b) => a -> b -> a. Integral b) => a.nition: rms rms x y :: (Floating a) => a -> a -> a = sqrt ((x^2 + y^2) * 0.5) has the type (Num a. This is a problem.8. and since 2 has the type (Num a) => a. the type of x^2 is (Num a.5) The exponentiation function (^) (one of three dierent standard exponentiation operators with dierent typings. see x6.
the programmer has speci. Essentially.54 11 MODULES is no way to resolve the overloading associated with the type variable b. since it is in the context. but has otherwise vanished from the type expression.
ed that x should be squared. but has not speci.
we can .ed whether it should be squared with an Int or an Integer value of two. Of course.
above). and the . consisting of the keyword default followed by a parenthesized. any Integral instance will do. When an ambiguous type variable is discovered (such as b. whereas here. Because of the dierence between the numeric and general cases of the overloading ambiguity problem. if at least one of its classes is numeric and all of its classes are standard.x this: rms x y = sqrt ((x ^ (2::Integer) + y ^ (2::Integer)) * 0. this kind of overloading ambiguity is not restricted to numbers: show (read "xyz") As what type is the string supposed to be read? This is more serious than the exponentiation ambiguity.5) It's obvious that this sort of thing will soon grow tiresome. Haskell provides a solution that is restricted to numbers: Each module may contain a default declaration. very dierent behavior can be expected depending on what instance of Text is used to resolve the ambiguity. the default list is consulted. because there. however. In fact. commaseparated list of numeric monotypes (types with no variables).
which provides no defaults. (See x4. Very cautious programmers may prefer default (). Rational.3. but (Integer.) The \default default" is (Integer. the ambiguous exponent above will be resolved as type Int. For example. Double). if the default declaration default (Int. A module in Haskell serves the dual purpose of controlling name-spaces and creating abstract data types. Double) may also be appropriate.rst type from the list that will satisfy the context of the type variable is used.4 for more details. 11 Modules A Haskell program consists of a collection of modules. Float) is in eect. The top level of a module contains any of the various declarations we have discussed: .
class and instance declarations. function de. type signatures.xity declarations. data and type declarations.
nitions. and pattern bindings. Except for the fact that import declarations (to be described shortly) must appear .
the declarations may appear in any order (the top-level scope is mutually recursive).rst. and modules are in no way \. Haskell's module design is relatively conservative: the name-space of modules is completely at.
rst-class." Module names are alphanumeric and must begin with an uppercase letter. There is no formal connection between a Haskell module and the .
le system that would (typically) support it. there is no connection between module names and . In particular.
le names. and more than one module could conceivably reside in a single .
le (one module may even span several .
les). a particular implementation will most likely adopt conventions that make the connection between modules and . Of course.
Technically speaking. a module is really just one big declaration which begins with the keyword module. here's an example for a module whose name is Tree: .les more stringent.
55 11.1 Quali.
Branch).1. fringe ) where data Tree a = Leaf a | Branch (Tree a) (Tree a) fringe :: Tree a -> [a] fringe (Leaf x) = [x] fringe (Branch left right) = fringe left ++ fringe right The type Tree and the function fringe should be familiar. they were given as examples in Section 2. layout is active at the top level of a module.ed Names module Tree ( Tree(Leaf.2. and thus the declarations must all line up in the same column (typically the . [Because of the where keyword.
The names in an export list need not be local to the exporting module. this is allowed. so the eect would be the same. any name in scope may be listed in an export list. fringe ) main = print (fringe (Branch (Leaf 1) (Leaf 2))) The various items being imported into and exported out of a module are called entities.Branch).. As short-hand. The Tree module may now be imported into some other module: module Main (main) where import Tree ( Tree(Leaf. omitting it would cause all entities exported from Tree to be imported. Exporting a subset of the constructors is also possible. Note the explicit import list in the import declaration. (In the above example everything is explicitly exported. and fringe. all of the names bound at the top level of the module would be exported. If the export list following the module keyword is omitted. Leaf. Branch.) Note that the name of a type and its constructors have be grouped together.] This module explicitly exports Tree.1 Quali.rst). as in Tree(Leaf. 11. we could also write Tree(. Also note that the module name is the same as that of the type.Branch).)..
xed by the name of the module imported. These pre.
[Quali.' character without intervening whitespace.xes are followed by the `.
A.x and A .ers are part of the lexical syntax. Thus. x are quite dierent: the .
rst is a quali.
ed name and the second a use of the in.
' function.] For example. using the Tree module introduced above: .x `.
56 11 MODULES module Fringe(fringe) where import Tree(Tree(. fringe ) import qualified Fringe ( fringe ) main = do print (fringe (Branch (Leaf 1) (Leaf 2))) print (Fringe.fringe (Branch (Leaf 1) (Leaf 2))) Some Haskell programmers prefer to use quali.Branch)..A different definition of fringe fringe (Leaf x) = [x] fringe (Branch x y) = fringe x module Main where import Tree ( Tree(Leaf.)) fringe :: Tree a -> [a] -.
ers for all imported entities. making the source of each name explicit with every use. Others prefer short names and only use quali.
ers when absolutely necessary. Quali.
2 Abstract Data Types Aside from controlling namespaces. left. right. a suitable ADT for it might include the following operations: data Tree a leaf branch cell left. For example. The compiler knows whether entities from dierent modules are actually the same. such name clashes are allowed: an entity can be imported by various routes without con ict.ers are used to resolve con icts between dierent entities which have the same name. leaf. although the Tree type is simple enough that we might not normally make it abstract. modules provide the only way to build abstract data types (ADTs) in Haskell. cell. branch. 11. all operations on the ADT are done at an abstract level which does not depend on the representation. isLeaf) where data Tree a = Leaf a | Branch (Tree a) (Tree a) leaf branch cell (Leaf a) left (Branch l r) right (Branch l r) isLeaf (Leaf _) isLeaf _ = = = = = = = Leaf Branch a l r True False . For example. right isLeaf -:: :: :: :: :: just a -> Tree Tree Tree Tree the type name Tree a a -> Tree a -> Tree a a -> a a -> Tree a a -> Bool A module supporting this is: module TreeADT (Tree. But what if the same entity is imported from more than one module? Fortunately. the characteristic feature of an ADT is that the representation type is hidden.
Thus Leaf and Branch are not exported. This is useful for explicitly excluding names that are used for other purposes without having to use quali. 11.3 More Features 57 Note in the export list that the type name Tree appears alone (i. without its constructors).e.3 More Features Here is a brief overview of some other aspects of the module system.11. the advantage of this information hiding is that at a later time we could change the representation type without aecting users of the type. Of course. and the only way to build or take apart trees outside of the module is by using the various (abstract) operations. See the report for more details. An import declaration may selectively hide entities using a hiding clause in the import declaration..ers. import Prelude hiding length will not import length from the Standard Prelude.
for a given type and class. there are many rules concerning the import and export of values. it is illegal to import two dierent entities having the same name into the same scope. Although Haskell's module system is relatively conservative. there cannot be more than one instance declaration for that combination of type and class anywhere in the program. . 12 Typing Pitfalls This short section give an intuitive description of a few common problems that novices run into using Haskell's type system. Class methods may be named either in the manner of data constructors. in parentheses following the class name.ned dierently. The reader should read the Report for details (x5). or as ordinary variables. Instance declarations are not explicitly named in import or export lists. Most of these are obvious|for instance. Other rules are not so obvious|for example. Every module exports all of its instance declarations and every import brings all instance declarations into scope.
because identi.58 12 TYPING PITFALLS 12.1 Let-Bound Polymorphism Any language using the Hindley-Milner type system has what is called let-bound polymorphism.
one passed as argument to another function) cannot be instantiated in two dierent ways.ill-typed expression because g. A common numeric typing error is something like the following: average xs = sum xs / length xs -. For example. The type mismatch must be corrected with an explicit coercion: average average xs :: (Fractional a) => [a] -> a = sum xs / fromIntegral (length xs) 12.5). g 'a') in f (\x->x) -.ers not bound using a let or where clause (or at the top level of a module) are limited with respect to their polymorphism.Wrong! (/) requires fractional arguments.5. is used within f in two dierent ways: once with type [a]->[a]. The reason for this restriction is related to a subtle type ambiguity and is explained in full detail in the Report (x4. A simpler explanation follows: The monomorphism restriction says that any identi.. More general numeric expressions sometimes cannot be quite so generic. In particular. 12. bound to a lambda abstraction whose principal type is a->a. and once with type Char->Char. but length's result is an Int. a lambda-bound function (i. and not implicitly coerced to the various numeric types. this program is illegal: let f g = (g []. as in many other languages.e.2 Numeric Overloading It is easy to forget at times that numerals are overloaded.3 The Monomorphism Restriction The Haskell type system contains a restriction related to type classes that is not found in ordinary Hindley-Milner type systems: the monomorphism restriction.
er bound by a pattern binding (which includes bindings to a single identi.
er). must be monomorphic. An identi. and having no explicit type signature.
or is overloaded but is used in at most one speci.er is monomorphic if is either not overloaded.
The simplest way to avoid the problem is to provide an explicit type signature. Note that any type signature will do (as long it is type correct).c overloading and is not exported. Violations of this restriction result in a static type error. A common violation of the restriction happens with functions de.
ned in a higher-order manner. as in this de.
nition of sum from the Standard Prelude: sum = foldl (+) 0 .
59 As is. We can . this would cause a static type error.
which are isomorphic to . in order to assure eÆcient access to array elements. arrays in a functional language would be regarded simply as functions from indices to values. but pragmatically.x the problem by adding the type signature: sum :: (Num a) => [a] -> a Also note that this problem would not have arisen if we had written: sum xs = foldl (+) 0 xs because the restriction only applies to pattern bindings. we need to be sure we can take advantage of the special properties of the domains of these functions. 13 Arrays Ideally.
a naive implementation of such an array semantics would be intolerably ineÆcient. we have a function that produces an empty array of a given size and another that takes an array. does not treat arrays as general functions with an application operation. Obviously. and a value. producing a new array that diers from the old one only at the given index. Haskell. but as abstract data types with a subscript operation. therefore. either requiring a new copy of an array for each incremental rede.nite contiguous subsets of the integers. Two main approaches to functional arrays may be discerned: incremental and monolithic definition. an index. In the incremental case.
thus. without reference to intermediate array values. constructs an array all at once.nition. serious attempts at using this approach employ sophisticated static analysis and clever run-time devices to avoid excessive copying. on the other hand. Although Haskell has an incremental array update operator. The monolithic approach. Arrays are not part of the Standard Prelude|the standard library contains the array operators.1 Index types The Ix library de. 13. the main thrust of the array facility is monolithic. or taking linear time for array lookup. Any module using arrays must import the Array module.
Bool. We regard the primitive types as vector indices. Integer. and tuples as indices of multidimensional rectangular arrays. in addition. instances may be automatically derived for enumerated and tuple types. Char.a) a -> Int inRange :: (a.nes a type class of array indices: class (Ord a) => Ix a where range :: (a.a) -> [a] index :: (a. and tuples of Ix types up to length 5. Note that the .a) -> a -> Bool Instance declarations are provided for Int.
these are typically the bounds (.rst argument of each of the operations of class Ix is a pair of indices.
rst and last indices) of an array. such bounds would be written in a .9). For example.1).(100. while a 100 by 100 1-origin matrix might have the bounds ((1. zero-origin vector with Int indices would be (0.100)). (In many other languages. the bounds of a 10-element.
but the present form .60 13 ARRAYS form like 1:100. 1:100.
4] [(0.2 Array Creation Haskell's monolithic array creation function forms an array from a pair of bounds and a list of index-value pairs (an association list): array :: (Ix a) => (a.(1. (0.2).a) -> [(a.0). (1. (0. in index order.4) range ((0.2. since each bound is of the same type as a general index. the operation yields the zero-origin ordinal of the index within the range.1).2)) (1.2)] The inRange predicate determines whether an index lies between a given pair of bounds.0).) The range operation takes a bounds pair and produces the list of indices lying between those bounds.3. the index operation allows a particular element of an array to be addressed: given a bounds pair and an in-range index.1.2)) ) ) [0.9) 2 1 ) index ((0.0). (For a tuple type. for example.b)] -> Array a b Here.1) ) 4 13. this test is performed component-wise. (1. is a de. range (0.(1. For example.1).ts the type system better.) Finally.0). (1. for example: index (1.
i*i) | i <.100) [(i.nition of an array of the squares of numbers from 1 to 100: squares = array (1. this usage results in array expressions much like the array comprehensions of the language Id [6]. in fact. Array subscripting is performed with the in.100]] This array expression is typical in using a list comprehension for the association list.[1... f i) | i <.a) -> Array a b = array bnds [(i.x operator !.range bnds] Thus.
Many arrays are de.ne squares as mkArray (\i -> i * i) (1.100).
a!(i-2) + a!(i-1)) | i <.n) ([(0.n]]) .[2. 1). that is. Here. (1. with the values of some elements depending on the values of others. 1)] ++ [(i.. we have a function returning an array of Fibonacci numbers: fibs :: Int -> Array Int Int fibs n = a where a = array (0. for example.ned recursively.
61 13.3 Accumulation Another example of such a recurrence is the n by n wavefront matrix. in which elements of the .
rst row and .
j)) | i <.n)) ([((1.rst column all have the value 1 and other elements are sums of their neighbors to the west.j-1) + a!(i-1. 1) | i <. j <.. northwest.n].n]] ++ [((i. the recurrence dictates that the computation can begin with the .[1.[2.1).j-1) + a!(i-1..j)..(n.Int) Int = a where a = array ((1.n]] ++ [((i.n]]) The wavefront matrix is so called because in a parallel implementation.. a!(i. 1) | j <.1). and north: wavefront wavefront n :: Int -> Array (Int.[2.j).[2.
traveling from northwest to southeast. It is important to note. however. that no order of computation is speci.rst row and column in parallel and proceed as a wedge-shaped wave.
and indeed. we must do this in general for an array be fully de.ed by the association list. we have given a unique association for each index of the array and only for the indices within the bounds of the array. In each of our examples so far.
but the value of the array at that index is then unde. An association with an out-of-bounds index results in an error. if an index is missing or appears more than once. there is no immediate error.ned. however.
a) -> [Assoc a c] -> Array a b The . so that subscripting the array with such an index yields an error. the result is called an accumulated array: accumArray :: (Ix a) -> (b -> c -> b) -> b -> (a.3 Accumulation We can relax the restriction that an index appear at most once in the association list by specifying how to combine multiple values associated with a single index. 13.ned.
1) | i <.a) * s) s = 10 / (b . b ). zero. inRange bnds i] Suppose we have a collection of measurements on the interval [a . the accumulating function is (+).is. and the remaining arguments are bounds and an association list. as with the array function.rst argument of accumArray is the accumulating function. Typically. this function takes a pair of bounds and a list of values (of an index type) and yields a histogram.a) . and we want to divide the interval into decades and count the number of measurements within each: decades decades a b :: (RealFrac a) => a -> a -> [a] -> Array Int Int = hist (0. for example. and the initial value.9) .a) -> [a] -> Array a b = accumArray (+) 0 bnds [(i. that is. map decade where decade x = floor ((x . the second is an initial value (the same for each element of the array). Integral b) => (a. a table of the number of occurrences of each value within the bounds: hist hist bnds is :: (Ix a.
62 13 ARRAYS 13.4 Incremental updates In addition to the monolithic array creation functions. Haskell also has an incremental array update function. written as the in.
is written a // [(i. an array a with element i updated to v. the simplest case. v)]. the indices in the association list must be unique for the values to be de.b)] -> Array a b As with the array function. The reason for the square brackets is that the left argument of (//) is an association list. usually containing a proper subset of the indices of the array: (//) :: (Ix a) => Array a b -> [(a.x operator //.
b) c -> Array (a.j).[jLo.(iHi.j). Ix b.b) c swapRows i i' a = a // ([((i . a!(i'. Never fear. ((i'. it's like writing two loops where one will do in an imperative language.jLo). we can perform the equivalent of a loop fusion optimization in Haskell: swapRows i i' a = a // [assoc | j <..j).ned.. here is a function to interchange two rows of a matrix: swapRows :: (Ix a.jHi].(iHi. Enum b) => a -> a -> Array (a. assoc <.j)).. taking advantage of overloading to de. For example.j). a slight ineÆciency.jHi)) = bounds a The concatenation here of two separate list comprehensions over the same list of j indices is.j)) | j <.[((i .jHi]] ++ [((i'. a!(i .[jLo.j)) | j <.jLo).jHi]]) where ((iLo. a!(i.5 An example: Matrix Multiplication We complete our introduction to Haskell arrays with the familiar example of matrix multiplication.[jLo.jHi)) = bounds a 13. however. a!(i'. j))] ] where ((iLo.
uj') ] where ((li. Ix c.(ui.lj').j) | k <. if we are careful to apply only (!) and the operations of Ix to indices.range (li.(ui. Num d) => Array (a. For simplicity.k) * y!(k.ui). j <.ne a fairly general function. and moreover.(ui'.uj')) | otherwise = error "matMult: incompatible bounds" . Since only multiplication and addition on the element type of the matrices is involved.c) d matMult x y = array resultBounds [((i. however.uj)]) | i <.uj)) = bounds x ((li'.uj)==(li'.uj')) = bounds y resultBounds | (lj.j). we get a function that multiplies matrices of any numeric type unless we try hard not to. that the bounds be equal: matMult :: (Ix a.range (lj. we require that the left column indices and right row indices be of the same type.lj'). sum [x!(i.b) d -> Array (b. Additionally.ui') = ((li. Ix b. we get genericity over index types. the four row and column index types need not all be the same.c) d -> Array (a. and in fact.lj).range (lj'.
we can also de.13.5 An example: Matrix Multiplication 63 As an aside.
ui).(ui'.(ui.uj)]) | i <.j).uj') k <.ui') = ((li.range (lj.j)) | i <.lj').(ui'.k) * y!(k.uj')) | otherwise = error "matMult: incompatible bounds" We can generalize further by making the function higher-order.uj)) = bounds x ((li'.ui).lj').c) e -> Array (a.uj')) = bounds y resultBounds | (lj.j). Ix b. j <.(ui. resulting in a presentation that more closely resembles the usual formulation in an imperative language: matMult x y = accumArray (+) 0 resultBounds [((i.lj). x!(i. j <.j) | k <.k) `star` y!(k.c) g genMatMult sum' star x y = array resultBounds [((i.range (lj.ne matMult using accumArray.uj') ] where ((li.range (lj'. sum' [x!(i.ui') = ((li.lj'). simply replacing sum and (*) by functional parameters: genMatMult :: (Ix a.uj)==(li'.b) d -> Array (b.uj)) = bounds x ((li'.(ui. Ix c) => ([f] -> g) -> (d -> e -> f) -> Array (a.uj')) = bounds y resultBounds | (lj.lj).range (li.lj').uj)==(li'.uj')) | otherwise = error "matMult: incompatible bounds" APL fans will recognize the usefulness of functions like the following: genMatMult maximum (-) genMatMult and (==) With the .range (lj'.uj) ] where ((li.(ui.range (li.
rst of these. the arguments are numeric matrices. the arguments are matrices of any equality type. and the (i . j ) is True if and only if the i -th row of the . j )-th element of the result is the maximum dierence between corresponding elements of the i -th row and j -th column of the inputs. and the result is a Boolean matrix in which element (i . In the second case.
but merely appropriate for the function parameter star. Notice that the element types of genMatMult need not be the same. We could generalize still further by dropping the requirement that the .rst argument and j -th column of the second are equal as vectors.
clearly.rst column index and second row index types be the same. two matrices could be considered conformable as long as the lengths of the columns of the .
The reader may wish to derive this still more general version.) . (Hint: Use the index operation to determine the lengths.rst and the rows of the second are equal.
Here you will .64 14 REFERENCES The Next Stage A large collection of Haskell resources is available on the web at haskell.org.
4 of this tutorial. 15 Acknowledgements Thanks to Patricia Fasel and Mark Mundt at Los Alamos. 1992. How to replace failure by a list of successes. Report on the Programming Language Haskell 98. 1984. Yale University. [10] P. Haskell compilers or interpreters run on almost all hardware and operating systems. September 1990. Department of Computer Science Tech Report YALEU/DCS/RR-1106. and application of functional programming languages. Springer Verlag. Burlington. A Non-strict Purely Functional Language. Conception. [3] P. Yale University. ACM Computing Surveys. and David Rochberg at Yale University for their quick readings of earlier drafts of this manuscript. Wadler. [5] Simon Peyton Jones (editor) The Haskell 98 Library Report. 201. Prentice Hall. Clinger (eds. December 1986. Steele Jr. [4] Simon Peyton Jones (editor). Wadler. Digital Press. 1995. Special thanks to Erik Meijer for his extensive comments on the new material added for version 1.0) reference manual. [8] G. Bird. Mass. 1998. Laboratory for Computer Science. Introduction to Functional Programming using Haskell. Feb 1999. Feb 1999. pages 113{ 128. evolution.). 1985. Monads for Functional Programming In Advanced Functional Programming . Technical report. Introduction to Functional Programming System Using Haskell. Massachusetts Institute of Technology. [7] J. Nikhil. Sandra Loosemore. [2] A. Common Lisp: The Language. Rees and W. 21(3):359{411. The Hugs system is both small and portable { it is an excellent vehicle for learning Haskell. Martin Odersky. Charles Consel. The revised3 report on the algorithmic language Scheme. Department of Computer Science Tech Report YALEU/DCS/RR-1105. and Nick Carriero. New York. In Proceedings of Conference on Functional Programming Languages and Computer Architecture. SIGPLAN Notices. papers.S. LNCS Vol. Id (version 90. and much valuable information about Haskell and functional programming.Davie. Cambridge University Press. Springer Verlag. [6] R. . demos. 1989. LNCS 925. [9] P. 21(12):37{79. References [1] R.. Amir Kishon.nd compilers. Hudak.L. | https://pt.scribd.com/doc/51174776/haskell-98-tutorial | CC-MAIN-2017-09 | refinedweb | 24,882 | 69.58 |
Topic 10 Equity Valuation Models Intrinsic value versus market price Dividend discount models (DDM) The constant-growth DDM Stock prices and investment opportunities Life cycles and multistage growth models Price-earnings (P/E)
The constant-growth DDM
Stock prices and investment opportunities
Life cycles and multistage growth models
Intrinsic Value versus Market Price
Assume a one-year holding period.
Suppose that ABC stock has:
Question:
Is the stock attractively priced today given your forecast of next year’s price?
The expected holding-period return (HPR):
Expected HPR =
The stock’s expected HPR is the sum of:
The required rate of return for ABC stock:
From the CAPM, when stock market prices are at equilibrium levels, the rate of return that investors can expect to earn on a security is:
This is the return that investors will require of a security given its risk as measured by beta.
Compare the intrinsic value of a share of stock to its market price.
The intrinsic value (V0) of a share of stock:
The present value of all expected cash payments to the investor in the stock (including expected dividends as well as the proceeds expected from the ultimate sale of the stock) discounted at the appropriate risk-adjusted interest rate, k.
Whenever the intrinsic value (i.e. the investor’s own estimate of what the stock is really worth) exceeds the market price, the stock is considered undervalued and a good investment.
In case of ABC stock:
Because intrinsic value ($50) exceeds current price ($48), the stock is undervalued in the market.
Thus, investors will want to buy ABC.
Note: k is the discount rate, the required rate of
return, or the market capitalization rate.
Dividend Discount Models (DDM)
Notations:
Dt: expected dividend to be received at the end of year t.
Suppose the investor plans to hold the stock forever.
The dividend discount model (DDM):
The current value of a share of common stock is the sum of all future expected dividend payments discounted to the present, no matter what the investor’s holding horizon is.
It is incorrect to conclude that the DDM focuses exclusively on dividends and ignores capital gains as a motive for investing in stock.
Indeed, capital gains (as reflected in the expected sales price) are part of the stock’s value.
The price at which you can sell a stock in the future depends on dividend forecasts at that time.
For ABC stock:
If g = 0.05, and the most recently paid dividend was D0= 3.81, then expected future dividends are:
The larger its expected dividend per share.
The lower the market capitalization rate, k.
The higher the expected growth rate of dividends.
Suppose a stock is selling at its intrinsic value, i.e.
For a stock whose market price equals its intrinsic value (P0 = V0), the expected holding-period return will be:
E(r) = k = dividend yield + capital gains yield
The discounted cash flow (DCF) formula:
i.e.by observing the dividend yield (D1/P0)and
estimating the growth rate of dividends (g), we can
compute k.
Stock prices and investment opportunities
X pays out all of its earnings as dividends, maintaining a perpetual dividend flow of $5 per share.
If k = 12.5%, X would then be valued at:
D1/k = $5/12.5% = $40 per share.
X would not grow in value, because with all earnings paid out as dividends, and no earnings reinvested in the firm, capital stock and earnings capacity would remain unchanged over time; earnings and dividends would not grow.
Now suppose X engages in projects that generate a return on investment of 15%, which is greater than the required rate of return, k = 12.5%.
It would be foolish for such a company to pay out all of its earnings as dividends.
If X retains or plows back some of its earnings into its highly profitable projects, it can earn a 15% rate of return for its shareholders, whereas if it pays out all earnings as dividends, it forgoes the projects, leaving shareholders to invest the dividends in other opportunities at a fair market rate of only 12.5%.
Suppose that X chooses a lower dividend payout ratio (the fraction of earnings paid out as dividends), reducing payout from 100% to 40%, maintaining a plowback ratio (the fraction of earnings reinvested in the firm) at 60%. The plowback ratio is also referred to as the earnings retention ratio.
The dividend of the company will be $2 (= 40% $5 earnings) instead of $5.
Although dividends initially fall under the earnings reinvestment policy, subsequent growth in the assets of the firm because of reinvested profits will generate growth in future dividends, which will be reflected in today’s share price.
How much growth will be generated?
Suppose X starts with plant and equipment of $100 million and is all equity financed.
With a return on investment or equity (ROE) of 15%:
total earnings = ROE $100 million
= 15% $100 million = $15 million.
There are 3 million shares of stock outstanding, so earnings per share are $5 (= $15 million/3 million).
If 60% of the $15 million in this year’s earnings is reinvested, then the value of the firm’s capital stock will increase by:
0.60 $15 million = $9 million, or by 9%.
i.e. The percentage increase in the capital stock:
= ROE the plowback rate (b)
= 15% 60% = 9%.
Now endowed with 9% more capital, the company earns 9% more income, and pays out 9% higher dividends.
The growth rate of the dividends is:
g = ROE b = 15% 60% = 9%.
If the stock price equals its intrinsic value, it should sell at:
When X reduces current dividends and reinvest some of its earnings in new investments, its stock price increases.
The increase in the stock price reflects the fact that the planned investments provide an expected rate of return greater than the required rate.
That is, the investment opportunities have positive net present value (NPV). The value of the firm rises by the NPV of these investment opportunities.
This NPV is called the present value of growth opportunities (PVGO).
= the value of assets already in place (i.e. the no-
growth value of the firm)
+ the NPV of the future investments the firm will
make (i.e. the PVGO)
i.e. Price = No-growth value per share + PVGO
57.14 = 40 + 17.14
If the firm’s projects yield only what investors can earn on their own, shareholders cannot be made better off by a high reinvestment rate policy.
To justify reinvestment, the firm must engage in projects with better prospective returns than those shareholders can find elsewhere.
Price = No-growth value per share + PVGO
Life cycles and multistage growth models
In early years, there are ample opportunities for profitable reinvestment in the company. Payout ratios are low, and growth is correspondingly rapid.
In later years, the firm matures, attractive opportunities for reinvestment may become harder to find. In this mature phase, the firm may choose to increase the dividend payout ratio, rather than retain earnings. The dividend level increases, but thereafter it grows at a slower rate because the company has fewer growth opportunities.
To compute the intrinsic value, follow the following 3 steps:
the nonconstant growth period.
Price-Earnings (P/E) Ratio
Price-earnings multiple:
the ratio of price per share to earnings per share, commonly called the P/E ratio.
The P/E ratio and growth opportunities
Price = No-growth value per share + PVGO
P0 = E1/k and P/E ratio = 1/k.
PVGO P/E ratio.
The P/E ratio might serve as a useful indicator of expectations of growth opportunities.
A high P/E multiple indicates that a firm enjoys ample growth opportunities.
The impact of the plowback rate (b) on the P/E ratio:
(i) If ROE > k, then b P/E ratio.
When ROE exceeds k, the firm offers attractive investment opportunities, so the market will reward it with a higher P/E multiple if it exploits those opportunities more aggressively by plowing back more earnings into those opportunities.
(ii) If ROE < k, then b P/E ratio.
When ROE < k, investors prefer that the firm pay out earnings as dividends rather than reinvest earnings in the firm at an inadequate rate of return.
That is, for ROE < k, P/Efalls as plowback increases.
(iii) If ROE = k, then b P/E ratio does not change.
The impact of stock risk on the P/E ratio:
Riskier stocks
have higher required rates of return (k)
Note:
This is true even outside the context of the constant-growth model.
For any expected earnings and dividend stream, the present value of those cash flows will be lower when the stream is perceived to be riskier.
Hence the stock price and P/E ratio will be lower.
Combining P/E analysis and the DDM
Recall the example:
D1 = $0.17
D2 = $0.183
D3 = $0.197
D4 = $0.21
Dividends enter their constant-growth phase at the end of year 4.
The forecasted data for year 4:
P/E ratio: 25.
EPS: $2.20.
the estimate of share price for year 4:
25 $2.20 = $55.
Other comparative valuation ratios
The P/E ratio is an example of a comparative valuation ratio. Such ratios are used to assess the valuation of one firm versus another based on a fundamental indicator such as earnings.
Other such comparative ratios are commonly used:
The ratio of price per share divided by book value per share.
Book value is the net worth of a company as shown on the balance sheet.
Price-to-cash-flow ratio:
Earnings as reported on the income statement can be affected by the company’s choice of accounting practices, and thus are commonly viewed as subject to some imprecision and even manipulation.
In contrast, cash flow—which tracks cash actually flowing into or out of the firm—is less affected by accounting decisions.
Some analysts use operating cash flow when calculating this ratio.
Others prefer “free cash flow” (= operating cash flow - new investment).
Many start-up firms have no earnings. Thus, the P/E ratio for these firms is meaningless.
The price-to-sales ratio (the ratio of stock price to the annual sales per share) has recently become a popular valuation benchmark for these firms.
Of course, price-to-sales ratios can vary markedly across industries, since profit margins vary widely. Nevertheless, use of this ratio has increased substantially in recent years.
Market valuation statistics:
While the levels of these ratios differ considerably, for the most part, they track each other fairly closely, with upturns and downturns at the same times.
The Free Cash Flow Approach to
Valuing the Equity in a Firm
To make this happen, the firm will have to invest an amount equal to 15% of pretax cash flow each year.
i.e. the value of the whole firm = $15,370,000.
Note:
• the value of the whole firm
= the value of debt + the value of equity
• the value of debt = $2,000,000
the value of equity = $13,370,000.
Inflation and Equity Valuation
Consider a firm X that pays out all earnings as dividends.
Earnings and dividends per share are $1, and there is no growth.
Consider an equilibrium real capitalization rate (k*)of 10% per year.
The price per share of X stock:
Inflation (i)is 6% per year, but the values of the other economic variables adjust so as to leave their real values unchanged.
The nominal capitalization rate (k):
k = (1 + k*)(l + i)- 1 = 1.10 1.06 - 1 = 16.6%.
The expected nominal growth rate of dividends (g)is now 6%, which is necessary to maintain a constant level of real dividends.
Thus, the nominal dividend expected at the end of this year is $1.06 per share.
The effect of inflation on earnings, plowback ratio, and P/E ratio:
Last year there was no inflation. The inventory cost $10 million. Labor, rent, and other processing costs (paid at year-end) were $1 million, and revenue was $12 million.
Assuming no taxes:
All earnings are distributed as dividends to the 1 million shareholders.
Because the only invested capital is the $10 million in inventory, the ROE is 10% (= $1 million/$10 million).
Because inventory is paid for at the beginning of the year, it will still cost $10 million.
However, revenue will be $12.72 (= $12 1.06) million, and other costs will be $1.06 (= $1 1.06) 1 million.
The amount required to replace inventory at year’s end is $10.6 million (rather than the beginning cost of $10 million), so the amount of cash available to distribute as dividends is $1.06 million (not the reported earnings of $1.66 million).
A dividend of $ 1.06 million would be just enough to keep the real value of dividends unchanged and at the same time allow for maintenance of the same real value of inventory.
That is, the reported earnings of $1.66 million overstate true economic earnings.
Inventory must rise from a nominal level of $10 million to a level of $10.6 million to maintain its real value.
This inventory investment requires reinvested earnings of $0.6 million.
We have seen that as long as real values are unaffected, the stock’s price is unaffected by inflation.
Higher inflation is associated with greater uncertainty about the economy, which tends to induce a higher required rate of return on equity and hence a lower level of stock prices.
Investors mistake the rise in nominal rate of interest for a rise in the real rate.
As a result, they undervalue stocks in a period of higher inflation. | https://www.slideserve.com/issac/topic-10 | CC-MAIN-2018-51 | refinedweb | 2,286 | 63.59 |
Writing Resource Properties
Microsoft® Windows® 2000 Scripting Guide
In Windows 2000, WMI is primarily a read-only technology; you use it mainly to retrieve information about managed resources. However, some WMI properties are read/write. This means you can use a script not only to retrieve the values of these properties but also to configure those values.
For example, the script in Listing 6.25 retrieves all instances of the Win32_OSRecoveryConfiguration class. (In this case, the class contains only a single instance.) The script provides new values for properties such as DebugInfoType and DebugFilePath and then applies the changes (and thus configures operating system recovery options) by using the Put_ method. If you do not call the Put_ method, the changes will not be applied.
Note
This template works only for properties that are writable. Attempting to change a read-only property will result in an error.
Listing 6.25 Template for Writing Resource Properties
To use this template with other WMI classes and to configure other WMI properties:
Set the value of strClassName to the name of the WMI class.
If necessary, set the value of strNamespace to the appropriate WMI namespace.
Replace the statements within the For Each loop that configure new property values. Remove the following lines, and replace them with the appropriate lines of code for the properties being modified: | https://technet.microsoft.com/en-us/library/ee156561.aspx | CC-MAIN-2017-39 | refinedweb | 224 | 55.64 |
> > Hi list, I've been following a discussion on a new way of defining > > getters and setters on python-dev and just can't understand what the > > purpose is. Everybody agreed on the dev list that this is a good idea > > so I guess it must be right :) > > > > The whole thing started with this post of Guido: > > > > > > > > which then continued into November. Basically, the idea is that using > > the new way a setter can be added to property that was read-only > > before. But if I have this already, > > > > class C: > > @property > > def attr( self ): return self._attr > > > > what prevents me using the following for adding a setter for attr: > > > > class C: > > def attr( self ): return self._attr > > def set_attr( self, value ): self._attr = value > > attr = property( attr, set_attr ) > > > > In other words all I needed to do is delete @property, write the > > setter method and add attr = property( attr, set_attr ). What does the > > new way improve on this? > > It prevents namespace-pollution in a clever way. By first defining the > getter, the @propset-decorator will augment the already createt property > and return it. > > Thus you don't end up with a > > set_attr > > function. > > > Other, more complex recipes to do the same look like this and are much > harder to grasp: > > > @apply > def my_property() > def fget(self): > return self._value > def fset(self, value): > self._value = value > return property(**locals()) > > So the proposed propset-decorator certainly makes things clearer. > > Diez Aaaaaha :) Makes sense indeed. Thanks, Daniel | https://mail.python.org/pipermail/python-list/2007-November/452654.html | CC-MAIN-2014-15 | refinedweb | 245 | 64.41 |
An open source library for statistical plotting
Project description
Lets-Plot for Python
- Overview
- Installation
- Quick start with Jupyter
- Example Notebooks
- GGBunch
- Data Sampling
- Export to File
- Formatting
- The 'bistro' Package
- Geospatial
- 'No Javascript' Mode
- Offline Mode
- Interesting Demos
- Scientific Mode in IntelliJ IDEA / PyCharm
- What is new in 2.0.0
- Change Log
- License
Overview
The
Lets-Plot for Python library includes a native backend and a Python API, which was mostly based on the
ggplot2 package well-known to data scientists who use R.
R
ggplot2 has extensive documentation and a multitude of examples and therefore is an excellent resource for those who want to learn the grammar of graphics.
Note that the Python API being very similar yet is different in detail from R. Although we have not implemented the entire ggplot2 API in our Python package, we have added a few new features to our Python API.
You can try the Lets-Plot library in Datalore. Lets-Plot is available in Datalore out-of-the-box (i.e. you can ignore the Installation chapter below).
The advantage of Datalore as a learning tool in comparison to Jupyter is that it is equipped with very friendly Python editor which comes with auto-completion, intentions, and other useful coding assistance features.
Begin with the quickstart in Datalore notebook to learn more about Datalore notebooks.
Watch the Datalore Getting Started Tutorial video for a quick introduction to Datalore.
Installation
1. For Linux and Mac users:
To install the Lets-Plot library, run the following command:
pip install lets-plot
2. For Windows users:
Install Anaconda3 (or Miniconda3), then install MinGW toolchain to Conda:
conda install m2w64-toolchain
Install the Lets-Plot library:
pip install lets-plot
Quick start with Jupyter
You can use Lets-Plot in Jupyter notebook or other notebook of your choice, like Datalore, Kaggle or Colab.
To evaluate the plotting capabilities of Lets-Plot, add the following code to a Jupyter notebook:
import numpy as np from lets_plot import * LetsPlot.setup_html() np.random.seed(12) data = dict( cond=np.repeat(['A','B'], 200), rating=np.concatenate((np.random.normal(0, 1, 200), np.random.normal(1, 1.5, 200))) ) ggplot(data, aes(x='rating', fill='cond')) + ggsize(500, 250) \ + geom_density(color='dark_green', alpha=.7) + scale_fill_brewer(type='seq') \ + theme(axis_line_y='blank')
Example Notebooks
See Example Notebooks.
GGBunch
GGBunch allows to show a collection of plots on one figure. Each plot in the collection can have arbitrary location and size. There is no automatic layout inside the bunch.
Data Sampling
Sampling is a special technique of data transformation, which helps dealing with large datasets and overplotting.
Learn more: Data Sampling.
Export to File
The
ggsave() function is an easy way to export plot to a file in SVG or HTML formats.
Note: The
ggsave() function currently do not save images of interactive maps to SVG.
Example notebook: export_SVG_HTML
Formatting
Lets-Plot supports formatting of values of numeric and date-time types.
Complementary to the value formatting, a string template is also supported.
For example:
value: 67719.94988293362 + string template: "Mean income: £{.2s}" = the formatting result: "Mean income: £67k"
An empty placeholder {} is also allowed. In this case a default string representation will be shown. This is also applicable to categorical values.
To learn more about format strings see: Formatting.
In Lets-Plot you can use formatting for:
- tooltip text, see: Tooltip Customization.
- labels on X/Y axis. See: Formatting demo.
- the
geom_text()labels. See: Label format demo.
- facetting values in
facet_grid(),
facet_wrap()functions. See: Facets demo.
The 'bistro' Package
The 'bistro' package is a collection of higher level API functions, each allows to create a certain kind of plot with a single function call instead of combining a plethora of plot features manually.
Correlation Plot
from lets_plot.bistro.corr
The
corr_plot() function creates a fluent builder object offering a set of methods for
configuring of beautiful correlation plots. A call to the terminal
build() method in the end
will create a resulting plot object.
Example: correlation_plot.ipynb
Image Matrix
from lets_plot.bistro.im
The
image_matrix() function arranges a set of images in a grid.
Example: image_matrix.ipynb
The
image_matrix() function uses
geom_image under the hood, so you might want to check out these demos as well:
Geospatial
GeoPandas Support
GeoPandas
GeoDataFrame is supported by the following geometry layers:
geom_polygon,
geom_map,
geom_point,
geom_text,
geom_rect.
Learn more: GeoPandas Support.
Interactive Maps
Interactive maps allow zooming and panning around geospatial data that can be added to the base-map layer using regular ggplot geoms.
Learn more: Interactive Maps.
Geocoding
Geocoding is the process of converting names of places into geographic coordinates.
The Lets-Plot has built-in geocoding capabilities covering the folloing administrative levels:
- countries
- states (US and non-US equivalents)
- counties (and equivalents)
- cities (and towns)
'No Javascript' Mode
In the 'no javascript' mode Lets-Plot genetares plots as bare-bones SVG images.
This mode is halpfull when there is a requirement to render notebooks in an 'ipnb' renderer which does not suppopt javascript (like GitHub's built-in renderer).
Activate 'no javascript' mode using the
LetsPlot.setup_html() method call:
from lets_plot import * LetsPlot.setup_html(no_js=True)
Alternativaly, you can set up the environment variable:
LETS_PLOT_NO_JS = true (other accepted values are: 1, t, y, yes)
Note: interactive maps do not support the 'no javascript' mode.
Offline Mode
In classic Jupyter notebook the
LetsPlot.setup_html() statement by default pre-loads
Lets-Plot JS library from CDN.
Alternatively, option
offline=True will force
Lets-Plot adding the full Lets-Plot JS bundle to the notebook.
In this case, plots in the notebook will be working without an Internet connection.
from lets_plot import * LetsPlot.setup_html(offline=True)
Note: internet connection is still required for interactive maps and geocoding API.
Interesting Demos
A set of interesting notebooks using
Lets-Plot library for visualization.
Scientific mode in IntelliJ IDEA / PyCharm
Plugin "Lets-Plot in SciView" is available at the JetBrains Plugin Repository.
The plugin adds support for interactive plots in IntelliJ-based IDEs with the enabled Scientific mode.
To learn more about the plugin check: Lets-Plot in SciView plugin homepage.
What is new in 2.0.0
Python 3.9 support
Faceted plots:
- new
facet_wrap()function.
- ordering of faceting values.
- formatting of faceting values.
See: Facets demo
new
formatparameter on scales: formatting tick labels on X/Y axis.
Example:
scale_x_datetime(format="%b %Y") scale_x_continuous(format='is {.2f}')
Demo: Formatting demo
See also: Formatting
Tooltips:
- new
coloroption: overrides the default tooltip color:
geom_xxx(tooltips=layer_tooltips().color('red'))Learn more: Tooltip Customization.
- crosshair cursor when tooltip is in a fixed position specified by the
anchoroption.
Brand new Geocoding API.
Note: This is a breaking change! Hence we bumped the Lets-Plot version to 2.0.0.
In the Lets-Plot v2.0.0 the peviouse Geocoding API is no longer working.
The old version of geocoding backend remains on-line for a couple of release cycles to continue support of prior Lets-Plot versions.
To learn more about new Geocoding API see: Geocoding.
See CHANGELOG.md for other changes and fixes.
Change Log
See CHANGELOG.md
License
Code and documentation released under the MIT license. Copyright © 2019-2020, JetBrains s.r.o.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/lets-plot/ | CC-MAIN-2021-10 | refinedweb | 1,225 | 50.33 |
Listening for SCO Connections
Once the RFCOMM connection is established, the audio gateway will connect and release an SCO connection as needed. Recall that the SCO connection carries audio data in both directions.
Creating an SCO connection is nearly identical to creating a RFCOMM connection. The main difference is, SCO connections do not specify a channel: to connect to a remote host, only the host address is specified. Of course, SCO sockets also use different constants and structs. Listing Four provides an example:
Listing Four
#include "btinclude.h" int main() { int sock; int client; unsigned int len = sizeof(struct sockaddr_sco); struct sockaddr_sco local; struct sockaddr_sco remote; char pszremote[18]; sock = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); local.sco_family = AF_BLUETOOTH; local.sco_bdaddr = *BDADDR_ANY; if (bind(sock, (struct sockaddr*)&local, sizeof(struct sockaddr_sco)) < 0) return -1; if (listen(sock, 1) < 0) return -1; client = accept(sock, (struct sockaddr*)&remote, &len); ba2str(&remote.sco_bdaddr, pszremote); printf("sco received connection from: %s\n", pszremote); return 0; }
Following the Signaling Diagrams in the HSP Profile Document
From a BlueZ API standpoint, all of the pieces required to implement the headset profile have been covered. What we haven't discussed is how the headset and audio gateway interact. Interaction between the devices is described in signaling diagrams.
Understanding the signaling diagrams is important in order to know what types of scenarios your program needs to handle. While looking at the diagrams, keep in mind that we're implementing the headset (HS) side. Let's examine the incoming audio connection establishment from page 210 of the HSP profile document. Figure 3 is the table from the document:
Figure 3.
The signaling diagram can be viewed as a sequence of mandatory and optional events that happen from the top down. The first event is the establishment of an RFCOMM connection, represented by the arrow labeled Connection establishment. This connection is initiated by the audio gateway. Note that the RFCOMM connection can also be initiated by the headset side as indicated on page 212 of the HSP document.
Next is a
RING event, which is generated by an incoming phone call. When the audio gateway receives an incoming phone call, it will send the text
RING to the headset. Optionally, the headset will establish a SCO connection and send an in-band ring tone. The audio gateway will continually send
RING to the headset until the headset responds with
AT+CKPD=200. After receiving this response, the audio gateway responds with
OK and then initiates the SCO connection if the connection does not yet exist.
Debugging with hcidump
If you plan to do Bluetooth programming in Linux, hcidump is an excellent debugging tool. I'm going to cover the very basics of how to translate the output from hcidump using the Bluetooth core specification document.
One place where hcidump becomes useful is when your Bluetooth device doesn't seem to be connecting to your program. If you have hcidump running and you don't see any output, the device is not even communicating with your Bluetooth adapter.
The hcidump program contains a number of options for filtering and logging to files or sockets. We won't filter any events and we'll let the output write to the screen. The only option we'll turn on is the hex and ascii output option. Here's the command:
sudo hcidump -X.
Here's sample output from my phone connecting to the sample bths program (with modified Bluetooth addresses):
> HCI Event: Connect Request (0x04) plen 10 0000: 00 11 22 33 44 55 0c 02 5a 01 u.4Q....Z. < HCI Command: Accept Connection Request (0x01|0x0009) plen 7 0000: 00 11 22 33 44 55 00 u.4Q... > HCI Event: Command Status (0x0f) plen 4 0000: 00 01 09 04 .... > HCI Event: Role Change (0x12) plen 8 0000: 00 00 11 22 33 44 55 00 .u.4Q...
To interpret the results, turn to Volume 2 (Core System Package), Part E (Host Controller Interface Specification), 7 (HCI Commands and Events) of Core V2.1 + EDR document (this is the core specification file mentioned in the Bluetooth profiles section of this article).
The first line of the sample hcidump output is an event. Events are listed under 7.7. The output tells us the event is a Connect Request (event code 0x04). Connect request is documented in section 7.7.4. Table 1 shows a screenshot of the table.
Table 1.
This table tells us the parameters of a connection request are a 6 byte Bluetooth address, a 3 byte class field, and a single byte link type field.
The next line in the sample output is a HCI Command Accept Connection Request which is documented in section 7.1.8.
Putting the Pieces Together
All of the examples are provided in separate files. I've also put all the pieces together in a single sample. The sample includes code that sends audio data from your phone to your computers default sound device. If you run the program, pair and connect your phone, and make a phone call, you should here the audio on your computer speakers. However, the program does not take data from your mic and send it to the phone (through the SCO socket). That's an exercise that I leave to you.
Unpack the samples and run make to compile them. Then follow these steps to run the example:
- Disable HSP/HFP: add
Disable=Headset,Gatewayto
/etc/Bluetooth/audio.confunder the
[General]section
- Restart Bluetooth:
sudo service Bluetooth restart
- Run
bthsas root. If the program isn't run as root, it will fail when trying to set the class:
sudo ./bths
- Pair your phone with your machine.
- From your phone, initiate a connection to your machine by selecting your machine in the Bluetooth settings. Upon successful connection from the phone, the program will output
received connection from 00:11:22:33:44:55.
- Initiate a phone call from your phone. After initiating the call, your phone should create a SCO connection to your machine. The bths program will output
sco received connection from 00:11:22:33:44:55, and all audio that you would normally hear on your phone will play through your machine.
The provided example several limitations. One issue is data from the RFCOMM socket is not processed until a SCO connection is initiated. Once both sockets are connected, they are both processed, but the program should process data from the RFCOMM socket even when there's no active SCO connection. This example won't handle incoming calls to your phone for this reason.
Final Observations
This article provides quite a bit of detail on how to interpret and implement Bluetooth profiles. In the introduction, I also promised that you'd learn how to implement a custom profile for configuring a standalone device. Some of the tools to do so are mentioned above, namely RFCOMM sockets, but there are other options as well. Here are a few:
- Custom protocol over an RFCOMM connection. This would be nearly identical to creating a custom protocol over TCP.
- Linux supports serial port emulation over Bluetooth. This option would allow a wireless serial link between machines, over which a custom serial protocol could be implemented. It's also useful for existing programs that require a serial interface.
- Linux supports networking over Bluetooth, often referred to as a Personal Area Network (PAN). This option creates an IP link between devices, allowing protocols such as HTTP to function over Bluetooth. With such a link, one could run a web server on one device and connect to the device with a browser, as mentioned, all over Bluetooth.
If you own an Android phone, you should know that the Bluetooth radio is exposed to the Java API. This allows you to create custom Bluetooth programs on your phone. Now what are the possibilities?
Ben DuPont is a software engineer located in Green Bay, WI. | http://www.drdobbs.com/mobile/using-bluetooth/232500828?pgno=3 | CC-MAIN-2014-23 | refinedweb | 1,320 | 55.74 |
Copyright © 1997,1998 W3C (MIT, INRIA, Keio ), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.
This document is a complete revision of the working draft dated 1998-02-16. In addition to a major rewrite and reorganization, it incorporates some technical changes to the names of certain attributes ('about' and 'resource' and adds a mechanism for making statements about the members of a collection ('aboutEach').. The RDF Model and Syntax Working Group will not allow early implementation to constrain their ability to make changes to this specification prior to final release. address for "Latest version" rather than the addresses for specific working draft versions themselves. The latest version address is the better one to bookmark as it should point to newer revisions as they are published.
Comments on this specification may be sent to www-rdf-comments@w3.org. The archive of public comments is available at.
The World Wide Web suffers from substantial growing pains. It was which will complete the framework. Most importantly, to facilitate the definition of metadata, RDF will have a class system, not unlike community. There are also other areas of technology which contributed to the design; these include object-oriented programming and modeling languages, as well as databases..
The basic data model consists of three object types:
Resources are referred to by a URI.>".I defined by the organization that serves as the unique key for each employee type with the schema that defines the property type. property statements apply. If the resource does not yet exist (i.e. does not yet have a URI) '"' [5] idAttr ::= 'ID="' IDsymbol '"' [6] property ::= '<' propName '>' value '</' propName '>' | '<' propName resourceAttr '/>' [7] propName ::= Qname [8] value ::= description | string [9] resourceAttr ::= 'resource="' URI '"' [10] Qname ::= [ NSname ':' ] name [11] URI ::= (see RFC1738, RFC1808) [12] IDsymbol ::= (any legal XML name symbol) [13] name ::= (any legal XML name symbol) [14] NSname ::= properties in the model instance. The Description element may be thought of (for purposes of the basic RDF syntax) as smiply is given in the about. A Description element without an about attribute creates a new resource. Typically such a resource will be a surrogate, or proxy, for some other real resource that does not have a recognizable URI. This "in-line" resource has a URI. creator of this RDF expression and defined in an XML namespace processing instruction such as:
<?xml:namespace ns="" prefix="s"?>
The URI in the ns attribute of the namespace declaration is a globally unique name for the particular schema this metadata creator is using to define her use of the Creator property type. Other schemas may also define a property type named Creator and the two property types will be distinguished via their schema URIs..-07-20T14:36</s:Date> </rdf:Description> </rdf:RDF>
is equivalent for RDF purposes to
<rdf:RDF> <rdf:Description < property statements when the property value statements can be written as attributes of the Creator element:
<rdf:RDF> <rdf:Description <s:Creator </rdf:Description> </rdf:RDF>
When using this abbreviation form the about attribute of the nested Description element becomes a resource attribute on the property created:Description> <* '</rdf:Description>' | typedNode [6a] property ::= '<' values.types of these container types, in which case production [18] is extended to include the names of those declared subtypes.></rdf:li> <rdf:li></rdf:li> <rdf:li></rdf:li> < is the "thing" a statement is made of? In other words, what is the object the statement is referring to. This object make which all have a number of common properties (property types + values),>
A resource may have multiple properties with the same property type. This is not the same as having a single property whose value properties, one for each committee member, as this would state the vote of each individual member. Rather, it is better to model this as a single approvedBy property whose value is a Bag containing the committee members' identities:
D
Figure 7: Using Bag to indicate a collective opinion believes that Ora Lassila is the creator of the resource
we have said nothing about the resource; instead, we have expressed a fact about a belief Ralph has. In order to express this belief to RDF, we have to model the original statement as a resource with four properties. This process is formally called reification in the Knowledge Representation community. A model of a statement is called a reified statement.
To model statements RDF defines the following property types:
A new resource with the above four properties represents the original statement and can be used as the value of other properties and additional properties can be attached to it. Depending on how we would like to model this example, we could attach another property to the reified statement (say, "BelievedBy") with an appropriate value (in this case, "Ralph Swick"). Using base-level RDF/XML syntax, this could be written as
<rdf:RDF> <rdf:Description> <rdf:propObj <rdf:propName <rdf:value>Ora Lassila</rdf:value> <rdf:instanceOf <BELIEF:BelievedBy>Ralph Swick</BELIEF:Believed. that in-line resource. A Description may have both an ID attribute and a bagID attribute.
Since attaching a bagID to a Description results in including in the model a bag of the reified properties of the Description, we can use this as a syntactic shorthand when making statements about statements. For example, if we wanted to say that Ralph believes that Ora is the creator of and that he also believes that the title of that resource is "Ora's Home Page" we can simply write
<RDF:Description <BELIEF:BelievedBy>Ralph Swick</BelievedBy> </RDF:Description>
Note that this shorthand example includes an additional fact in the model not represented by the example in Figure 8. This shorthand usage expresses both a fact about Ralph's belief and two facts about Ora's home page.:, or
[r] --p--> v:
[] --creator--> "Ora Lassila"
and the corresponding triple (member of Triples) would be
{creator, [], "Ora Lassila"}
The notation [URI] denotes the node representing the resource identified by URI (which '"' [6.8] aboutEachAttr ::= 'aboutEach="' URI '"' '"' [6.18] Qname ::= [ NSname ':' ] name [6.19] URI ::= (see RFC1738, RFC1808) container identifies, the URI which: corresponding to the typeName of the typedNode. Specifically, when a typedNode is given, a triple {RDF:instanceOf,n,t} is created where n is the resource whose URI.
<<to be completed; substantially copied from the 19980216 draft.>> serves as the URI of the corresponding RDF schema..
Revision History:: 1998-07-21T17:05:48Z | http://www.w3.org/TR/1998/WD-rdf-syntax-19980720/ | CC-MAIN-2017-26 | refinedweb | 1,075 | 51.89 |
* Break directive used for interrupting scopes. 24 * 25 * @author <a href="mailto:wyla@removethis.sci.fi">Jarkko Viinamaki</a> 26 * @author Nathan Bubna 27 * @version $Id$ 28 */ 29 public class Break extends Directive 30 { 31 32 /** 33 * Return name of this directive. 34 * @return The name of this directive. 35 */ 36 public String getName() 37 { 38 return "break"; 39 } 40 41 /** 42 * Return type of this directive. 43 * @return The type of this directive. 44 */ 45 public int getType() 46 { 47 return LINE; 48 } 49 50 /** 51 * Since there is no processing of content, 52 * there is never a need for an internal scope. 53 */ 54 public boolean isScopeProvided() 55 { 56 return false; 57 } 58 59 60 } | http://pmd.sourceforge.net/pmd-5.4.1/xref/net/sourceforge/pmd/lang/vm/directive/Break.html | CC-MAIN-2018-09 | refinedweb | 117 | 65.93 |
Hello,
I’m receiving compilation errors when trying to use the Aspose.Pdf.Generator namespace. I know the Generator namespace has been antiquated on the newer versions of the Aspose.Pdf package but I don’t understand why it fails to recognize it when I’m using that older version.
The package is being used on a project a colleague shared with me and for whatever reason he receives no errors when building that project using the exact same Aspose.Pdf package version (18.10) targeting the exact same framework (4.6.1).
Any clarification would be greatly appreciated. I’m very confused | https://forum.aspose.com/t/net-aspose-pdf-version-18-10-generator-namespace-not-found/190726 | CC-MAIN-2022-40 | refinedweb | 103 | 51.34 |
® Turn to the Expertg Installation EQUIPMENT OPERATION OAT sensor must be field Installation for more details. EQUIPMENT This Infinity Interface. TM OPERATION Instructions HAZARD installed. See Accessory HAZARD unit is designed for use with an Infinity User NOTE: Read the entire instruction manual before starting the installation. TABLE OF CONTENTS PAGE SAFETY CONSIDERATIONS ......................... 2 INTRODUCTION ................................... 2 RECEIVING AND INSTALLATION ................. 2-12 Check Equipment .................................. 2 Identify Unit .................................... 2 Inspect Shipment ................................. 2 Provide Unit Support ............................... 2 Roof Curb ...................................... 2 Slab Mount ..................................... 2 Ground Mount .................................. 2 Provide Clearances ................................. 7 Rig and Place Unit ................................. 7 Inspection ...................................... 8 Introduction ..................................... 8 Use of Rigging Bracket ............................ 8 Select and Install Ductwork ........................... 8 Converting Horizontal Discharge Units to Downflow (Vertical) Discharge Units .......................... 9 Provide for Condensate Disposal ..................... 10 Install Flue Hood .................................. 10 Install Gas Piping ................................. 10 Install Electrical Connections ........................ 11 High-Voltage Connections ........................ 11 Routing Power Leads Into Unit ..................... 12 Connecting Ground Lead to Ground Screw ........... 12 Routing Control Power Wires ..................... 12 Accessory Installation ............................ 12 Special Procedures for 208-v Operation .............. 12 PRE-START-UP ................................... 15 START-UP ..................................... 15-26 Unit Start-Up and Troubleshooting ................... 15 Sequence of Operation .......................... 20-24 Check for Refrigerant Leaks ......................... 25 Start-Up Adjustments .............................. 25 Checking Cooling and Heating Control Operation ...... 25 Checking and Adjusting Refrigerant Charge ........... 25 A05307 Fig. 1 - Unit 48XL Refrigerant Charge .............................. 26 No Charge ..................................... 26 Low Charge Cooling ............................. 26 To Use Cooling Charging Charts .................... 26 Non-Communicating Emergency Cooling/Heating Mode .. 26 MAINTENANCE ................................ 28-30 Air Filter ........................................ 28 Indoor Fan and Motor .............................. 28 Inducer Blower ................................... 28 Limit Switch ..................................... 28 Burner Ignition ................................... 28 Main Burners .................................... 28 Inducer Pressure Switch ............................ 28 Outdoor Coil, Indoor Coil, and Condensate Drain Pan ..... 29 Outdoor Fan ..................................... 29 Electrical Controls and Wiring ....................... 29 Refrigerant Circuit ................................. 29 Indoor Airflow ................................... 29 Pressure Switches ................................. 29 Loss-of-Charge Switch ............................ 28 High-Pressure Switches ............................ 29 Copeland Scroll Compressor (Puron cR)Refrigerant) ........ 30 Refrigerant System ................................ 30 Refrigerant .................................... 30 Compressor Oil ................................. 30 Servicing Systems on Roofs with Synthetic Materials .... 30 Liquid-Line Filter Drier .......................... 30 Puron (R-410A) Refrigerant Charging ............... 30 TROUBLESHOOTING ........................... 30-31 FINAL CHECKS ................................... 32 CARE AND MAINTENANCE ........................ 32 START-UP CHECKLIST ............................ 36 SAFETY Installation CONSIDERATIONS and servicing of this equipment can be hazardous due to mechanical and electrical components. Only trained and qualified personnel should install, repair, or service this equipment. Untrained personnel can perform basic maintenance flmctions, such as cleaning and replacing air filters. All other operations must be performed by trained service equipment, observe precautions labels attached to or shipped precautions Follow personnel. When working on this in the literature, on tags, and on with the unit and other safety that may apply. all safety codes. Installation local and national building clothing, and work gloves. must be in compliance with codes. Wear safety glasses, protective Have fire extinguisher available. Read these instructions thoroughly and follow all warnings included in literature and attached to the unit. or cautions Recognize symbol safety information. This is the safety-alert /_. When you see this symbol on the unit and in instructions or manuals, be alert to the potential for personal iniury. Understand these signal words: DANGER, WARNING, and CAUTION. These words are used with the safety-alert symbol. DANGER identifies the most serious hazards which will result in severe personal iniury or death. WARNING signifies hazards which could result in personal iniury or death. CAUTION is used to identify unsafe practices which may result in minor personal injury or product and property damage. NOTE is used result in enhanced installation, to highlight suggestions reliability, or operation. which will NOTE: installations. Low NOx requirements RECEIVING apply only to natural gas AND INSTALLATION Check Equipment IDENTIFY The UNIT unit model informative number and serial number plate. Check INSPECT are printed this information against on the unit shipping papers. SHIPMENT Inspect for shipping damage while unit is still on shipping pallet. If unit appears to be damaged or is torn loose from its anchorage, have it examined by transportation inspectors before removal. Forward claim papers directly to transportation Manufacturer is not responsible for any damage incurred company. in transit. Check all items against shipping list. Immediately notify the nearest Carrier office if any item is missing. To prevent loss or damage, leave all parts in original packages until installation. Provide For Unit Support hurricane (Professional tie downs, contact Engineering) ROOF CURB Install accessory distributor Certificate, for details roof curt) in accordance with instructions with curt) (See Fig. 4). Install insulation, cant strips, flashing. Ductwork must be attached to curb. IMPORTANT: The for a water gasketing tight seal. of the Always install furnace to operate within the intended temperature rise range with a duct system which has an external static pressure critical within the allowable range, as specified in "Indoor Airflow Adjustments" section of these instructions. See furnace rating plate. air leaks and poor unit performance. with the roof curt). Improperly and PE if required. Install unit to the roof gasketing applied shipped roofing, curt) is material gasketing and supplied also can result in Curb should be level to within 1/4 in. (6.35 m) (See Fig. 2). This is necessary for unit drain to function properly. Refer to accessory roof curt) installation instructions for additional information as required. ELECTRICALSHOCK Failure to follow iniury or death. HAZARD this warning could result in personal Before installing or servicing system, always turn off main power to system and tag disconnect. There may be more than one disconnect switch. Turn off accessory heater power switch MAXIMUM ALLOWABLE DIFFERENCE if applicable. A-B in. (ram) B-C 1/4 (6.35) 1/4 A-C (6.35) 1/4 (6.35) A07925 Fig. 2 - Unit Leveling UNIT OPERATION AND SAFETY Failure to follow this warning iniury or equipment damage. Puron (R-410A) standard R-22 systems systems. equipment or components Ensure service equipment HAZARD could result SLAB in personal MOUNT Place the unit on a solid, level concrete in. (102 operate at higher DO NOT use Tolerances mm) thick with pad that is a minimum 2 in. (51 mm) above grade. of 4 The slat) should extend approximately 2 in. (51 mm) beyond the casing on all 4 sides of the unit (See Fig. 3). Do not secure the unit to the slat) except when required by local codes. pressures than R-22 service on Puron (R-410A) equipment. is rated for Puron (R-410A). INTRODUCTION The 48XL Category packaged unit I gas heating/electric is a fully self-contained air conditioner designed for outdoor installation (See Fig. 1). Standard units are shipped in a horizontal-discharge configuration for installation on a ground-level slab or directly on the ground if local codes permit. Standard units can be converted to downflow configurations for rooftop applications. Models with an N in the fifth position (vertical) of the model RETURr SUPPLY .,_ lY/i_ \ \'\1 .,_ m_ _E_ III1| OPENIN,_ i _, f--_OPENING IIII| tlil _ _z_ ( 't [ IIIII Ill[ I_J'/_ _ _ II IIIII Ill| _ dill dlII 1111 _III jlII IIIII IIIII IIIII N I/ _'_ A' N?',.q IIII II II IIII lUll combination #-/ are EVAR //I /_ // tlii illl -2=_--__-----_/ . j, / COIL COND. . COIL A07926 dedicated Low NOx units designed for California installations. These models meet the California maximum oxides of nitrogen (NOx) emissions requirements of 40 nanograms/joule or less as shipped from the factory and must be installed in California Air Quality Management Districts or any other regions in North America where a Low NOx rule exists. "_ ) / 2" _ (50.Smm) discharge number IIll _ <s' _ I! ,I Hiv-'_ \ -- JbJ/.... GROUND Fig. 3 - Slab Mounting MOUNT The unit may be installed either Detail on a slab or placed directly ground if local codes permit. Place the unit prepared with gravel for condensate discharge. on level on the ground ase / / ,,Screw.__._ (NOTE / A) -_'l *Gasketing / .._ r_ j \ _ Flashing I Ill_l field supplied Wood _ II JJU_ilt"_ Ro°f II_::i!ll/I# Roofing material U_ curb* (field Insulation supphed) I[ IL field supplied-- ll_ii![l '_ /l_!_i:ll \ nailer* II_ Duotwork _ill I[ field supplied/ Roof Curb for Small Cabinet Roof Curb for Large Cabinet Note A: When unit mounting screw is used, retainer bracket must also Note A: When unit mounting screw is used, retainer bracket must also be used. be used. _E Supply opening (BxO) + G \ F \/ R/A S/A ................................................................ _, _Gask_tua_Ound"/_ Insulated Gasket around SuppoR deck pan Long Suppo_ outer edge N X_ Retu'nopening (BXC) A05308 UNIT CATALOG NUMBER A IN. (MM) B IN. (MM) CPRFCURB006A00 8 (203) 11 (279) 16-1/2 (419) 28-3/4 (730) 30-3/8 (771) 44-5/16 (1126) 45-15/16 CPRFCURB007A00 14 (356) 11 (279) 16-1/2 (419) 28-3/4 (730) 30-3/8 (771) 44-5/16 (1126) 45-15/16 CPRFCURB008A00 8 (203) 16-3/16 (411) 17-3/8 (441) 40-1/4 (1022) 41-15/16 (1065) 44-7/16 (1129) 46-1/16 (1169) CPRFCURB009A00 14 (356) 16-3/16 (411) 17-3/8 (441) 40-1/4 (1022) 41-15/16 (1065) 44-7/16 (1129) 46-1/16 (1169) be used as well. SIZE 024-030 036-060 D IN. (MM) C IN. (MM) E IN. (MM) F IN.(MM) G IN. (MM) (1167) (1167) NOTES: 1. Roof curb 2. Seal strip 3. Roof 4. Attach 5. Insulated d. When curb must must is made ductwork panels: unit conditions. be set up for unit be applied, of 1d-gauge to curb 1-in. mounting This screw installed. to unit being installed. steel. (flanges (25 mm) bracket being as required, of duct thick is used is available rest on curb). fiberglass (see Note through 1 lb. density. A), a retainer bracket must This bracket Micrometl. Fig. 4 - Roof Curb Dimensions must also be used when required by code for hurricane or seismic UNIT ELEGTRIG_L CHARACTERISTICS INIT 208'230 208,230 48XL024¢140 ,SXLO2,1G#I LSS 396 @l 405 4O8 ] 60 i 60 _SXLU30040 2GS,P30 48XL03_060 CORNER_EIEHT LBS 4 Hi 6 85,38 _0 i81¸9 /8_ 8 /8_/ 02; ¸ ¢2) 0_;' '? ,3ENTEROF GRAVlT{ M_,_/I_ X 8080(800_ 5,USO{28UJ 5O8 O(20 i_) 5G80{_00_ ' 489 0(:_ 5) 489G,:19 3) 489 Oil9 3) 489¸O i95 4,170_176} 4,1,' 6(i}' 6} 44_G_ii _} REOUIREDCLEARANCESTO COMBUS_BLE MAlL KG C 955 U_IT HEIGHT "_" _U4:_14_ 1641_(43 I_9_ _(43 09? ', 5 ) 8 TO_ OE U_iT ..... _CT SinE OF u_il SIDE OPPOSi_E DUCTS 80TTO_ OF gNIT ELECT_iC HEA_ PANEL 4b(6 #41U i_IETER8 585¸6 [14 S08 [2 555 6 [/4 /2 7 [0 9i4 4 [36 .............. O24040 85/58 0_4060 86¸¸¸¸39 0 86¸¸¸39 e 8O¸¸¸¸36¸5 i_8,0_/ 0300,!O 8_395 8;',53 _, 8O¸¸¸¸36¸5 I_9/C_ 6 NEC. REQUIREDCLEARANCES, 638,060 88¸¸¸¸39¸9 88/39 9 81/36 15i¸¸¸68 5 8ET_EN VN:TS, POWERENTRY S]SE • • U_l[ AND UNGI_OUr,I_i) SU:_i_¢IS PO_'I_ I'/:RY S:I)i ...... U_i[ AN_¸ 8LOG4 OR 80r_CREIE _A_LS _ 0iHEI_ 6_OUNSE8 SURF_ClS, PO_E!RENTRY S_ ........... vl 7 [iN] 00] 00] 00] _0] O0] ilk T( 8 [ _] I066 8:4_ OOI 914¸0 _3_ 00] i06_ 8:42 ,UO] REQUIRE_ CLEARANCEFOR OPERATIONAND _RVlCINO ,<ILL]tdETERS [I] 914 0 3_ GO] 914 0 (36 O0 Ev_l_ CO:L AGCiSS S:I)E .............. POWERENTR_ ¸ SlOE (i:XC_R:¸ FO_ Ii{¢ R_OU_Ri_ENTG) U_ll top .......................................... SIDE OPPOSITE DUCTS.............................. O_C[ P_r,_LL.................... TOP VIEW .............................. 798 6 :3:44] _MJU]KU O]S _C S 9i,1¸0:3_ GO] 9i4 0 {36 GOI 3,34 8 _12 GO]_ [ tlHil IS [{&C [} L GS IUAN 904 8 1 00} [ROB _4i S_'SII_,:_IE_ G_Sri_ PER[ %_A_CE _4448ECO_IfRO_IISE_ ...................... FII{L:} _TR_ ¸ _ 8ER,qSE PORIS _, Vii LOil,] ....... i] ..... 1i [I //'/ [4 6_] I i_ _5505 ]' ,I [285] ER_IN OUTLET--" [i2 _851 68] ii O [52 72] LEFT SIDE VIEW 2498 [983] [953]j 2496 [985] 85] FRONTVIEW RIGHTSIDEVIEW REAR VIEW A06608 Fig. 5 - 48XL024-030 Unit Dimensions UNIT UNIT WT UNIT NEIGNT ELECTRICAL CHARACTERISTICS LBS KG "A" 48XLOS6060 2081230-I-60 485 2200 11425(449B) 48XL036090 20B/230-1-00 493 2236 I142514498) 48XLO42060 20B1230-I-60 507 2290 4BXL042090 2O81R3O-l-GO 515 '336 48XLO4809U 2081230"1=60 521 48XL048115 20B1230-1-60 521 48XL048130 2081230-I"60 48XLOUOORO 48XLOROH5 48XLODOlSO 036090 1011458 042060 1111503 042090 1131513 4215(166) 11933(4698) 5534(210) 5207(205) 4216(166) 1193314098) 5534(210) 5207(205) 4210(166) 2363 11933(4098) 4953(195) 5398(213) 4572(180) 2363 11933(469B) 4953(195) 5398(213) 4572(180) 521 2363 11933(4698) 4953(195} 5398(213) 4572(180) 2081230-I-60 572 2595 12949(5098) 5534(210) 508 0(200) 4470(176) 2O81D3O'l'6O 572 259 12949(509B) 5534(21 508 0(200) 4470(17 572 2595 12949(5098) 5534(210) 5 _14/517 92/417 185/839 79135,0 1361617 1811821 81/36T 13B1620i1841835 BETWEEN UNIT UNIT SIDE OF OPPOSITE BOTTOM OR O4BORO 115152 D B6/390 IBB/62EilBD/B26 O48115 115/522 13B/620 UNIT NEAT UNITS, AND AND UNIT ......................... DUCTS ............... POWER UNGROUNDED BLOCK OR SERVICE _H? G;%_! 7 (42941 SURFACES, ENTRY FULL LOUVER FULL 048130 1151522 861390 13B/6261IBRIB26 000090 1261572 911413 153/694 2021916 060115 1261572 911415 153/694 _OD/916 060130 1261572 911413 1531694iROD/916 POWER _ mm mm ENTRY _ mm mm mm MILLIMETERS 1066B [42 [[N] ON] ...... SIDE ................... DISTANCESIE UNIT IS SYSTEM,THEN 9_40 [3600] 10068 [4200] PLACED LESS THAN 304 B [ID,O0} FROM WALL SYSTEM PERFORMANCE MAYBE COMPROMISED 286{113) POWER ENTRY mm ARE IN INCHES FULL LOUVER 22210881 CONTROL ENTRY mmm '.yl TC 5O6 I II 402,0 115,831 [0.16] 722 C284) [1.B4] COMPRESSOR, BLOWER, RICAL ELECTRIC ACCESS HEAT _ 52.0 46.6 [2.07] PAN ]2263 £12.951 1_23.I 144221 LEFT SIDEVIEW RETURN DUCT OPENING DUCT " ' N,P.T. BAS ENTRY FRONT VIEW __ 87.2 RIOHT SIDE VIEW 3473 [13681 [B.43] _35_.2 [13.B31 142.2 [5.00] [48,28] _ _351.2 Unit Dimensions _4 E13831 REARVIEW A07900 Fig. 6 - 48XL036-060 " H77 I4N3I i \ [1.681 DRAIN 19,010,75] N,PT X 220[O.BT] DEEP SUPPLY 397.1 115.G31 362,9 [14,29} 50] OR] 8P_,P,A'IION A._B 8_RVIa_ DIMENSIONS IN [] LOUVER SIDE [O [36 MILLIMETERS TIN) IVAP COIL ACCESS SIDE ........................... 9140 [36 ON) POWER ENTRY SIDE ....................................... 9140 [3600] (EXCEPT FOR NEC REOUIREMENTS) UNIT TOP ................................................ R14O [3600] SIDE OPPOSITE DUCTS ..................................... 9140 [3600] DUCT PANEL .............................................. 3048 [IDOO]_ _MINIMUM 1 [4 611 ¢ mmm SIDE ............... T 4 1821826 t PORT [DO0] [14 ON) 9_4 SURFACES, POWER ENTRY CONCRETE WALLS AND OTHER RB_JIBED ¢f_.A,e,N_CE _ $090 [14.00] 508 3SS 6 12 .............. [IN] 355.6 ................... PANEL D) 4470(176) MILLIMETERS DUCT SIDE GROUNDED TOP VIEW 5OBO{2OO) UNIT ............................................. OF 1821826 ELECTRIC t O) 0 911413 861390 2 4216(166) 520T(DOD) TOP 1121508 MMIIN Y 5534(210) CORNER WEIGHT LBSIND A B C 1001454 OF GRAVITY 5DOT(DO5) 2081230-I-60 036060 CENTER X 5534(210) Table UNIT SIZE NOMINAL COOLING Data - Unit 48XL 024060 030040 030060 036060 036090 (ton) 2 2 2-1/2 2-1/2 3 3 (Btu) 40,000 396 180 60,000 401 182 40,000 403 183 60,000 408 185 60,000 485 220 CAPACITY NOMINAL HEATING CAPACITY OPERATING WEIGHT (Ib) (kg) I - Physical 024040 COMPRESSORS Quantity 2-Stage Size Part Number OUTDOOR COIL Rows...Fins/in, Face Area (sq ft) OUTDOOR FAN Nominal Cfm Diameter (in.) (ram) Motor Hp (Rpm) INDOOR COIL Rows...Fins/in, Face Area (sq ft) INDOOR FAN Airflow 042090 3-1/2 3-1/2 90,000 493 224 60,000 507 230 90,000 515 234 9.5 4.3 13.8 6.3 13.8 6.3 Scroll 1 REFRIGERANT: PURON (R-410A) Quantity (Ib) (kg) REFRIGERANT METERING DEVICE Nominal Comfort 042060 10.1 4.6 10.1 4.6 11.3 5.1 11.3 5.1 9.5 4.3 2 Ton 2 Ton 3 Ton 3 Ton 3 Ton 3 Ton 4 Ton 4 Ton EA36YD129 EA36YD129 EA36YD139 EA36YD139 EA36YD139 EA36YD139 EA36YD149 EA36YD149 2...21 13.6 2...21 13.6 2...21 15.3 2...21 15.3 2...21 17.5 2...21 17.5 2...21 19.4 2...21 19.4 2700 22 559 1/8 (825) 2700 22 559 1/8 (825) 2700 22 559 1/8 (825) 2700 22 559 1/8 (825) 2800 22 559 1/8 (825) 2800 22 559 1/8 (825) 2800 22 559 1/8 (825) 2800 22 559 1/8 (825) 3...17 3.7 3...17 3.7 3...17 3.7 3...17 3.7 3...17 4.7 3...17 4.7 3...17 4.7 3...17 4.7 TXV (Cfm) Variable based on Comfort Rollback(see Userlnter_ceinstructionsfor moreinformation). Efficiency 7OO 700 875 875 1050 1050 1225 1225 Max 8OO 800 1000 1000 1200 1200 1400 1400 475 727 475 727 745 875 745 875 844 1120 844 1120 1120 1410 1120 1410 10x10 254x254 10x10 254x254 10x10 254x254 10x10 254x254 11x10 279x254 11x10 279x254 11x10 279x254 11x10 279x254 1/2 1/2 1/2 1/2 3/4 3/4 3/4 3/4 2...44 3...44 2...44 3...44 3...44 3...38 3...44 3...38 Furnace (gas ht.) airflow-Low Furnace (gas ht.) airflow-High Stage Stage Size (in.) (ram) Motor HP (RPM) FURNACE SECTION* Burner Orifice No. (Qty._Drill Size) Natural Gas HIGH-PRESSURE Cut-out Reset (Auto) SWITCH (peig) 670 ±10 470 ± 25 HIGH-PRESSURE SWITCH 2 (psig) (Compressor Solenoid) Cut-out 565 ± 15 455 ± 15 Reset (Auto) LOSS-OF-CHARGE / LOW- PRESSURE SWITCH (Liquid Line) (psig) Cut-out 23 ± 5 55 ± 5 Reset (auto) RETURN-AIR FILTERS Throwaway (in.)€ (mm) Continued next page. 20x24x1 508x610x25 24x30x1 610x762x25 24x36x1 610x914x25 Table UNIT SIZE NOMINAL COOLING NOMINAL HEATING OPERATING WEIGHT Data (Con't) - Unit 48XL 048115 048130 060090 060115 (ton) 4 4 4 5 5 5 (Btu) 90,000 521 236 115,000 521 236 130,000 521 236 90,000 572 259 115,000 572 259 130,000 572 259 15.8 7.2 15.8 7.2 CAPACITY CAPACITY 1--Physical 048090 (Ib) (kg) COMPRESSORS Quantity 2-Stage 060130 Scroll 1 REFRIGERANT: PURON (R-410A) Quantity (Ib) (kg) REFRIGERANT METERING DEVICE Size 15.3 6.9 15.3 6.9 15.3 6.9 15.8 7.2 4Ton 4Ton 4Ton 5Ton 5Ton EA36YD 149 EA36YD 149 EA36YD 149 EA36YD 159 EA36YD 159 EA36YD 159 3300 22 559 3300 22 559 3300 22 559 3300 22 559 3300 22 559 3300 22 559 1/4 (1100) 1/4 (1100) 1/4 (1100) 1/3 (1110) 1/3 (1110) 1/3 (1110) 2...21 19.4 2...21 19.4 2...21 19.4 2...21 23.3 2...21 23.3 2...21 23.3 3...17 5.7 3...17 5.7 3...17 5.7 4...17 5.7 4...17 5.7 4...17 5.7 TXV Part Number OUTDOOR FAN Nominal Cfm Diameter (in.) (mm) Motor Hp (Rpm) OUTDOOR COIL Rows...Fins/in, Face Area (sq ft) INDOOR COIL Rows...Fins/in, Face Area (sq ft) INDOOR FAN Nominal Airflow (Cfm) Comfort Variable based on Comfort 5Ton Rollback(see Userlnterfaceinstructionsfor moreinformation). Efficiency 1400 1400 1400 1750 1750 1750 Max 1600 1600 1600 2000 2000 2000 815 1215 1255 845 1215 1255 1385 1885 1875 1300 1910 1920 11x10 279x254 11x10 279x254 11x10 279x254 11x10 279x254 11x10 279x254 11x10 279x254 3/4 3/4 3/4 1 1 1 3...38 3...33 3...31 3...38 3...33 3...31 Furnace (gas ht.) airflow-Low Furnace (gas ht.) airflow-High Stage Stage Size (in.) (ram) Motor HP (RPM) FURNACE SECTION* Burner Orifice No. (Qty._Drill Natural Gas HIGH-PRESSURE Cut-out Reset (Auto) Size) SWITCH (peig) 670 ± 10 470 ± 25 HIGH-PRESSURE SWITCH (Compressor Solenoid) Cut-out Reset (Auto) LOSS-OF-CHARGE LOW-PRESSURE 2 (peig) 565 ± 15 455 ± 15 / SWITCH (Liquid Line) (psig) Cut-out Reset (auto) RETURN-AIR (in.)1(ram) 23 ± 5 55 ± 5 FILTERS Throwaway 24x36xl 610x914x25 *Based on altitude of 0 to 2000 ft (0 to 610 m). 1-Recommended filter sizes for field-installed air filter grilles mounted on the wall or ceiling of the conditioned structure. Required filter sizes shown are based on the larger of the ARI (Air Conditioning and Refrigeration Institute) rated cooling airflow or the heating airflow velocity of 300 ft/minute for throwaway type or 450 ft/minute for high-capacity type. Air filter pressure drop for non-standard filters must not exceed 0.08 IN. W.C. Provide The Clearances required Rig and Place Unit minimum Adequate service ventilation outdoor fan draws and air under in. or under a partial above partial unit overhang IMPORTANT: at either Do the detrimental Do or not roof carpeting top. outdoor-air will or the unit damage other should be at least and runoff levels. coil The it clearance is 48 extension Rigging structures, Only of a When working air restriction fan discharge may not be ice, the unit. combustible 4 in. (102 mm) Do not use unit or snow from Do install materials. not Slab-mounted above the highest expected if it has been under water. unit on water with tags, safety for operators Instruction Condition gloves. 7 all equipment. this and equipment, and precautions of the of the to adapt 3. Follow can be location hazardous (roofs, for elevated ground observe labels that lifting precautions attached might support to the staff in the equipment, apply. equipment should include, but to, the following: 2. kit, operators this stickers, other be limited units equipment installation crane install 1. Application an overhang the and on Training An this the qualified handle any of to etc.). should and due trained, literature, mm). handling reasons lifts water, flood and many does not in either a overhang) airflow. the The discharges minimum horizontal outdoor or and house 48 in. (1219 inlet provided. 6. life. where or be in 5 and the fan discharge locate the unit maximum restrict to compressor place outdoor as a normal exceed shown must obstruction. The not not air the (such must are Be sure that coil. Do not an overhead overhang the outdoor through through the top fan grille. recirculate to the outdoor corner clearances such lifter to various in any of the special load as balance, applicable safety to the load, sizes operation codes. adjustment of the of loads. or precaution. as it relates temperature, and or kinds to operation of the lifting etc. Wear safety shoes and work INSPECTION Prior to initial use, and at monthly intervals, all rigging brackets and straps should be visually inspected for any damage, evidence of wear, structural deformation, or cracks. Particular should be paid to excessive wear at hoist hooking points attention and load support areas. Brackets or straps showing any kind of wear in these areas must not be used and should be discarded. PROPERTY DAMAGE HAZARD Failure to follow this warning iniury/death or property damage. could result in personal Do not strip screws when re-securing the unit. If a screw is stripped, replace the stripped one with a larger diameter screw (included). ELECTRICALSHOCK Failure to follow iniury or death. Riu_inu/Liftinu HAZARD this warning could result of Unit 1. Bend top of brackets in personal down approximately 30 degrees from the corner posts. 2. Attach Before installing or servicing system, always turn off main power to system. There may be more than one disconnect switch. Turn off accessory heater power switch if applicable. Tag disconnect switch with a suitable warning label. opposite weight straps of equal length to the rigging brackets at ends of the unit. Be sure straps are rated to hold the of the unit (See Fig. 7). 3. Attach a clevis of sufficient strength in the middle of the straps. Adjust the clevis location to ensure unit is lifted level with the ground. 4. After unit is securely corner posts, screws. UNIT FALLING this warning could result Failure to follow this warning iniury/death or property damage. could straps. Remove brackets then reinstall in personal rigged units or lift over people. INTRODUCTION installed rigging UNIT Never stand beneath lifting/rigging and HAZARD Failure to follow iniury or death. The in place detach rigging screws, bracket is engineered only on Small Packaged This bracket is to be used to rig/lift roofs or other elevated structures. and designed to be FALLING HAZARD result in personal When straps are taut, the clevis should be a minimum in. (914 mm) above the unit top cover. of 36 Products. a Small Packaged Product onto After the unit is placed the top crating. on the roof curb or mounting Select and Install Ductwork pad, remove The design and installation of the duct system must be accordance with the standards of the NFPA for installation PROPERTY DAMAGE HAZARD Failure to follow this warning iniury/death or property damage. non-residence could result in personal Rigging brackets for one unit use only. When removing unit at the end of its useful life, use a new set of brackets. USE OF RIGGING Field Installation a air conditioning type, NFPA Select and size ductwork, supply-air and 90B ventilating and/or registers, local systems, codes and return and air grilles according to ASHRAE (American Society of Heating, Refrigeration, and Air Conditioning Engineers) recommendations. The unit has duct flanges on the side of the unit. BRACKET of Ri_in_ type NFPA 90A or residence ordinances. in of on the supply- and return-air openings Bracket 1. If applicable, remove unit from shipping carton. Leave top shipping skid on the unit for use as a spreader bar to prevent the rigging straps from damaging the unit. If the skid is not available, use a spreader bar of sufficient length to protect the unit from damage. 2. Remove rain lip (See Fig. 7). Use above to secure the brackets PROPERTY DAMAGE bracket lifting. MUST under removed the panel in step 2 OPERATION to follow this HAZARD warning could result in personal or death. For vertical supply and return units, tools or parts could drop into ductwork, therefore, install a 90 degree turn in the return ductwork between the unit and the conditioned space. If a 90 degree elbow cannot be installed, then a grille of sufficient strength and density should be installed to prevent objects from falling into the conditioned space. Units with electric heaters require 90 degree elbow in supply duct. HAZARD Failure to follow this warning iniury/death or property damage. Rigging adequate brackets the screws to the unit. Failure iniury 4 screws in unit corner posts. 3. Attach each of the 4 metal rigging ELECTRICAL be under could result in personal When designing and installing ductwork, consider 1. All units should have field-supplied filter rack installed in the return-air the rain lip to provide Recommended sizes for filters are shown the following: filters side or accessory of the unit. in Table 2. Avoid abrupt duct size increases and reductions. change in duct size adversely affects air performance. 1. Abrupt 36-in. (914 mm) UNITHEIGHT A/ SEE DETAIL A06298 A RIGGING WEIGHT CABINET MODEL Small 48XL-024 Ib 420 kg 191 Small 48XL-030 427 194 48XL-036 515 234 48XL-042 48XL-048 537 543 244 246 48XL-060 594 269 Large J NOTE: See dimensional drawing for corner weight distribution. Corner weights shown on drawing are based on unit-only weights and do not include packaging. D ACCESS PANEL C A06296 Fig. 7 - Suggested IMPORTANT: unit to prevent ensure Use weather installed, connector flexible transmission tight and airtight use fireproof canvas between ductwork flexible duct is used, resistant duct connector insert connectors of vibration. seal. between ductwork Use suitable When and gaskets to heat is electric a sheet metal sleeve (or sheet metal sleeve) for max possible 4. Seal, insulate, and weatherproof insulate and cover with a vapor through conditioned Air Conditioning (SMACNA) inside duct. must extend Heat 24-in. air flow (See Table 1). all external ductwork. Seal, barrier all ductwork passing spaces. Follow Contractors and Air Conditioning latest Sheet Metal and National Association Contractors (ACCA) minimum installation standards heating and air conditioning systems. 5. Secure all ducts CONVERTING HORIZONTAL DOWNFLOW (VERTICAL) DISCHARGE DISCHARGE UNITS TO UNITS (or similar heat resistant material) and unit discharge connection. If (610 mm) from electric heater element. 3. Size ductwork Rigging to building and vibration-isolate duct according to good construction structure. Failure to follow iniury or death. this HAZARD warning could result in personal Before installing or servicing system, always turn off main power to system and tag. There may be more than one disconnect switch. Turn off accessory heater power switch if applicable. residential NOTE: covers in SHOCK Association for Flash, openings practices. ELECTRICAL weatherproof, wall or If unit is not equipped are required. See pre-sale 1. Open all electrical roof starting supply NOTE: electrical disconnects any service 2. Remove side with duct covers, accessory duct literature. and install lockout tag before work. duct covers to access bottom return and knockouts. These panels knockout. are held in place with tabs similar 3. Use a screwdriver and hammer to remove bottom of the composite unit base. the panels 4. Ensure to block the side duct covers horizontal air openings are in place (See Fig. 8). to an in the off the 3. Secure flue hood to flue panel by inserting the top and the bottom a single screw on of the hood. 1" (25 mm) MIN. __ 2" (51 mm) MIN A08001 Fig. 9 - Condensate Install Supply Duct Cover A06320 Fig. 8 - 48XL Provide for Condensate NOTE: Ensure with local codes, with Duct Covers that condensate-water Gas Piping The gas provided. supply pipe enters The gas connection the unit through the access hole to the unit is made to the l/2-in. FPT gas inlet on the gas valve. On Install a gas supply line that runs to the heating section. Refer to Table 2 and the current edition of NFOC in the U.S. and the current Disposal restrictions, Trap disposal methods comply and practices. NSCNGPIC recommended in Canada. Do not use cast-iron pipe. It is that a black iron pipe is used. Check the local utility The units dispose of condensate through a 3/4 -in. NPT female fitting that exits on the compressor end of the unit. Condensate for recommendations concerning existing lines. Size gas supply piping for 0.5 IN. W.C. maximum pressure drop. Never use pipe water can be drained directly (where permitted) or onto smaller onto the roof in rooftop installations a gravel apron in ground level installations. Install a field-supplied condensate condensate connection to ensure proper drainage. trap at end of Make sure that the outlet of the trap is at least 1 in. (25 mm) lower than the drain-pan condensate connection to prevent the pan from overflowing. Prime the trap with water. When using a gravel apron, make sure it slopes away from the unit. If the installation requires draining the condensate water away from the unit, install a field-supplied 2-in. (51 mm) trap at the condensate connection to ensure proper drainage. Condensate trap is available as an accessory or is field-supplied. Make sure that the outlet of the trap is at least 1 in. (25 mm) lower than the unit drain-pan condensate connection to prevent the pan from overflowing. field-supplied at outlet undersize than the l/2-in. For natural FPT gas inlet on the unit gas valve. gas @plications, the gas pressure propane A conversion 1/8-in. NPT equipment When line, observe Refer to the NFPA B149.1). 2. When flexible MUST connectors HAZARD could result in personal connect B149.2) plumbing codes. 2. Remove must conform the National Z223.1 (in with panel. panel. hangers, local building to the following to heating section and to meter. etc. Use a minimum of one hanger sizes larger than of national codes. every 1/2 6 ft. (1.8 in., follow 3. Apply joint compound (pipe dope) sparingly and only to male threads of joint when making pipe connections. Use only pipe dope that is resistant to action of liquefied codes petroleum gases as specified Never use Teflon t@e. or latest revision. Refer to provincial and local or wastewater codes and other @plicable local flue hood from shipping on flue panel. Orient adhere @proved 2. Protect all segments of piping system against physical and thermal damage. Support all piping with @propriate straps, Fuel Gas Code (NFGC), NFPA Canada, CAN/CSA B149.1, and location section of the blower compartment-See return duct cover to locate the flue screws is NOT valves as follows: installation and with 54/ANSI codes, shutoff low spots in long runs of pipe. Grade all pipe 1/4 in. m). For pipe recommendations 1. This length (6.35 mm) for every 15 ft (4.6 m) of length to prevent traps. Orade all horizontal runs downward to risers. Use risers to The venting system is designed to ensure proper venting. The flue hood assembly must be installed as indicated in this section of the unit installation instructions. Install the flue hood by a licensed the maximum 4. The use of copper tubing for gas piping by the state of Massachusetts. 1. Avoid this warning pertaining Z223.1-2006 be performed are used, In the absence of local building pertinent recommendations: Failure to follow injury or death. gauge of the gas of manual local codes 54/ANSI 3. When lever handle type manual equipment are used, they shall be T-handle valves. Install Flue Hood POISONING test shall not exceed 36 in. (915 mm). least 1 in. for every 10 ft. (3 m) of horizontal run. Be sure to check the drain trough for leaks. Prime the trap at the beginning of the cooling season start-up. MONOXIDE for In the state of Massachusetts: 1. Gas supply connections plumber or gas fitter. end of the 2 -in. (51 mm) trap (See Fig. 9). Do not the tube. Pitch the drain trough downward at a slope of at accessible valve. the gas supply to gas pipe installations. (in Canada, CAN/CSA NOTE: t@ping, be installed immediately upstream to the gas valve and downstream shutoff installing kit instructions. plugged connection, must supply connection Connect a drain trough using a minimum of 3/4 -in. PVC or field-supplied 3/4 -in. copper pipe CARBON at unit gas connection must not be less than 4.0 IN. W.C. or greater than 13 IN. W.C. while the unit is operating. For propane @plications, refer to Place flue screw holes hood (inside 4. Install sediment Fig. 10). This condensate. the return Fig. 8). Remove the hood. Remove two assembly over flue national trap in riser leading to heating section (See as a trap for dirt and leg functions external, pipe within manual main shutoff 6 ft (1.8 m) of heating 10 valve in section. 6. Install ground-joint union close to heating section unit manual shutoff and external manual main valve. in flue hood with holes in the flue codes. drip 5. Install an accessible, gas supply by local and/or between shut off Install IN Electrical ELECTRICAL CAP C99020 7. Pressure national to unit. Trap test all gas piping in accordance with local and plumbing and gas codes before connecting piping HIGH-VOLTAGE NOTE: piping Pressure is connected disconnected systems unit piping system to the gas valve. from the gas valve when test pressure gas supply The test the gas supply system heating section system by closing the slightly opening The supply during is in excess at pressures must external the ground-joint after the gas supply piping the testing must be of the piping of 0.5 psig. Pressure test the equal to or less than 0.5 psig. be isolated main from manual the gas piping shutoff valve and union. this HAZARD warning could result in personal The unit cabinet must have an uninterrupted, unbroken electrical ground. This ground may consist of an electrical wire connected to the unit ground screw in the control compartment, or conduit approved for electrical ground when installed in accordance with NEC, NFPA 70 National Fire Protection Association (latest edition) (in Canada, Canadian Electrical Code CSA C22.1) and local electrical codes. NIPPLE Fig. 10 - Sediment SHOCK Failure to follow iniury or death. TEE _-_ Connections CONNECTIONS The unit must have a separate electrical service with a field-supplied, waterproof disconnect switch mounted at, or within sight from, the unit. Refer to the unit rating plate, NEC and local codes for maximum fuse/circuit breaker size and minimum circuit amps (ampacity) for wire sizing. The field-supplied disconnect may be mounted on the unit over the high-voltage inlet hole (See Fig. 5 and 6). Operation of unit on improper line voltage constitutes abuse and may cause unit damage that could affect warranty. FIRE OR EXPLOSION HAZARD Failure to follow this warning could result in fire, explosion, personal injury, death and/or property damage. • Connect gas pipe to unit using a backup wrench to avoid damaging gas controls. UNIT test for gas leaks with an open flame. Use a commercially available soap solution made specifically for the detection of leaks to check all connections. • Use proper length of pipe to avoid stress on gas control manifold. 3. Be sure that high-voltage power to unit is within operating voltage range indicated on unit rating plate. 4. Insulate low-voltage wires for highest voltage contained within conduit when low-voltage control wires are in same conduit as high-voltage wires. having jurisdiction, black iron pipe shall be installed at furnace gas valve and extend a minimum of 2 in. (51 mm) outside furnace casing. • If codes allow a flexible connector, always use a new connector. Do not use a connector which has previously 5. Do not damage internal components when drilling through any panel to mount electrical hardware, conduit, etc. serviced another gas appliance. been completed. Use a commercially available made specifically for the detection of leaks specified by local codes and/or regulations). HAZARD 2. Use only copper conductor for connections between field-supplied electrical disconnect switch and unit. DO NOT USE ALUMINUM WIRE. • If a flexible connector is required or allowed by authority gas leaks at the field-installed gas lines after all piping connections DAMAGE Failure to follow this caution may result in damage to the unit being installed. 1. Make all electrical connections in accordance with NEC NFPA 70 (latest edition) and local electrical codes governing such wiring. In Canada, all electrical connections must be in accordance with CSA standard C22.1 Canadian Electrical Code Part 1 and applicable local codes. Refer to unit wiring diagram. • Never purge a gas line into a combustion chamber. Never 8. Check for factory-installed COMPONENT and have soap solution (or method 11 Table 2- Maximum Gas NOMINAL IRON PIPE SIZE (IN.) INTERNAL DIAMETER Flow Capacity* 10 20 30 40 50 60 (IN.) (3.0) (6.1) (9.1) (12.1) (15.2) (18.3) .622 LENGTH OF PIPE ft (m)'{" 70 80 90 (21.3) (24.4) 100 (27.4) 125 (30.5) 150 (38.1) 175 (45.7) 200 (53.3) (61.0) -- -- 3/4 1 .824 1.049 175 360 680 120 250 465 97 200 375 82 170 320 73 151 285 66 138 260 61 125 240 57 118 220 53 110 205 50 103 195 44 93 175 40 84 160 77 145 72 135 1 - 1/4 1 - 1/2 1.380 1.610 1400 2100 950 1460 770 1180 600 990 580 900 530 810 490 750 460 690 430 650 400 620 360 550 325 500 300 460 280 430 1/2 *Capacity of pipe in cu ft of gas per hr for gas pressure of 0.5 psig or less. Pressure drop of 0.5-IN. NFPA 54/ANSI Z223,1. 1- This length includes an ordinary ROUTING Use POWER only voltage conduit copper LEADS wire number of fittings. INTO UNIT between disconnect and unit. The high leads should be in a conduit until they enter the duct panel; termination at the duct panel must be watertight. Run the high-voltage leads through the power entry knockout on the power entry side panel. See Fig. 5 and 6 for location and size. For single-phase units, connect leads to the black and yellow wires. CONNECTING GROUND LEAD TO GROUND SCREW Connect the ground lead to the chassis using the ground the control plate near the inducer switch (See Fig. 13). ROUTING For detailed Interface CONTROL POWER instruction on the low voltage screw on connections to the User guide. low-voltage hole provided into unit (See Fig. 5 and 6). Connect user interface leads to unit control power leads as shown in Fig. 14. transformer supplies 24-v accessory electrical heater. for 230-v operation. primary as described section. The furnace board power for complete system Transformer is factory wired If supply voltage is 208-v, rewire transformer in Special Procedures for 208-v Operation is fused by a board-mounted automotive fuse placed in series with transformer SEC1 and R circuit. The C circuit of transformer circuit is referenced to chassis ground through a printed circuit run at SEC2 be sure control board factory-installed screws. ACCESSORY A. Outdoor and gas valve grounding wire. Check to is mounted securely using both Air Thermistor (OAT) no OPERATION of an outdoor temperature sensor using the board OAT terminals is required. Many control For detailed mounting instructions please refer to TSTATXXSEN01-B Procedures will Humidifier The appear If the thermistor at UI. Re-wire damage is wired thermistor to either incorrectly, correctly for furnace is provided for Connections control board terminal low voltage (24-vac) control required as UI monitors indoor When commanded to operate marked HUM of a humidifier. humidity. humidifier, No the unit humidistat control is will energize the HUM output to turn humidifier on and de-energize HUM output to turn humidifier off. Wire HUM and COM terminals C. directly Electronic Electronic Air to humidifier as shown in Fig. 14. Air Cleaner Cleaner terminals are provided on the Infinity Control Board (EAC-I and EAC-2). While these terminals can be used to power a 230V EAC, it is recommended that any EAC be installed per the EAC installation instructions and connected separately to a standard II5V or 230V outlet with an airflow sensor to control SPECIAL operation PROCEDURES Be sure unit disconnect rollback, for the OAT sensor, installation instructions 1 through OAT inputs will not cause or thermistor. operation. B. HAZARD Infinity features (auto humidity control, comfort ETC.) will be lost if the OAT is not connected. data for on User to be observed. Mis-wiring reading Connect 208-v. The installation Infinity control no. 63TS-TAI3): is no polarity NOTE: wiring EQUIPMENT (catalog There Disconnect INSTALLATION to supply outdoor temperature and for temperature display Interface (UI). Using two wires of the field-supplied thermostat wire cable, wire the ends of the two black OAT pigtails. Wire the opposite ends of these two wires to the OAT provided with the UI. normal WIRES (UI), refer to the UI installation The OAT input is used system level functions Infinity Form a drip-loop with the control leads before routing them into the unit. Route the low voltage control leads through grommeted, The unit including W.C. (based on a 0.60 specific gravity gas). Refer to Table, 3. 12 of the EAC. FOR 208-V switch the black primary OPERATION is open. lead from the transformer. See unit label (See Fig. 16 and 17). the black primary lead to the transformer terminal labeled USER INTERFACE TOP COVER DISCONNECT PER NEC* FROM GAS LINE *NEC - NATIONAL ELECTRICAL CODE A06091 Fig. 11 - Typical Installation GROUND SCREW (IN SPLICE BOX) GROUND LEAD SINGLE-PHASE CONNECTIONS TO DISCONNECT PER NEC z_L_ L1 BLKm -- _YEL_ L2 ...... NOTE: Use copper wire only. LEGEND NEC - National Electrical Code Field Wiring _ Splice Connections A06299 Fig. 12 - Line Power 13 Connections HP/AC Board Furnac6 Board A06306 Fig. 13 - Control User interface Plate infinity HP/AC Board infinity Furnace Board OAT Outdoor Air Thermistor (Supplied with [U) FIELD CONNECTION REQUIRED (BLACK WIRES) m 1 OCT | | | a_Outdeor Coil Thermistor FACTORY CONNECTED L m 0 m Y2 m Y1 m w1 m | FACTORY WIRES PROVIDED FOR FIELD CONNECTION OF UTiLiTY CURTAILMENT C R Factory Wiring A06301 Fig. 14 - Control Voltage Wiring 14 Connections PRE-START-UP joint union until the odor be loosened, combustion retighten FIRE, HAZARD EXPLOSION, ELECTRICAL Failure to follow this warning could iniury or death and/or property damage. 1. Follow goggles recognized safety practices when checking or servicing result not remove electrical sources compressor c. Ensure protective system. cover until refrigerant ternfinals. leak is suspected around 5. Never attempt to repair soldered refrigerant system is under pressure. 6. Do not contains 7. To remove a component, proceed as follows: wear a. Shut off gas supply b. Shut off electrical lockout tag. protective all 6. Each with respect to (See Fig. 24). sure that air filter(s) is in place. drain trap is filled with water loose parts system has two Do not loosen Schrader-type ports, one System Unit Start-Up NOTE: and and Troubleshooting Always check high- and low-voltage supply to the unit components. Check the integrity of the plug receptacle and unit wiring harness prior to assunfing a component A. LED LEDs Description built into Infinity person information the unit controls from system ports. connections failure. available control concerning and ECM at the system boards provide installer or service operation and/or fault condition of motor. This information is also UI in text with basic troubleshooting d. Cut component connecting tubing with tubing cutter and remove component from unit. instructions. Careful use of information displayed need for extensive manual troubleshooting. e. Carefully Both the furnace and heat pump (HP)/air conditioner (AC) boards have an amber LED and a green LED. On the HP/AC board, these unsweat necessary. remaining tubing stubs when Oil can ignite when exposed to flame. are located Use the Start-Up Checklist supplied proceed as follows to inspect and at the end of this book and prepare the unit for initial start-up: 1. Remove all access panels. shipped 3. Make with unit. the following connections. and tight. d. Ensure wires do not touch refrigerant sheet metal edges. e. Inspect handling, coil fins. If damaged carefully 4. Verify the following straighten during tubing shipping and lighting the unit tasks with the gas valve in the OFF position. If the gas supply pipe was not purged before of system connecting that the ground communications status on the STATUS LED using 1. The number of short flashes indicates first digit of code. of long flashes second 5. The time between second. indicates on. A long flashes the digit of code. flash is 1 second is 0.25 seconds. last short flash and first long 6. The LEDs will be off for 2.5 seconds 7. If multiple Be and (ABCD) Oil. see or sharp connector the as installed in the unit). at the upper right side, 2. The number 4. The time between conditions: the unit, it will be full of air. It is recommended as an indicator 3. A short flash is 0.25 seconds fins with a fin comb. a. Make sure gas line is free of air. Before for the first time, perform the following is used Status Codes will be displayed following protocol: refrigerant leak. Leak test all refrigerant tubing connections using electronic leak detector, or c. Inspect all field- and factory-wiring sure that connections are completed reduce (See Fig. 15 and 18). inspections: liquid-soap solution. If a refrigerant leak is detected, following Check for Refrigerant Leaks section. Conmmnications will adjacent to the fuse, above the terminal block. The amber LED is the System Status LED, labeled STATUS. The green LED, labeled a. Inspect for shipping and handling damages, such as broken lines, loose parts, disconnected wires, etc. b. Inspect for oil at all refrigerant tubing connections on unit base. Detecting oil generally indicates a near the System (lower right corner of the HP/AC board On the furnace board, these are located COMM, 2. Read and follow instructions on all DANGER, WARNING, CAUTION, and INFORMATION labels attached to, or NOTE: correctly fan blade START-UP to unit and install c. Relieve and reclaim all refrigerant using both high- and low-pressure then light unit. low-side Schrader fitting located on the suction line, and one high-side Schrader fitting located on the compressor discharge line. Be sure that caps on the ports are tight. to unit. power a odor, blade is correctly fan hub is positioned unit into of gas 5. Compressors are internally spring mounted. or remove compressor holddown bolts. while goggles to purge gas lines f. Make sure that all tools and nfiscellaneous have been removed. compressor use torch to remove any component. oil and refrigerant under pressure. to elapse, e. Make sure that condensate to ensure proper drainage. before box if connection detection 5 nfinutes housing d. Make and tagged. 4. Relieve and recover all refrigerant from system touching or disturbing anything inside ternfinal upon sure that condenser-fan motor ternfinal are disconnected purge positioned in fan orifice. Top 1/3 of condenser should be within fan orifice venturi. in personal and wear refrigerant line be allowed Never Immediately the union. Allow 2. Do not operate compressor or provide any electric power to unit unless compressor ternfinal cover is in place and secured. 3. Do chamber. b. Make SHOCK and the supply of gas is detected. priority status power up, are active before repeating concurrently, code. the highest status code is displayed. B. Control Start-Up Troubleshooting On codes flash is 1 green and COMM System LEDs will Communications be turned off until successful system conmmnications are established (this should happen within 10 seconds). Once conmmnications with UI are successful, both COMM LEDs will be lit and held on. At the same time, amber STATUS LEDs will be lit and held continuously on until a request for operating mode is received. will be on any time unit is in idle mode. The STATUS If, at any time, communications are not successful exceeding 2 nfinutes, the Infinity control will 15 LED for a period only allow emergency heating or cooling operation using a common thermostat and the terminal strip connections on the two control boards (See Non-Communicating Emergency Cooling/Heating Mode) and will display Status Code 16, System Communication Fault, on amber STATUS LED. No further troubleshooting information will be available at UI until communications are re-established. If either COMM LED does not light within proper time period and status codes are not displayed; 1. Check system transformer high- and low-voltage the system is powered. 2. Check ABCD connection on both boards. to be sure 3. Check fuse on furnace board to be sure it is not blown. If fuse is open, check system wiring before replacing it to be sure a short does not cause a failure of replacement fuse. If COMM LED does not light within proper time period and status code is displayed: 1. Check system wiring to be sure UI is powered and connections are made A to A, B to B, etc. and wiring is not shorted. Miswiring or shorting of the ABCD communications wiring will not allow successful communications. NOTE: Shorting or miswiring low-voltage system wiring will not cause damage to unit control or UI but may cause low voltage fuse to open. C. Indoor Fan Motor Troubleshooting The indoor fan is driven by an ECM motor consisting of two parts: the control module and the motor winding section. Do not assume motor or module is defective if it will not start. Use the designed-in LED information aids and follow troubleshooting steps described below before replacing motor control module or entire motor. Motor control module is available as a replacement part. VERIFY MOTOR WINDING SECTION ELECTRICALSHOCK Failure to follow iniury or death. HAZARD this warning as long as UI maintains a demand operate while electric heaters communicates with the motor even when the motor not communicate motor will shut for airflow. The a fault condition at least is idle. If, during once control exists. every operation, will not The control five seconds, the control does with the motor for more than 25 seconds, the itself down and wait for communications to be reestablished. D. Furnace Furnace system Control Troubleshooting control faults indicated by flashing codes on the amber STATUS LED can be resolved using troubleshooting information provided below. Codes are listed in order of their priority, highest to lowest. Though multiple faults can exist at any time, only the highest priority code will be displayed on STATUS LED. Clearing the indicated fault when multiple faults exist will cause the next highest priority Status Code to be flashed. All existing STATUS faults, as well as a fault history, CODE CONTINUOUS Check for 230 SEC-2. STATUS Control STATUS VAC at UI. at L1 and L2, and 24 VAC CODE CONTINUOUS at SEC-1 and ON has 24 VAC power. CODE 11 - NO PREVIOUS Stored status codes STATUS can be viewed OFF CODE are erased CODE automatically 12 - BLOWER after 72 hours. ON AFTER POWER UP (230 VAC or 24 VAC) Blower runs for 90 seconds if unit is powered up during a call for heat (R-W/W1 closed) or (R-W/W1 opens) during blower on-delay period. STATUS CODE 13 - LIMIT CIRCUIT Lockout occurs if a limit or flame than 3 minutes or 10 successive limit heat. Control will auto reset after three 33. STATUS Control CODE 14 - IGNITION LOCKOUT rollout switch is open longer trips occurred during high hours. Refer to status code LOCKOUT will auto reset after three hours. Refer to status code 34. STATUS CODE Indicates the blower 15 - BLOWER failed MOTOR LOCKOUT to reach 250 RPM to communicate within 30 seconds successive heating cycles. Control Refer to status code 41. or the blower failed after being turned ON in two will auto reset after 3 hours. could result in personal gqRNSA After disconnecting power from the ECM motor, wait at least 5 minutes before removing the control section. Internal capacitors require time to discharge. Before proceeding to replace a motor control module: 1. Check motor winding section to be sure it is functional. 2. Remove motor control module section and unplug winding plug. Motor shaft should turn freely, resistance between any two motor leads should be similar and resistance between any motor lead and unpainted motor end should exceed 100,000 ohms. ojt a>- T° 3. Failing any of these tests, entire ECM motor must be replaced. r_VCZ] 4. Passing all of the tests, motor control module alone can be replaced. MOTOR TURNS SLOWLY D _ _O = RN4 1. Low static pressure loading of blower while access panel is removed will cause blower to run slowly. Particularly at low airflow requests. This is normal, do not assume a fault exists. 2. Recheck airflow and system static pressure using UI service screens with access panel in place. NOTE: Blower motor faults will not cause a lockout of blower operation. The fan coil control will attempt to run the blower motor A06026 Fig. 15 - Detail of Furnace 16 Board CONNECTION WIRING DIAGRAM LADDER WIRING DIAGRAM DANGER: ELECTRICAL SHOCK HAZARD DISCONNECT POWERBEFORE SERVICING FIELD UNIT COMPONENTARRANGEMENT SECTIO_ OUTDOOR F_N [] 208,_3o 60HZ,IPH SUPPLY VAC I _'I"M _ i,,,,_ - [] I _° qf_ SAS TI LEGEND _F[ELD _° • ? SPLICE SPLICE FACTORY WIRING - FIEL@ COnTrOL _IRI_G FIEL@ POWE_ WIRING RSC REMOTE SPARKER CQNT CONTACTOR CAP COMP CAPACITOR COMPRESSOR MOTOR CS COMPRESSOR SOLENO[D CCH CRANK HEATER CASE CONTROL P P PLI 1(c) TO BE WIRED iN ACCOROANC[ WITH NEC ANO LOCAL CODES 8LOWER-O_ DELAY FOR GAS _EATING iS 3O SECONDS¸ _LOWER-OYF OELAY FOR GAS H[ATING IS 120 SECONOS D_AULT WITH Fi[LD SELECTABLE D[LAYS OF gO, 120, 150, OR 180 SECONDS AVAILABLE 8LOWER-OFF OEL_Y _OR COOLING IS 9O SECONDS co_ COM _ IGNITION LOCKOUT OCCURS AFTER FOUR CONSECUTIVE, UNSUCCESSFUL IGNITION ATTEMPTS CONTROL W_LL AUTO R[S[T AFTER THREE HOURS¸ DUSO0003 111_. > g co CONNECTION WIRING DIA6RAM LADDER WIRING DIAGRAM DANGER: ELECTRICAL SHOCK HAZARD DISCONNECT POWERBEFORE SERVICING FIELD UN]T COMPONENT OUTDOORFA,, SECTIO_ ARRANGEMENT 60HE, ------_ SUPPLY 208/230 _ VAC 1PH ,.._' L_-- DANGER: ELECTRICAL SHOCK HAZARD DISCONNECT POWERBEFORE SERVICING _, L1 _ _''''_1_ _ USE B_ IELD COPPER CONDUCTORS 208/230 SUPPY VAC, ONLY 60 mz, Y PH _ CONT SECTIOn, SECTION I 23 I I 11 =. q_ ICCH I GAS SECTIO_ @ L2 _ 0 FZELD SPL]CE SPL]CE FACTORY FIELD FIELD _o RSC ? CONTACTOR CAP co_P CAPACITOR COMPRESSOR CS r COMPRESSOR CCH EQUIP FS G_,D SOLENOID CRANK CASE HEATER EQUIPMENT FLAME SENSOR GROUND HPS TRAN q_ WIRING CONTROL WIRING POWER WIRING REMOTE SPARKER CONTROL CONT -B, LEGEND HIGH PRESSURE TRANSFORMER SEE NOTES_ SWITCH T PL1-51C PL>4 UI PL3 I _!L PL>_ GI PL3 2 SER INTERFACE PLT C NOTES; IF IT USE ANY OE THE ORIGinAL WIRE FURNISHED MUST BE REPLACED WFH TYPE 90 C OR T_C COPPER REPLACE LOW VOLTAGE (MANUFACTURED MODEL DR4-DSD, MODELS TO BE LOCAL D36 WIRED CODES RLOWER-ON CONDUCTORS FUSE FOR WITH BY LITTLEFUSE, LSI AND LS2 D6D, iN DELAY RAVE LSI ACCORDANCE _OR GAS FIELD R AMP iS REPLACED, EQUIVALENT INSTALLATIONS IT _ITN REC HEATING iS OFF DELAY FOR COOLING IGNITION LOCKOUT OCCURS AEPER UNSUCCESSFUL [GNIHON ATTEMPTS AUTO RESET AFTER THREE HOURS IS 90 PLi l(C) I AND BD SECONDS BLOWER OFF DELAY FOR GAS HEATING IS IDO DEFAUL_ _ITR EIELD DELECTABLE DELAYS OF ISD, OR 180 SECONDS AVAILABLE BLOWER I I J:USE ONLY P/N 257003) ARE IN SERIES ONLY SECONDS DO, 120, GOM CO_ SECONDS FOUR CONSECUTIVE. CONTROL WILL DU500095 g 2 o_ o © D °° O O O O {] [ OO •43ff]° O0 d]]O 0 oo [E] .a O UTILITY RELAY UTILITY OPEN '_ * SUPPLIED @ IRcD * Lql_id SIGNAL RELAY BY UTILITY @ @ Ilne So lellold PROVIDER A05247 Fig. 18 - 2-Stage STATUS Control CODE 21 - GAS HEATING will NOT defective control STATUS SIGNAL Flame auto reset. 22 while until fault is cleared. valve. STATUS Check closed. Check for short circuit 25 pressure SWITCH tubing or will run voltage INVALID Indicates either the model plug flashes 4 times on power-up, switch FUSE (24VAC) MODEL gas stuck IS OPEN wiring. SELECTION OR is missing or incorrect. If code control is defaulting to model selection stored in memory. Check for proper and resistance values per wiring diagram. STATUS CODE 31, 32 - PRESSURE NOT CLOSE OR REOPENED model SWITCH plug number (230VAC), obstructed OR RELAY DID vent, defective inducer voltage inadequate combustion air supply, disconnected or pressure tubing, or low inlet gas pressure (if LGPS used). STATUS CODE 33 - LIMIT CIRCUIT for loose blower wheel, FAULT restricted filter or restricted duct system, combustion CODE 34 - IGNITION defective air supply PROVING vent, excessive switch (flame or roll-out FAILURE Control will try three more times before lockout 14 occurs. If flame signal lost during blower on-delay period, blower will come on for the selected blower off-delay. Check for oxide buildup on flame sensor (clean with fine steel wool), proper flame sense microamps (.5 microamps D.C. min., 4.0-6.0 nominal), manual valve shutoff, low inlet gas pressure, control ground continuity, gas valve defective or turned off, flame sensor must not be grounded, inadequate flame carryover or rough ignition, must be connected to unit sheet metal. STATUS CODE 41 - BLOWER Indicates the blower to communicate within after being operation. Auto failed turned MOTOR ON or ten CODE 45 - CONTROL reset after one hour lockout wire FAULT to reach 250 RPM the prescribed or green/yellow or the blower time limits. seconds CIRCUITRY Thirty during failed seconds steady-state LOCKOUT due to gas valve relay stuck open, flame sense circuit failure, or software check error. Reset power clear lockout. Replace control if status code repeats. E. HP/AC See Control Table 4 for troubleshooting STATUS SENSOR HP/AC control board status If an OAT sensor is found at power-up, will be displayed at amber STATUS Check in wiring 19 codes and information. CODE 53, OUTDOOR AIR FAULT - DETAILED DESCRIPTION for faults Using an Ohm open condition. to Troubleshooting TEMPERATURE input is constantly to be within a valid temperature range. If sensor open or shorted at any time after initial validation, Indicates a limit or flame rollout switch is open. Blower will run for 4 minutes or until open switch remakes, whichever is longer. If open longer than 3 minutes, code changes to lockout 13. If open less than 3 minutes status code 33 continues to flash until blower shuts off. Check dirty connections, or inadequate switch open). STATUS Control relay may be defective. If open longer than five minutes, inducer shuts off for 15 minutes before retry. If open during blower on-delay period, blower will come on for the selected blower off-delay. Check for excessive wind, restricted inducer motor, defective pressure switch, lower Board STATUS DID NOT OPEN or pressure VOLTAGE in secondary - Inducer for leaky gas valve or stuck-open CODE 24 - SECONDARY STATUS CODE SETUP ERROR gas valve FLAME-PROVING gas valve is de-energized. Check Control wind, for mis-wired ABNORMAL CODE 23 - PRESSURE for obstructed STATUS LOCKOUT Check (valve relay). CODE is proved HP/AC meter, checked is found to be Status Code 53 LED. connecting check resistance sensor to OAT terminals. of thermistor for a short or If thermistor is shorted or open, replace it to return normal operation. If fault is in the wiring the fault will clear the code and return the system connections, the system to correcting to normal The If fault condition is an open thermistor or a wiring problem that appears to be an open thermistor and the power to the unit is cycled off, the fault code will be cleared on the next power-up but the fault will remain and system operation will not be as expected. This is because on power-up, the unit control cannot discern the difference between an open sensor or if a sensor is not installed. Sequence of Operation The 48XL packaged unit is designed for installation with a communicating UI. This unit will not respond to commands provided by a common thermostat except under certain emergency situations described in Step l--Start-Up The UI uses temperature, indoor cooling and Troubleshooting. humidity and other data supplied from and outdoor system components to control heating or system for optimum comfort. The unit will be commanded by UI to supply airflow. The unit will operate requested airflow for most modes. INDOOR AIRFLOW The nominal the indoor blower at airflow operations WITH curtailment INFINITY relay should CONTROL be will be 350 cfm per ton of nominal cooling capacity as defined by unit size. Actual airflow request will be adjusted from nominal using indoor and outdoor temperature and indoor humidity data to COMPRESSOR 33% of the scroll compression load capacity. The 24-volt low-stage operation. for occupant comfort and system for further system control details. area so the system operates at part solenoid coil is de-energized in When the compressor is operating at high stage, the modulating ring is activated, sealing the bypass ports, which allows the compressor to operate at full load capacity. coil is energized in high stage operation. CRANKCASE HEATER The heater crankcase OPERATION is energized to follow this caution FAN MOTOR DELAYS-AIR ambient is greater heating airflow for the system NOTE: free from changed detail. obstructions, using adjusted grilles properly. the UI. See UI installation Airflow instructions Once the compressor should not be started cooling cycle remains point that is slightly has started until :'on" below AIR CONDITIONER COOLING again are open, can until the room the cooling SEQUENCE have elapsed. temperature control setting from it The to of the UI. OF OPERATION OPERATION a call for first stage cooling, compressor are energized. demand, high-stage cooling the outdoor If low-stage is energized fan, and low stage cannot satisfy cooling by the UI. After second stage is satisfied, the unit returns to low-stage operation until first stage is satisfied or until second stage is required again. When both first stage and second will shut off. NOTE: When stage cooling two-stage unit is operating vapor (suction) pressure will be higher system or high-stage operation. NOTE: minute Outdoor after compressor are satisfied, fan motor will the compressor at low-stage, than a standard continue shuts off, when outdoor system single-stage to operate ambient from a time delay of outdoor ambient operation from last only). fan at termination is greater of cooling than or equal to 100°F air conditioner to high and from high to low capacity; be drops this feature, pins. (38°C). for more and then has stopped, 4 minutes Defrost delay on return (with Infinity • There is no time delay between low to high dictates. NOTE: With and return-air recycle when there is a To bypass condition. mode when outdoor being installed. Be sure that all supply-and operation or user interface. short and release Forced valid communication rise in each the desired to OPERATIONS • Two minute time delay to return to standby • One minute For gas heat operations, Table 3 shows the temperature gas heating mode. Refer to these tables to determine than or equal include: • Five minute compressor brown-out 65°F overload should open. Outdoor fan for one minute after the compressor CONDITIONER call from the thermostat For cooling operation, the recommended airflow is 350 to 450 cfm for each 12,000 Btuh of rated cooling capacity. For heating operation, the airflow must produce a temperature rise that falls within the range stamped on the unit rating plate. below OPERATION shuts off when the outdoor 100°F (38°C). momentarily off cycle energizes the outdoor fan any time the The outdoor fan remains energized if a pressure switch or compressor motor will continue to operate may result in unit damage. solenoid air temperature. The outdoor unit control compressor is operating. HAZARD The 24-volt (IF APPLICABLE) during • Five minute time delay to start cooling Failure factory OPERATION The unit time delays OPERATION to When the compressor is operating in low stage, the modulating ring is deactivated, allowing two internal bypass ports to close off TIME UNIT connected Fig. 13, 14 and 16). This input allows a power utility device to interrupt compressor operation during peak load periods. When the utility sends a signal to shut the system down, the UI will display "Curtailment Active". OUTDOOR for air conditioner optimize the system operation efficiency. Refer to UI literature utility (18 ° C) outdoor ADJUSTMENTS requested INTERFACE supplied pigtails (PINK, connected to R, VIOLET connected to Y2 on the control board) located in the low voltage splice box (See operation. NOTE: UTILITY for one is greater than or equal to 100°F (38°C). 20 and from high staging the compressor to low capacity from low will change as demand Table 3 - Air Delivery Rated Heating Input (Btu/hr) and Temperature Rise at Rated Low Stage 48XL(-,N)024040 48XL(-,N)030040 40,000 26,000 48XL(-,N)030060 48XL(-,N)036060 48XL(-,N)042060 60,000 48XL(-,N)036090 48XL(-,N)042090 48XL(-,N)048090 48XL(-,N)060090 High Stage Input Heating Rise Either Stage, °F (°C) Unit High Stage Heating Heating Rise Range OF (°C) "Efficiency .... High Stage Low Stage Low Stage Comfort" High Stage Low Stage 20 - 50 15-45 35 30 40 (11-28) (8-25) (19) (17) (22) 35 (19) 25 - 55 25 - 55 40 50 (14-31) (14-31) (22) (28) 35 - 65 (19-36) 35 - 65 (19-36) 50 (28) 55 (31) 39,000 90,000 58,500 48XL(-,N)048115 48XL(-,N)060115 115,000 75,000 30 - 60 (17-33) 30 - 60 (17-33) 45 (25) 50 (28) 48XL(-,N)048130 48XL(-,N)060130 130,000 84,500 35 - 65 (19-36) 35 - 65 (19-36) 50 (28) 55 (31) Airflow delivery values for external static pressure values of up to 1 IN. W.C. Table OPERATION 4 - Heat FAULT On solid, no flash None Emergency Standard Thermostat Control Low Stage Cool/Heat High Stage Cool/Heat Operation Operation Conditioner Board Status AMBER LED FLASH CODE Standby - no call for unit operation Mode Pump/Air Rapid, continuous flashing Codes POSSIBLE CAUSE AND ACTION Normal operation. Unit being controlled by standard thermostat inputs instead of Infinity Control. Only high stage operation is available. This operating mode should be used in emergency situations only. None 1, pause Normal operation. None 2, pause Normal operation. System Communications Failure 16 Invalid Model Plug 25 Control does not detect a model plug or detects an invalid model plug. will not operate without correct model plug. High-Pressure Switch Open Low-Pressure 31 High-pressure switch trip. Check refrigerant and coils for airflow restrictions. 32 Low-pressure 45 Outdoor unit control board has failed. 46 Line voltage < 187v for at least 4 seconds. Compressor Outdoor Coil Sensor Fault 53 Outdoor air sensor not reading or out of range. Ohm out sensor and check wiring. 55 Coil sensor not reading or out of range. Ohm out sensor and check wiring. Thermistors Range 56 Improper relationship between coil sensor and outdoor sensors and check wiring. Low Stage Thermal Cutout 71 Compressor voltage sensed, then disappears while cooling or heating demand exists. Possible causes are internal compressor overload trip or start relay not releasing (if installed). High Stage Thermal Cutout 72 Compressor voltage sensed, then disappears while cooling or heating demand exists. Possible causes are internal compressor overload trip or start relay not releasing (if installed). Contactor Shorted 73 Compressor voltage sensed when no demand for compressor operation exists. Contactor may be stuck closed or there is a wiring error. No 230V at Compressor 74 Compressor voltage not sensed when compressor should tactor may be stuck open or there is a wiring error. Low Stage Thermal Lockout 81 Thermal cutout occurs in three consecutive low/high stage cycles. stage locked out for 4 hours or until 24v power recycled. Low High Stage Thermal Lockout 82 Thermal cutout occurs in three consecutive high/low stage cycles. stage locked out for 4 hours or until 24v power recycled. High Low-Pressure Lockout 83 Low-pressure switch trip has occurred during 3 consecutive operation locked out for 4 hours or until 24v power recycled. cycles. High-Pressure Lockout 84 High-pressure switch trip has occurred during 3 consecutive operation locked out for 4 hours or until 24v power recycled. cycles. Switch Open Control Fault Brown Out v) (230 Out of Communication 21 with UI lost. Check wiring to UI, indoor and outdoor units. Unit charge, outdoor fan operation switch trip. Check refrigerant charge and indoor air flow. Control board needs to be replaced. and fan operation air sensor. Ohm out be starting. Con- Unit Unit INFINITY CONTROLLED LOW AMBIENT COOLING period This unit is capable (-18°C).ONLY is not for ambient begin on must to cycle until and ambient ambient and the outdoor Infinity cooling coil low cooling when using the Infinity required, replaced of fan motor in the UI set-up. air temperature. mode operates plus minutes. ambient outdoor coil temp is turned air fan has been ON for 30 off to allow refrigerant system to coil temp is <outdoor air stabilize.) • In low stage, fan is off when outdoor temperature plus 1 °F (.6°C) minutes. (Fan is turned or outdoor fan has been ON for 30 off to allow refrigerant system to outdoor air temperature > 80°F (27°C) (Fan is turned or if outdoor ambient switch If flame start up. After motor is turned outdoor 3 minutes, 10 minutes fan cycling during low if LPS trips, then outdoor fan for the remainder then cooling per the coil temperature of the cooling within 10 minutes, cooling operation continues and generate control If a power amber must be grounded interruption is restored, occurs blower during if the UI is still calling After the 90-second period, []NIT The period, as long as no faults the unit will respond to MODE 1. Inducer up on Infinity second Pre-purge Period: When high speed, the pressure 2. Trial-For-Ignition pre-purge Sequence: is de-energized and present, control the inducer on to the appropriate terminal energized motor speed for the HUM and electronic air throughout the heating with Delay: When L2 and will motor will remain The indoor blower remain energized stopping the flow of gas to the HUM terminal. The on for a 4-second post-purge and air cleaner terminal EAC-I for 90, 120, 150, or 180 seconds on selection of blower-off delay selected in the factory-set default is 120-second blower-OFF GAS INPUT DAMAGE (NATURAL GAS) HAZARD this caution may Do an Improper not redrill orifice. result in component drilling (burrs, burner noise hole appears to have been redrilled, drill bit of correct size. check The spark igniter a 2-second HAZARD Failure to follow this warning could iniury, death and/or property damage. result in personal DO NOT bottom out gas valve regulator adjusting screws. This can result in unregulated manifold pressure and result in excess overfire and heat exchanger failures. period. will spark flame-proving 22 have the call for gas heat is satisfied, Failure to follow damage. FIRE for 3 seconds. The main gas valve relay contact closes to energize the gas valve on low stage. After 5 seconds, the igniter Lockout interrupting at SEC1 or the inducer motor comes switch closes, and the ignition control on the furnace board begins a 15 pre-purge period. If the pressure switch fails to a 15 second high furnace board performs is open, and starts the remain closed, the inducer will remain running. After the pressure switch re-closes, the Infinity ignition control will begin be no flame is common damaged or it is suspected orifice hole with a numbered AND ADJUSTMENTS When the UI calls for gas heat, the Infinity a self-check, verifies the pressure switch inducer on high speed. the gas valve's out-of-round holes, etc.) can cause excessive and misdirection of burner flame. If orifice the UI normally. GAS HEAT what or two seconds for gas heating. at the determines when unit is powered. (depending UI). The delay. space. operation the 90-second the LED will be ON continuously, are detected. will a call for heat, the only ON period LED light will flash code 12 during after which inducer period. CHECK for proper is proved and operate the gas valve is de-energized, the burners, and de-energizing (shut down HEAT terminal 5. Blower-Off LPS trip error) will occur. OF OPERATION-GAS will start a 90-second after power EAC-2 ll5VAC-to-ground MODE NOTE: Infinity control control will lock out. NOTE: NOTE: with the the living flame control cycle. listed above LPS trip response This Infinity system can be used to dehumidify See UI Installation Instructions for more details. SEQUENCE If on high Delay: If the burner flame is proven, 37 seconds after the gas valve is opened the Indoor Blower is turned gas heating stage. cycle. If the LPS does not close then the normal DEHUMIDIFICATION running. routine there should Simultaneously, the humidifier cleaner terminal EAC-I are system to stabilize.) for first 3 minutes when 4. Blower-On approximately coil temp off for 10 minutes with the compressor LPS closes within is proved will lock out of Gas-Heating mode until flame is no longer proved. fan has been OFF for 30 minutes. is ignored the burner the furnace Trials-For-Ignition before going to Ignition-Lockout. will reset automatically after 3 hours, by momentarily 230 VAC power, or by interrupting 24 VAC power SEC2 to the furnace board. coil temp > plus 25 °F (13.8 ° C) or outdoor on to allow refrigerant • Low-pressure outdoor lights If the burner flame is not proved within 2 seconds, the control will close the gas valve and repeat the ignition sequence up to 3 more stabilize.) • In high stage and low stage, fan is on when sensor, inducer on high speed and energize stage relay to increase gas flow. low is <outdoor always valve energized on low stage. If the UI is asking for high stage gas heat, the ignition control will maintain running the as follows: 3 ° F (1.7 ° C) or outdoor (Fan Low Fan may not controlled unit heating stage to run based on feedback from the UI. If the UI is asking for low stage gas heat, the ignition control will change the inducer speed to low speed and keep the gas kit Fan will cycle based Infinity The When flame-proving to be operation. NOTE: and low stage gas valve operation. 3. Flame-Proving: 0°F not need be enabled • In high stage, fan is off when temperature does low (4°C).OAT. to A low ambient controlled about 40°F outdoor control. down begins. speed inducer NOTE: When this unit is operating below 55°F (13°C) outdoor temperature, provisions must be made for low ambient operation. b. When the gas supply being used has a different heating value or specific gravity, refer to national and local codes, or contact your distributor to determine the CARBON MONOXIDE POISONING HAZARD Failure to follow this warning could result in personal iniury and/or required orifice 2. Adjust manifold Fig. 19). death. size. pressure a. Turn off gas supply If the manifold pressure and/or gas rate is not properly adjusted on HI and LO stages, excess carbon monoxide can be produced. to obtain low stage input rate (See to unit. b. Remove pipe plug on manifold (See Fig. 20) and connect manometer. Turn on gas supply to unit. c. Turn gas valve switch to ON. d. Set unit to run for 20 minutes in low-stage gas heat operation using the "INSTALLER CHECKOUT" menu on the User Interface. FIRE AND UNIT DAMAGE e. Remove HAZARD Failure to follow this warning could iniury or death and/or property damage. result in personal Unsafe operation of the unit may result if manifold is outside of the ranges listed in Table 6. Gas input rates on rating plate are for installations 2000 ft (610 m). input. 1. Determine Input rate must be within regulator valve pressure adjustment regulator cap from low stage gas (See Fig. 19) and turn low-stage adjusting screw (3/16 or smaller flat-tipped screwdriver) counterclockwise (out) to decrease rate and pressure clockwise at altitudes up to - 2% of rating plate (in) to increase input rate. the correct gas input rate. a. The rated gas inputs shown 1/2" in Table 4 are for altitudes NPT iNLET from sea level to 2000 ft (610 m) above sea level. These inputs are based on natural gas with a heating value of 1050 Btu/ft3 at .65 specific gravity. IN THE U.S.A.: The input rating for altitudes above 2,000 ft (610 m) must reduced by 4 percent for each 1,000 ft (305 m) above sea level. For installations plate. below Altitude ft, (610 m) refer to the unit rating 1/2' For installations the rating plate input rate. Table 2,000 be 5 - Altitude ft (m) Derate Percent Multiplier for U.S.A. Derate Multiplier Factor* of Derate 0 1.00 2001-3000 (610-914) 8-12 0.90 3001-4000 (915-1219) 12-16 0.86 4001-5000 (1220-1524) 16-20 0.82 20-24 0.78 6001-7000 (1829-2134) 24-28 0.74 7001-8000 (2134-2436) 28-32 0.70 8001-9000 (2139-2743) 32-36 0.66 36-40 0.62 9001-10,000 (2744-3048) 90,000 X pressure X 0.90 = 81,000 is outside this range, change f. Re-install Gas Control check orifice Never correct size. aligned orifice hole is essential 3. Verify natural less than 1.4 gas. If manifold orifices. adjustment cap. connected. If orifice hole appears been re-drilled, Valve pressure main burner low stage regulator g. Leave manometer re-drill damaged or it is suspected hole with a numbered an orifice. for proper to have drill bit of the A burr-free and squarely flame characteristics. gas low stage input rate. a. Turn off all other gas appliances the gas meter. and pilots served by b. If unit is not running, set unit to run for 20 minutes in low-stage gas heat operation using the "INSTALLER CHECKOUT" menu on the UI. c. Record number one revolution. of seconds d. Divide number of seconds of seconds in 1 hour). for gas meter to complete in step c. into 36 if the heating value of at 4300 ft (1372 m). Furnace Input Rate at Installation Automatic or more than 2.0 IN. W.C. for natural EXAMPLE: Installed TAP DO NOT set low stage manifold The input rating for altitudes from 2,000 (610 m) to 4,500 ft (1372 m) above sea level must be derated 10 percent by an authorized Gas Conversion Station or Dealer. Derate Multiplier Factor PDAE_'/FOLDE IN. W.C. IN CANADA: Btuh Input Furnace _ NOTE: :'Derate multiplier factors are based on midpoint altitude for altitude range, Furnace Input Rate at Sea Level Altitude J Fig. 19 - Redundant NOTE: 5001-6000 (1524-1829) OUTLET A04167 above 2,000 ft, (610 m) multiply the input by on by the derate multiplier in Table 6 for the correct 0-2000 (0-610) 90,000 NPT gas is not known). EXAMPLE: Assume a 90,000 installed. Assume that the size high stage input unit is being of the dial is 2 cubic ft., one revolution takes 129 sec., and the heating Btu/ft3. Proceed as follows: 23 value of the gas is 1050 a.129sec. to complete b. 3600/129 In this example, the nonfinal input rate for high stage is 90,000 Btu/hr, so the high stage manifold pressure is correctly set. If the measured high stage rate is too low, increase the manifold pressure to increase rate. If the measured high stage rate is too high, decrease the manifold pressure to decrease rate. one revolution = 27.9 c. 27.9 x 2 = 55.8 ft3 of gas flow/hr. d. 55.8 x 1050 = 58,590 Btuh input. In this example, the nonfinal input rate for low stage is 58,500 Btu/hr, so the low stage manifold pressure is correctly set. If the measured low stage rate is too low, increase the manifold pressure to increase rate. If the measured low stage rate is too high, decrease NOTE: the manifold pressure Double-check while clocking to decrease a. Furnace plate. that UI is running within b. Select "COMFORT" a. Furnace must operate within rise range listed on rating plate. on low stage gas heat low stage gas heat temperature must operate 7. Verify proper high stage gas heat temperature rise. rate. b. Make sure access panel is re-installed on the unit. c. Measure supply and return temperatures as close to the unit as possible. Subtract the return temperature from the supply temperature to deternfine rise. Rise should fall within the range specified on the rating plate. NOTE: If the temperature rise is outside the rating plate range, first check: the low stage firing rate. 4. Verify proper NOTE: Double-check that User Interface is running on high stage gas heat while clocking the low stage firing rate. rise. rise range listed on rating or "EFFICIENCY" mode on UI. "COMFORT" mode will provide a warmer supply air temperature, while "EFFICIENCY" will provide lower a. Gas input for low and high stage gas heat operation. gas consumption. c. Make sure access panel is re-installed d. Measure supply unit as possible. the supply fall within 5. Adjust b. Derate for altitude, if applicable. on the unit. c. Return and supply ducts for excessive restrictions causing static pressures in excess of .5 IN. W.C. and return temperatures as close to the Subtract the return temperature from temperature to deternfine rise. Rise should the range specified on the rating plate. manifold pressure to obtain high stage input d. Make sure model plug is installed. 8. Final Check rate a. Turn off gas to unit (See Fig. 19). b. Remove manometer from pressure tap. a. Set unit to run for 20 minutes in high-stage gas heat operation using the "INSTALLER CHECKOUT" menu on the UI. b. Remove regulator valve pressure NOTE: adjustment regulator c. Replace pipe plug on manifold (See Fig. 20). d. Turn on gas to unit. e. Check for leaks. cap from high stage gas CHECK GAS INPUT (PROPANE GAS) (See Fig. 19) and turn high-stage adjusting screw (3/16 or smaller flat-tipped screwdriver) counterclockwise (out) to decrease rate and Refer to propane kit installation instructions for properly checking gas input. clockwise (in) to increase DO NOT set high stage manifold NOTE: For installations below 2,000 ft (610 m), refer to the unit rating plate for proper propane conversion kit. For installations above 2,000 ft (610 m), contact your distributor for proper propane conversion kit. IN.W.C. or more pressure is outside input rate. pressure than 3.8 IN. W.C. for natural this range, change c. Re-install 6. Verify natural gas. If manifold main burner orifices. high stage regulator d. Leave manometer less than 3.2 adjustment cap. CHECK connected. With gas high stage input rate. a. Turn off all other gas appliances the gas meter. BURNER burner FLAME access panel removed, observe the unit heating operation. Watch the burner flames to see if they are light blue and soft in appearance, and that the flames are approximately the same and pilots served by for each burner. Propane will have blue flame (See Fig. 21). Refer to the Maintenance section for information on burner removal. b. If unit is not running, set unit to run for 20 minutes in high stage gas heat operation using the "INSTALLER CHECKOUT" menu on the UI. c. Record number revolution. of seconds d. Divide number of seconds of seconds in 1 hour). for gas meter to complete in step c. into 3600 gas is not known). EXAMPLE: Assume a 90,000 installed. Assume that the size a. 84 sec. to complete value of high stage input unit is being of the dial is 2 cubic ft., one revolution takes 84 sec., and the heating Btu/ft3. Proceed as follows: b. 3600/84 if the heating value of the gas is 1050 one revolution = 42.9 MANIFOLD PIPE PLUG c. 42.9 x 2 = 85.8 ft3 of gas flow/hr. d. 85.8 x 1050 = 90,090 099019 Fig. 20 - Burner Btuh input. 24 Assembly BURNER FLAME COMPONENT TEST The Infinity Furnace Board features a gas component test system to help diagnose a system problem in the case of a gas component BURNER failure. To initiate the component test procedure, ensure that there are no UI inputs to the control (the ABCD connector removed from the Infinity control board for this operation) time delays have expired. Turn on setup switch SWl-6. NOTE: The component is receiving MANIFOLD The component through 2. After Fig. 21 - Monoport LIMIT closes the gas valve and stops gas flow to the burners and pilot. The blower motor continues to run until LS resets. The furnace STATUS When the air low-temperature completes the LED will display temperature STATUS at the limit CODE switch 33. drops to the setting of the limit switch, the switch closes and control circuit. The direct-spark ignition system cycles and the unit returns ROLLOUT waiting 10 seconds, to normal The function of the rollout the event of flame rollout. heating switch is to close the main gas valve in The switch is located above the main fan operation is requested by the UI indoor EAC-I is energized fan for as long as the ignite, then shut OFF and remain OFF for the delay allowing the heat exchangers to heat up more then restarts indoor When at the end of the blower-ON fan motor after the gas heating will revert delay period. to continuous-blower airflow cycle is completed. the UI "calls for cooling", When airflow before transitioning the call for continuous The EAC turns fan motor back will switch to continuous-blower fan is removed, terminals the component Check Locate the indoor fan are energized test is completed, motor when the indoor blower will continue operating for an additional 5 seconds before shutting down, if no other function requires blower motor operation. ON on for 15 runs the the blower one or more See component of status codes. for Refrigerant is status test section test, turn setup 2. Repair NOTE: codes or Status switch SWl-6 to Leaks and repair refrigerant leaks and charge leak following the unit as follows: accepted system practices. Install a filter drier whenever the system has been opened for repair. 3. Check system 4. Evacuate additional for leaks using an approved refrigerant system leaks are found. method. and reclaim refrigerant 5. Charge unit with Puron (R-410A) refrigerant, volumetric-charging cylinder or accurate scale. unit rating plate for required charge. Start-Up if no using a Refer to Adjustments Complete the required procedures given in the Pre-Start-Up section before starting the unit. Do not jumper any safety devices when operating the unit. Do not operate the unit in cooling mode when the outdoor temperature is below 40°F (4°C) (unless low-ambient operation is enabled in the UI). Do not rapid cycle the compressor. Allow 5 min. between "on" cycles to prevent compressor damage. CHECKING OPERATION COOLING See UI Installation the indoor to operate at cooling airflow. When the call for cooling is satisfied, the indoor fan motor will operate an additional 90 seconds at cooling airflow. then NOTE: To repeat component OFF and then back ON. fan During a call for gas heat, the Infinity control will transition the indoor fan motor to continuous blower airflow or gas heat airflow, whichever is lowest. The indoor fan motor will remain ON until The turns the igniter then OFF. (11, 25, or 41) will flash. Code Label for explanation FAN MODE detailed instructions. Terminal indoor fan motor is energized. quickly, After furnace motor will operate at continuous blower airflow. Continuous operation is programmable. See the UI Owner's Manual the burners blower-ON the control then OFF. 1. Use both high- and low-pressure ports to relieve pressure and reclaim remaining refrigerant. motor (IFM) continues to run until switch is reset. The board STATUS LED will display STATUS CODE 33. continuous it ON operating. operation. burners. When the temperature at the rollout switch reaches the maximum allowable temperature, the control circuit trips, closing the gas valve and stopping gas flow to the burners. The indoor fan When control NOTE: SWITCH CONTINUOUS ON and keeps 4. After shutting the blower motor OFF, the control inducer for 10 seconds, then turns it OFF. SWITCHES Normally closed limit switch (LS) completes the control circuit. Should the leaving-air temperature rise above the maximum allowable temperature, the limit switch opens and the control circuit "breaks." Any interruption in the control circuit instantly board motor step 3. seconds, Burner if the control is as follows: turns the inducer for 15 seconds, 3. The will not operate or until all time delays have expired. test sequence 1. The control C99021 test feature any UI signals can be and all CHECKING AND Instructions HEATING for detailed AND ADJUSTING Any adjustment unit operating NOTE: unless charge. 25 to refrigerant with charge of the refrigerant is suspected The charging CHARGE Puron (R-410A) must be done with stage. Adjustment the unit temperatures charging in HIGH CHECKOUT. REFRIGERANT The refrigerant system is fully charged refrigerant and is tested and factory sealed. NOTE: system CONTROL of not charge having label and the tables and pressures label is attached in cooling to the outside the is not required proper shown mode only. of the unit. R-410A refer to system A refrigerant 6 - Heating Table HEATING INPUT(BTU/HR)* Inputs GAS SUPPLY PRESSURE Natural NUMBER OF ORIFICES (IN. W.C.) MANIFOLD High Stage 3.2-3.8 PRESSURE Natural (IN. W.C.) High Stage Low Stage Min Max 40,000 26,000 2 4.0 13.0 Low Stage 60,000 39,000 3 4.0 13.0 3.2-3.8 1.4 - 2.0 90,000 58,500 3 4.0 13.0 3.2-3.8 1.4 _ 2.0 115,000 75,000 3 4.0 13.0 3.2-3.8 1.4 _ 2.0 130,000 84,500 3 4.0 13.0 3.2-3.8 1.4 _ 2.0 1.4 - 2.0 *Cubic ft of natural gas per hour for gas pressures of .5 psig (14 IN. W.C.) or less and a pressure drop of .5 IN. W.C. (based on a .60 specific gravity gas). Ref: Table 6.2 (b) NPFA 54 / ANSI Z223.1. 7 - ECM Table Wet Coil Pressure Drop (IN. W.C.) UNIT SIZE 600 700 800 900 1000 024 0.005 0.007 0.010 0.012 0.015 0.007 0.010 0.012 0.015 0.018 0.021 0.024 0.019 0.023 0.027 0.032 0.037 0.042 0.047 0.014 0.017 0.020 0.024 0.027 0.031 0.035 0.039 0.043 0.027 0.032 0.036 0.041 0.046 0.052 0.029 0.032 0.036 030 036 042 STANDARD CFM (SCFM) 1200 1300 1400 1500 1100 O48 060 Table FILTERSIZE in.(mm) 20X20X1 (508x508x25) 24X30X1 24X36X1 (610x914x25) 600 700 800 900 1000 1100 1200 0.05 0.07 0.08 0.1 0.12 0.13 0.14 0.15 0.05 0.6 0.07 0.07 0.08 0.09 0.1 0.06 0.07 0.07 0.08 ....... IMPORTANT: indicated Drop Table (IN. W.C.) CFM 1300 1400 1500 1600 1700 When adjustment evaluating to the specified the refrigerant factory charge charge, must always 0.10 0.11 0.12 0.13 0.14 0.14 ........ 0.09 an TO USE COOLING be Take CHARGE is listed on the unit rating data table. Refer to the Refrigeration Refrigerants Section. plate Service NO CHARGE Use standard evacuating evacuating system, weigh in the specified (refer to system rating plate). LOW CHARGE techniques. amount After of refrigerant the liquid 0.09 CHARGING refrigerant CHARTS line temperature If the and read the manifold what the liquid causing leak, refer to Check NON-COMMUNICATING HEATING MODE: 4-WIRE line temperature the inaccurate for Refrigerant readings EMERGENCY THERMOSTAT COOLING established with the UI, the Infinity suction line. Mount the temperature sensing device on the suction line and insulate it so that the outdoor ambient does not affect the The operating interconnecting Infinity a standard from both insulated / wire with 105C, control disconnect the thermostatic the ABCD control boards and using No. 18 AWG type 90°C minimum or equivalent wire, will respond with the maximum safe airflow unit cooling capacity. 26 thermostat, will enable simple make the connections between the standard thermostat, board, and the HP/AC board per Fig. 22. Recommend connectors color-coded, with board to allow the units to correct subcooling for the various operating conditions. Accurate pressure gauge and temperature sensing devices are required. Connect the pressure gauge to the service port on the the normal control furnace terminals For be within is a Leaks section. Use Cooling Charging Chart (Fig. 23). Vary refrigerant until the conditions of the chart are met. Note that charging charts are different from type normally used. Charts are based on charging must pressure This mode of operation is provided only in the case where the UI has failed or is otherwise unavailable. If communications cannot be standard thermostat input control of the 48XL unit. COOLING reading. Indoor air CFM range of the unit. 0.053 2300 problem leak. 0.049 2200 NOTE: for 0.068 0.045 2100 REFRIGERANT Check 0.063 0.040 2000 to determine and/or the physical Techniques Manual, 0.057 2100 1900 Refer to the chart should be. charge 2000 1800 gauges. of refrigerant 1900 ........... very minimal. If a substantial adjustment is indicated, an abnormal condition exists somewhere in the cooling system, such as insufficient airflow across either coil or both coils. The amount 1800 8 - Filter Pressure 500 .... (610x762x25) 1700 1600 the furnace the use of 600V, 2/64" insulation. to cooling based and heating on gas furnace demands output and infinity Furnace Board infinityHP/AC Board OutdoorAir Thermistor (Suppliedwith IU) FIELD CONNECTION REQUIRED (BLACKWIRES) Standard 4=Wire Thermostat OutdoorCoil Thermistor FACTORYCONNECTED _'m m FACTORYWIRESPROVIDED FOR FIELDCONNECTION OF UTiLiTY CURTAILMENT AO6302 Fig. 22 - Non-Communicating Emergency Cooling/Heating Required Subcooling °F (°C) Wiring Connections Required Liquid Line Temperature for a Specific Subcooling (R-410A) Outdoor Ambient Temperature Required Subeoolin9 (°F) Pressure Model Size 024 030 036 15.5(8.6) 16.8(93) 14(7.7) 15.6(8.7)15.7(8.7)15.8(8.8)15.9(8.9) 16,4(9.I) I6.2(9) 156(8,7) 13.9(7.7) 13.9(7.7) 13.8(7.7) 042 048 oe° 19.2( 10.7 ) 19.1 ( 10.6 ) 19.1( 10.6 ) 18.9 ( 10.5) 18.7( 10.4 ) 21(11.6) 20.8(11.5) 20,7(11.5) 20,4(11,3) 20.2(11.2) 16.2(9) 16.6(9.2) 16.8(9.3) 17.3(9.6) 17.8(9.9) Required Subcooling (°C) Pressure 174 I81 188 56 59 61 5I 54 56 46 49 51 36 39 41 1200 1248 1296 13 15 16 I1 I2 13 8 9 10 2 4 5 Char in Procedure 195 202 209 216 223 230 63 65 67 69 71 73 58 60 62 64 66 68 53 55 57 59 61 63 43 45 47 49 51 53 1344 1393 1441 1489 1537 1586 17 18 20 2I 22 23 14 16 17 18 19 20 12 13 14 15 16 17 6 7 9 10 11 12 1- Measure Dischargeline pressure by attaching a gaugeto the service port. 2- Measurethe Liquid line temperature by attaching a temperature sensingdevice to it, 237 244 75 77 70 72 65 67 55 57 I834 1882 24 25 21 22 I9 20 I3 14 259 267 275 283 291 299 81 83 85 87 89 91 76 78 80 82 84 86 71 73 75 77 79 81 61 63 65 67 69 71 1786 1841 1896 1951 2008 2061 27 28 29 31 32 33 24 26 27 28 29 30 22 23 24 25 28 27 16 17 18 19 20 22 308 317 326 335 344 353 93 95 97 99 101 102 88 90 92 94 96 97 83 85 87 89 9I 92 73 75 77 79 81 82 2123 2185 2247 2309 2372 2434 34 35 36 37 38 39 31 32 33 34 35 36 28 29 30 31 33 34 23 24 25 26 27 28 363 373 383 104 106 108 99 101 103 94 96 98 84 86 88 2503 2571 2640 40 41 42 37 39 40 35 36 37 29 30 31 393 403 413 423 433 443 110 112 114 116 117 119 105 107 109 111 112 114 100 102 104 106 107 109 90 92 94 96 97 99 2709 2778 2847 2916 2985 3054 43 44 45 46 47 48 4I 42 43 44 45 46 38 39 40 41 42 43 32 33 34 35 36 37 453 463 473 121 I22 124 116 117 119 111 112 114 101 102 104 3123 3192 3261 49 50 51 47 47 48 44 45 46 38 39 40 483 493 503 513 523 533 126 127 129 130 132 133 121 122 124 125 127 128 116 117 119 120 122 123 106 107 109 110 112 113 3330 3399 3468 3537 3606 3675 52 53 54 55 56 56 49 50 51 52 53 54 47 47 48 49 50 51 41 42 43 44 44 45 15(8,3) 13.7(7.6) 3- insulatethe temperaturesensing device so that the Outdoor Ambient doesn't affect the reading, 4- Referto the required Subcooiingin the table based on the model size and the OutdoorAmbient temperature. 5- Interpolateif the Outdoortemperature lies in betweenthe table values, Extrapolateif the temperature lies beyondthe table range. 6- Findthe PressureValue correspondingto the the measured Pressureon the CompressorDischargeline. 7- Read acrossfrom the Pressure readingto obtain the Liquid line temperature for a required SubcooIing. 8- Add Charge if the measuredtemperature is higherthan the liquid line temperature value in the table. 9- Add Charge using the serviceconnection on the Suctionline of the Compressor, 50DU500166- 2,0 AO8423 Fig. 23 - Cooling Charging Table-Subcooling 27 Air Filter MAINTENANCE To ensure continuing high performance, and to minimize the possibility of premature equipment failure, periodic maintenance must be performed on this equipment. This packaged unit should be inspected at least once each year by a qualified service person. To troubleshoot unit, refer to Table 10, Troubleshooting Chart. NOTE TO EQUIPMENT OWNER: Consult your local dealer about the availability of a maintenance contract. IMPORTANT: Never in the return-air duct same dimensional size for recommended filter Inspect air filter(s) at least once each month and replace (throwaway-type) or clean (cleanable-type) at least twice during each cooling season and twice during the heating season, or whenever the filter becomes clogged with dust and lint. Indoor PERSONAL HAZARD INJURY AND UNIT DAMAGE Failure to follow this warning could result in personal injury or death and possible unit component damage. The ability to properly perform maintenance on this equipment requires certain expertise, mechanical skills, tools and equipment. If you do not possess these, do not attempt to perform any maintenance on this equipment, other than those procedures recommended in the Owner's Manual. operate the unit without a suitable air filter system. Always replace the filter with the and type as originally installed. See Table 1 sizes. Fan and Motor NOTE: All motors are pre-lubricated. these motors. Do not attempt to lubricate For longer life, operating economy, and continuing efficiency, clean accumulated dirt and grease from the blower wheel and motor annually. Inducer Blower NOTE: All motors are pre-lubricated. these motors. Do not attempt to lubricate Clean periodically to assure proper airflow and heating efficiency. Inspect blower wheel every fall and periodically during the heating season. For the first heating season, inspect blower wheel bi-monthly to determine proper cleaning frequency. Limit Switch ELECTRICAL SHOCK Failure to follow injury or death: Remove unit access panel to gain access to the limit switch. The limit switch is located above the indoor blower housing. HAZARD these warnings could result 1. Turn off electrical power to the unit before any maintenance or service on this unit. 2. Use extreme caution 3. Never place anything with the unit. when removing combustible panels in personal NOTE: On small chassis units, a second limit switch is located beside the indoor blower housing. performing Burner and parts. either on or in contact Ignition []nit is equipped with a direct spark ignition 100 percent lockout system. Ignition module is located in the control box. Refer to additional information in the Start-Up & Troubleshooting section for Status Code information. Main Burners At the beginning of each heating season, inspect for deterioration or blockage due to corrosion or other causes. Observe the main burner flames and adjust, if necessary. []NIT OPERATION HAZARD Failure to follow this caution may result in equipment damage or improper operation. EQUIPMENT Errors made when reconnecting wires may cause improper and dangerous operation. Label all wires prior to disconnecting when servicing. DAMAGE HAZARD Failure to follow this caution may result in equipment damage or improper operation. When servicing gas train, do not hit or plug orifice spuds. The minimum maintenance requirements for this equipment are as follows: 1. Inspect air filter(s) each month. Clean or replace when necessary. 2. Inspect indoor coil, drain pan, and condensate drain each cooling season for cleanliness. Clean when necessary. 3. Inspect indoor fan motor and wheel for cleanliness each cooling season. Clean when necessary. 4. Check electrical connections for tightness and controls for proper operation each cooling season. Service when necessary. 5. Check for restrictions on inducer outlet. Clean flue hood. Removal of Gas Train To remove the gas train for servicing: 1. Shut off main gas valve. 2. Shut off power to unit. 3. Remove unit access panel. 4. Disconnect gas piping at unit gas valve. 5. Remove wires connected to gas valve. Mark each wire. 6. Remove ignitor and sensor wires at the ignitor module. 7. Remove the mounting screw that attaches the burner rack to the unit base. 8. Slide the burner rack out of the unit. 6. Inspect burner compartment before each heating season for rust, corrosion, soot or excessive dust. 7. Inspect all accessories. Perform any service or maintenance to the accessories as recommended in the accessory instructions. 9. To reinstall, reverse the procedure outlined above. Inducer Pressure Switch Inspect pressure switch connections. Inspect pressure switch tube for cracks or restrictions. Replace if needed. 28 ELECTRICALSHOCK HAZARD Failure to follow this warning could result injury in personal or death. Disconnect and tag electrical power to the unit cleaning and lubricating the blower motor and wheel. before infinity Top A06035 Outdoor Coil, Indoor Drain Pan Coil, and Condensate Inspect the condenser coil, evaporator pan at least once each year. UNIT SIZE coil, and condensate drain The coils are easily cleaned when dry; therefore, inspect and clean the coils either before or after each cooling season. Remove all obstructions, including weeds and shrubs, that interfere with the airflow through the condenser coil. Straighten bent fins with a fin comb. If coated with dirt or lint, clean the coils with a vacuum Electrical detergent and water solution. Rinse coils with clear water, using a garden hose. Be careful not to splash water on motors, insulation, Remove condenser coil, be sure to clean between all dirt and debris from the unit base. Inspect the drain pan and condensate coil fins and inner the coils. Be sure to flush drain line when inspecting the coils. Clean the drain pan and condensate drain by removing all foreign matter from the pan. Flush the pan and drain trough with clear water. Do not splash water on the insulation, motor, wiring, or air filter(s). If the drain trough is restricted, "plumbers snake" or similar probe device. Outdoor clear it with a Fan 1 (26) 1 (26) 036 1 (26) 042 1 (26) 048 11/32 (9) 060 Inspect For best results, spray condenser the unit. On units with an outer DIM. IN. (MM) 030 9/16 (14) Fig. 24 - Outdoor cleaner, using the soft brush attachment. Be careful not to bend the fins. If coated with oil or grease, clean the coils with a mild wiring, or air filter(s). from inside to outside "A" 024 Controls and check Fan Blade Clearance and Wiring the electrical sure to turn off the electrical controls power access panel to locate and wiring annually. Be to the unit. all the electrical controls and wiring. Check all electrical connections for tightness. Tighten all screw connections. If any smoky or burned connections are noticed, disassemble the connection, clean all the parts, re-strip end and reassemble the connection properly and securely. the wire After inspecting the electrical controls and wiring, replace all the panels. Start the unit, and observe at least one complete cooling cycle to ensure proper operation. If discrepancies are observed in operating cycle, or if a suspected each electrical component instrumentation. checks. Refer Refrigerant malfunction with the to the unit wiring has occurred, check proper electrical label when making these Circuit Inspect all refrigerant tubing connections and the unit base for oil accumulation annually. Detecting oil generally indicates a refrigerant UNIT OPERATION HAZARD Failure to follow this caution may result in damage to unit components. refrigerant solution. Keep the outdoor fan free from all obstructions to ensure proper cooling operation, Never place articles on top of the unit, Refrigerant 2. Turn 4 screws motor/grille expose 3. Inspect holding assembly outdoor upside grille down the fan blades for cracks cover to or bends. loosen setscrew 5. When position replacing table shown fan blade, blade that set screw grille. engages The according to the the flat area on the motor is suspected, leak test all Leaks section. and low performance is suspected, Refrigerant Charge section. Airflow heating and/or cooling airflow does not require checking unless improper performance is suspected. If a problem exists, be sure that all supplyand return-air grilles are open and free from obstructions, and that the air filter is clean. Pressure and slide fan off in Fig. 24. shaft when tightening. 7. Replace on top to top fan blade. 4. If fan needs to be removed, motor shaft. 6. Ensure and motor or if low performance tubing using an electronic leak detector, or liquid-so@ If a refrigerant leak is detected, refer to Check for If no refrigerant leaks are found refer to Checking and Adjusting Indoor 1. Remove cover. leak. If oil is detected Pressure Switches switches - Refrigerant are protective devices Circuit integrated into the control circuit (low voltage). They shut off compressor if abnormally high or low pressures are present in the refrigeration circuit. These pressure switches are specifically designed to operate with Puron (R-410A) systems. R-22 pressure switches must not be used as replacements for the Puron Loss-of-Chame This switch suction airflow (R-410A) (Low Pressure) is located system. Switch on the liquid line and protects pressure drops to about switch should be closed. 20 psig. If system Hi_h-Pressure (HPS & HPS2) The 29 Switches high-pressure protects against low pressures caused by such events as loss of charge, low across indoor coil, dirty filters, etc. It opens if the system against switches excessive are located condenser pressure is above on the discharge coil pressure. HPS this, line and opens at 670 psig shutting down the compressor, while HPS2 opens at 565, limiting the compressor to low-stage operation only. High pressure may be caused by a dirty outdoor coil, failed fan motor, or outdoor air recirculation. To check switches: 1. Turn off all power to unit. 2. Disconnect leads on switch. 3. Apply ohm meter leads across switch. You should have continuity on a good switch. NOTE: Because these switches are attached to refrigeration system under pressure, it is not advisable to remove this device for troubleshooting unless you are reasonably certain that a problem exists. If switch must be removed, remove and recover all system charge so that pressure gauges read 0 psi. Never open system without breaking vacuum with dry nitrogen. Copeland Scroll Compressor (Puron Refrigerant) The compressor used in this product is specifically designed to operate with Puron (R-410A) refrigerant and cannot be interchanged. The compressor is an electrical, as well as mechanical, device. Exercise extreme caution when working near compressors. Power should be shut off, if possible, for most troubleshooting techniques. Refrigerants present additional safety hazards. EXPLOSION, FIRE HAZARD Failure to follow this warning could injury or death and/or property damage. Wear safety glasses and gloves when Keep torches and other ignition refrigerants and oils. result handling sources in personal System OPERATION Synthetic Roof Precautionary Procedure 1. Cover extended roof working area with an in,permeable polyethylene (plastic) drip cloth or tarp. Cover an approximate 10 X 10 ft (3x3 unit base. 4. Perform required service. 5. Remove and dispose of any oil-contaminated local codes. material per FILTER DRIER The filter drier is specifically designed to operate with Puron. Use only factory-authorized components.. PURON (R-410A) REFRIGERANT CHARGING Refer to unit information plate and charging chart. Some R-410A refrigerant cylinders contain a dip tube to allow liquid refrigerant to flow from cylinder in upright position. For cylinders equipped with a dip tube, charge Puron units with cylinder in upright position and a commercial metering device in manifold hose. Charge refrigerant into suction line. TROUBLESHOOTING LED DESCRIPTION This step covers the refrigerant system of the 48XL, including the compressor oil needed, servicing systems on roofs containing synthetic materials, the filter drier, and refrigerant charging. REFRIGERANT UNIT POE (polyolester) compressor lubricants are known to cause long term damage to some synthetic roofing materials. Exposure, even if immediately cleaned up, may cause embrittlement (leading to cracking) to occur in one year or more. When performing any service that may risk exposure of compressor oil to the roof, take appropriate precautions to protect roofing. Procedures which risk oil leakage include, but are not limited to, compressor replacement, repairing refrigerant leaks, and replacing refrigerant components such as filter drier, pressure switch, metering device, coil, accunmlator, or reversing valve. LIQUID-LINE The Copeland scroll compressor uses Mobil 3MA POE oil. This is the only oil allowed for oil recharge. OIL The compressor in this system uses a polyolester (POE) oil, Mobil 3MA POE. This oil is extremely hygroscopic, meaning it absorbs water readily. POE oils can absorb 15 times as much water as other oils designed for HCFC and CFC refrigerants. Take all necessary precautions to avoid exposure of the oil to the atmosphere. SERVICING SYSTEMS ON ROOFS WITH SYNTHETIC MATERIALS refrigerants. away from The scroll compressor pumps refrigerant throughout the system by the interaction of a stationary and an orbiting scroll. The scroll compressor has no dynamic suction or discharge valves, and it is more tolerant of stresses caused by debris, liquid slugging, and flooded starts. The compressor is equipped with an anti-rotational device and an internal pressure-relief port. The anti-rotational device prevents the scroll from turning backwards and replaces the need for a cycle protector. The pressure-relief port is a safety device, designed to protect against extreme high pressure. The relief port has an operating range between 550 and 625 psi differential pressure. Refrigerant COMPRESSOR AND SAFETY Failure to follow this warning iniury or equipment damage. could HAZARD result in personal This system uses Puron (R-410A) refrigerant which has higher operating pressures than R-22 and other refrigerants. No other refrigerant may be used in this system. Gauge set, hoses, and recovery system nmst be designed to handle Puron. If you are unsure, consult the equipment manufacturer. LEDs built into Infinity control boards provide installer or service person information concerning operation and/or fault condition of the unit controls and ECM motor. This information is also available at the system UI in text with basic troubleshooting instructions. Careful use of information displayed will reduce the need for extensive manual troubleshooting. See section B in Start-Up & Troubleshooting and Table 5, as well as the UI instructions, for additional information. Additional Troubleshooting information can be found in Table 10. MAJOR COMPONENTS 2-STAGE HP/AC BOARD The two-stage functions: HP/AC control board controls - Low- and high-stage compressor operation - Outdoor fan motor operation - Reversing valve operation 3O the following - Defrost COMPRESSOR operation - Low ambient - Crankcase cooling - Pressure external potential problems. The control continuously monitors the high voltage on the run capacitor of the compressor motor. Voltage protection switch monitoring (refrigerant) should be present any time the compressor contactor and voltage should not be present when the - Time delays FURNACE BOARD The furnace board - Indoor blower the following CONTACTOR functions: operation SHORTED If there is compressor compressor operation, - Inducer a wiring motor sparker - Pressure switch monitoring module COMMUNICATION FAILURE PLUG The HP/AC control board must have a valid model plug to operate. If a valid model plug is not detected, it will not operate and the will flash the appropriate PRESSURE SWITCH The unit is equipped 1. De-energize compressor with high- in Table 5. switches. or low-pressure If the switch, it & LPS) or the for 15 minutes. fault codes. delay, if there is still a call for cooling HPS is reset, the compressor and contactor is 5. If LPS or HPS has not closed after a 15 minute delay, the outdoor fan is turned off. If the open switch closes anytime delay, then resume operation with a call cycles, the unit operation 8. In the event of a low-pressure appropriate replaced. BROWN check the refrigerant control fault code If the should compressor be starting, voltage is not sensed when the compressor the contactor may be stuck open or there is a wiring Check error. The the contactor control will flash the appropriate and control box wiring. TROUBLESHOOTING board switch charge has failed, trip or low pressure and indoor the control (See TaMe 5). The control is less than (POWER DISCONNECT) PROPER SWITCHING STAGES capacity. The stage liquid pressures operation, current COMPRESSOR are very so liquid pressure similar between should low and not be used for will board for at least flash the should be 4 seconds, the DETECTION increase 20-45% INTERNAL when solenoid, switching when from energized in RELIEF to motor windings. Thermistors temperature If the outdoor displayed. connected insure and 230v wiring is THERMISTORS are electronic devices which sense temperature. As the increases, the resistance decreases. Thermistors are used to sense outdoor ambient Refer to Fig. 25 for resistance 26 for OCT location. control is closed should The compressor is protected by an internal pressure relief (IPR) which relieves discharge gas into compressor shell when differential between suction and discharge pressures exceeds 550 625 psi. The compressor is also protected by an internal overload If there is no 230v at the compressor contactor when the unit is powered and cooling demand exists, the appropriate error code is Verify that the disconnect to the unit. FOR code. Check the suction pressures at the service valves. Suction pressure should be reduced by 3-10% when switching from low to high TEMPERATURE 187v UNIT & HIGH fault airflow. (See Table 5). 230V LINE LOW Compressor appropriate compressor contactor and fan relay are de-energized. Compressor and fan operation are not allowed until voltage is a minimum of 190v. The control will flash the appropriate fault code NO 230V AT COMPRESSOR attached voltage check the unit will resume If the thermal cutout trips for three consecutive cycles, then unit operation is locked out for 4 hours and the appropriate fault code is low to high stage. The compressor high stage, should measure 24vac. OUT PROTECTION If the line interval), troubleshooting. FAULT If the HP/AC thermal protector has not re-set, the outdoor fan is turned off. If the call for cooling continues, the control will energize the compressor contactor every 15 minutes. If the thermal protector high 7. In the event of a high-pressure switch trip or high pressure lockout, check the refrigerant charge, outdoor fan operation and outdoor coil for airflow restrictions. CONTROL fault code. CUTOUT code shown in Table 5. After 15 minutes, with a call for low or high stage cooling, the compressor contactor is energized. If the NOTE: 6. If LPS or HPS trips 3 consecutive is locked out for 4 hours. lockout, will flash the appropriate THERMAL compressor contactor for 15 minutes, but continues to operate the outdoor fan. The control Status LED will flash the appropriate BETWEEN after the 15-minute for cooling. The control displayed. the appropriate or voltage sensed when there is no demand for the contactor may be stuck closed or there is closes (at the next 15 minute operation. and low-pressure of a high- fan operating 4. After a 15 minute the LPS energized. shown the compressor contactor (HPS1 solenoid contactor (HPS2). 2. Keep the outdoor 3. Display fault code, PROTECTION-REFRIGERANT control senses the opening will respond as follows: DETECTION If the control senses the compressor voltage after start-up, and is then absent for 10 consecutive seconds while cooling demand exists, the thermal protector is open. The control de-energizes the (gas) If communication with the Infinity Control is lost with the UI, the controls will flash the appropriate fault codes. Check the wiring to the UI, indoor and outdoor units. control error. COMPRESSOR - Remote MODEL is energized, contactor is de-energized. controls - Gas valve SYSTEMS SENSING The control board input terminals VS and L2 (See Fig. 18) are used to detect compressor voltage status, and alert the user of heater operation - Compressor VOLTAGE ambient or coil thermistor will flash the appropriate IMPORTANT: thermistor Coil thermistor is mounted (OAT) is field mounted been properly installed. 31 (OAT) and coil temperature (OCT). values versus temperature. See Fig. should fail, the HP/AC fault code (See Table 5). is factory properly. and connected. mounted. Outdoor Verify Check to air thermistor that the OAT has THERMISTOR 9O I CURVE I I I 80- k----4------4----_------4-------I .... \ i i i i i 7o- -'_-- q------ I----- _------ T------I .... 6o-_ _X__ J._ _ _ .I_ _ _ __ _ _ J__ _ _I.... \i i i i i 50.... '_------ 1----- _------ 1-------I .... 40- /_.__ l______/___l .... I\ I I I I 30.... _----_'-Z_---_------I------I .... 20.... _ ______/'_._/__ ____/ ____--I.... I I _ I I lo.... H--t---_--_-- o .................. I................... I................... I................... I................... I,,-,_ 0 20 40 60 80 TEMPERATURE 100 "tub 120 (DEG. F) \ A91431 Fig. 25 - Resistance THERMISTOR The control temperature SENSOR Values • In cooling conditions. mode, The comparison if the outdoor g warmer than the coil sensor indicates -> 20 °F cooler than the coil sensor, A06311 Fig. 26 - Outdoor indicates (or) the outdoor the sensors -> 10 °F air sensor IMPORTANT: are out of if the outdoor air sensor indicates 1. Ensure > _ 35 o F (_,_o C) 2. Ensure than the coil sensor (or) the outdoor air sensor indicates -> 10°F (-12°C) the sensors are out cooler than the coil sensor, adding covers. The thermistor FAILED Factory outdoor comparison will flash the appropriate is not performed THERMISTOR DEFAULT defaults have been air thermistor and/or during low ambient is routed OPERATION provided in the event coil thermistor. of failure Troubleshooting information. Chart (Table 10) valve for away from tubing and sheet rub-through or wire pinching. and tubing is secure and covers. service CARE of Securely fasten caps to l/2-turn stem in unit before all panels past and finger AND located file. at the back of this MAINTENANCE For continuing high performance and to minimize possible equipment failure, periodic maintenance must be performed on this equipment. Frequency areas, such information. after 5 minutes. If there is a thermistor out of range error, defrost will occur time interval during heating operation, but will terminate minutes. Refer to the troubleshooting that all wiring panels job, be sure to do the following: 5. Fill out Start-Up Checklist manual and place in customer If the OCT sensor should fail, low ambient cooling will not be allowed. Defrost will occur at each time interval during heating but will terminate Attachment 4. Leave Users Manual with owner. Explain system operation and periodic maintenance requirements outlined in manual. operation. If the OAT sensor should fail, low ambient cooling will not be allowed and the one-minute outdoor fan off delay will not occur. Defrost will be initiated based on coil temperature and time. operation, that all wiring 3. Tighten tight. of range. If the sensors are out of range, the control fault code as shown in Table 5. (OCT) CHECKS Before leaving metal edges to prevent warmer cooling Coil Thermistor FINAL range. • In heating F is: air sensor (-12°C) o tight on the liquid COMPARISON continuously monitors and compares the outdoor air sensor and outdoor coil temperature sensor to ensure proper operating J _ Versus Temperature at each after 5 additional 32 of maintenance as coastal may vary depending applications. See upon Users geographic Manual for AIR CONDITIONER REFRIGERATION SECTION WITH PURON QUICK-REFERENCE Puron refrigerant operates at 50-70 percent higher pressures than R-22. Be sure that servicing designed to operate with Puron. Puron refrigerant cylinders are rose colored. • Puron refrigerant position. cylinders manufactured Cylinders manufactured GUIDE equipment and replacement • Puron cylinder systems • Manifold service should March 1, 1999 and later DO NOT have a dip tube and MUST sets should pressure be charged be positioned • Leak detectors • Puron, • Vacuum rating must be 400 psig. DOT 4BA400 with liquid refrigerant. upside down should pressure be designed will not remove • Only use factory-specified moisture filter driers with rated working rapidly. Do not expose and service • A Puron liquid-line filter drier is required • Do not use an R-22 TXV. • Never to atmosphere must be opened • Do not vent Puron • Observe pressures valves materials. with wet cloth when brazing. on every unit. while it is under a vacuum. for service, break vacuum with dry nitrogen into the atmosphere. all warnings, cautions, • Do not leave Puron suction no less than 600 psig. oil to atmosphere. to certain plastics and roofing • Wrap all filter driers • When system with POE oils. from oil. filter drier in liquid line. • POE oils may cause damage open system device in the manifold rating. moisture liquid-line • Do not install a suction-line • POE oils absorb metering to detect HFC refrigerant. as with other HFCs, is only compatible pumps or DOT BW400. Use a commercial-type be 750 psig high side and 200 psig low side with 520 psig low side retard. • Use hoses with 750 psig service are prior to March 1, 1999, have a dip tube that allows liquid to flow out of cylinder in upright to flow. • Recovery components and bold text. line driers in place for more than 72 hrs. 33 and replace filter driers. hose. to allow liquid Table 9- Troubleshooting SYMPTOM Chart CAUSE REMEDY Power failure Fuse blown or circuit breaker tripped Compressor and outdoor fan will not start Defective contactor, transformer, control relay, or highpressure, loss-of-charge or low-pressure switch Replace component Insufficient line voltage Determine cause and correct Incorrect or faulty wiring Check wiring diagram and rewire correctly UI setting too low/too high Reset UI setting Units have a 5-minute time DO NOT bypass this compressor time delay-wait for 5 minutes until time-delay relay is de-energized delay Faulty wiring or circuit Loose connections in compressor Compressor runs will not start but condenser fan Check wiring and repair or replace Compressor motor burned out, seized, or internal overload open Compressor operates continuously Low input voltage (20 percent low) Determine cause and correct Refrigerant Recover refrigerant, evacuate system, and recharge to capacities shown on rating plate overcharge or undercharge Insufficient line voltage Blocked outdoor coil Replace and determine cause Determine cause and correct Determine cause and correct Defective run/start capacitor, overload or start relay Determine cause and replace Faulty outdoor fan motor or capacitor Restriction in refrigerant system Replace Locate restriction and remove Dirty air filter Unit undersized for load Replace filter Decrease load or increase UI temperature set too low Reset UI setting Low refrigerant charge Locate leak, repair, and recharge Recover refrigerant, evacuate system, and recharge Clean coil or remove restriction Outdoor coil dirty or restricted Dirty air filter Recover excess pressure Air in system Indoor or outdoor air restricted Head pressure too low Excessive suction pressure Check for leaks, repair and recharge Remove restriction High heat load Reversing valve hung up or leaking internally Check for source and eliminate Refrigerant Recover excess refrigerant overcharged charge Metering device or low side restricted Insufficient coil airflow Temperature IFM does not run or air short-cycling too low in conditioned area Replace valve Replace filter Check for leaks, repair and recharge Remove source of restriction Check filter-replace if necessary Reset UI setting Outdoor ambient below 55°F (13°C) Filter drier restricted Verify low-ambient Replace Blower wheel not secured to shaft Insufficient voltage at motor Properly tighten blower wheel to shaft Determine cause and correct Power connectors Connectors not properly sealed Water dripping into motor IFM operation refrigerant Recover refrigerant, evacuate system, and recharge Determine cause and correct Low refrigerant charge Restriction in liquid tube Dirty air filter Low refrigerant Suction pressure too low unit size Replace filter Clean coil Dirty indoor or outdoor coil Refrigerant overcharged head Replace compressor Determine cause and replace Air in system Excessive Determine cause Defective run capacitor, overload, or PTC (positive temperature coefficient) thermistor Defective compressor Compressor cycles (other than normally satisfying) cooling/heating calls Call power company Replace fuse or reset circuit breaker should snap easily; do not force Verify proper drip loops in connector wires Gently pull wires individually to be sure they are crimped into the housing is intermittent Connectors cooling enabled in UI not firmly sealed 34 Table lO--Troubleshooting SYMPTOM Chart Con't-Gas Furnace CAUSE REMEDY Water in gas line Drain. Install drip leg. No power to unit Check power supply fuses, wiring or circuit breaker. No 24-v power supply to control circuit Check transformer. NOTE: Some transformers have internal overcurrent protection that requires a cool-down period to reset. Mis-wired Check all wiring and wire nut connections or loose connections Burners will not ignite Inadequate heating Misaligned spark electrodes Check flame ignition and sense electrode tioning. Adjust as necessary. No gas at main burners 1. Check gas line for air. Purge as necessary. NOTE: After purging gas line of air, wait at least 5 minutes for any gas to dissipate before attempting to light unit. 2. Check gas valve. Inducer pressure switch not closing 1. Check pressure switch wires, connections, and tubing. Repair or replace if necessary. Dirty air filter Clean or replace filter as necessary Gas input to unit too low Check gas pressure at manifold match with that on unit nameplate Unit undersized for application Restricted airflow Replace with proper unit or add additional posi- unit Clean or replace filter. Remove any restriction. Check rotation of blower, temperature Adjust as necessary. Limit switch cycles main burners Poor flame characteristics Operation Incomplete combustion results in: Aldehyde odors, carbon monoxide, sooting flame, floating flame 35 rise of unit. 1. Tighten all screws around burner compartment 2. Cracked heat exchanger. Replace. 3. Unit over-fired. Reduce input (change orifices or adjust gas line or manifold pressure). 4. Check burner alignment. 5. Inspect heat exchanger for blockage. Clean as necessary. START=U P CHECKLIST (Remove and Store in Job File) I. Preliminary information MODEL NO.: SERIAL NO.: DATE: TECHNICIAN: II. PRE-START-UP (insert checkmark in box as each item is completed) VERIFY THAT ALL PACKING MATERIALS HAVE BEEN REMOVED FROM UNIT REMOVE ALL SHIPPING HOLD DOWN BOLTS AND BRACKETS PER INSTALLATION INSTRUCTIONS CHECK ALL ELECTRICAL CONNECTIONS AND TERMINALS FOR TIGHTNESS CHECK GAS PiPiNG FOR LEAKS (WHERE APPLICABLE) CHECK THAT INDOOR (EVAPORATOR) AIR FILTER IS CLEAN AND IN PLACE VERIFY THAT UNIT INSTALLATION IS LEVEL CHECK FAN WHEEL, AND PROPELLER FOR LOCATION IN HOUSING/ORIFICE AND SETSCREW TIGHTNESS ill. START-UP ELECTRICAL SUPPLY VOLTAGE COMPRESSOR AMPS INDOOR (EVAPORATOR) FAN AMPS TEMPERATURES OUTDOOR (CONDENSER) AIR TEMPERATURE RETURN-AIR TEMPERATURE DB COOLING SUPPLY AIR DB GAS HEAT SUPPLY AiR DB WB WB PRESSURES GAS INLET PRESSURE IN.WG GAS MANIFOLD PRESSURE IN.WG REFRIGERANT SUCTION PSIG SUCTION LINE TEMP* REFRIGERANT DISCHARGE PSIG DISCHARGE TEMPI, ( ) VERIFY REFRIGERANT CHARGE USING CHARGING CHARTS GAS HEAT TEMPERATURE RISE TEMPERATURE RISE (See Literature) RANGE MEASURED TEMPERATURE RISE ( ) VERIFY THAT CONDENSATE CONNECTION IS INSTALLED PROPERLY ( ) VERIFY THAT OUTDOOR AIR THERMISTOR (OAT) iS PROPERLY INSTALLED & CONNECTED *Measured at suction inlet to compressor 1-Measured at liquid line leaving condenser. Copyright 2008 Carrier Corp. • Manufacturer reserves 7310 W. Morris St. • the right to change, Indianapolis, IN 46231 at any time, specifications and designs Printed in U.S.A. without Edition notice and without 3d Date: 08/08 obligations, Catalog No:48XL-O4Sl Replaces: 48XL-3SI | https://manualzz.com/doc/2031545/carrier-48xl-air-conditioner-user-manual | CC-MAIN-2018-30 | refinedweb | 22,174 | 56.76 |
WWIIOL web geeks needed…January 24, 2007
If’n you’re not a WWIIOL player or’n you’ve never built a web page, this’n isn’t for you. An’ if’n you try to read’n on, I’m promise’n I’ll do my damn’est ‘n write it all like this’n.
I’m going to give you a preview of something to look at, review really.
Now – take a deep breath. Do not get all overexcited on me. Tell yourself: this means nothing. This is not an official CRS project. I’m doing this in my spare time because Killer has been asking for something like this since Day 1, and because there is overlap with part of my day job (game management and monitoring).
When I started here, game management consisted of a handful of text files (also used to control the building of client datafiles), terrain data. And that was it.
Game management tools consisted of a web page that could tell you if a server might be online or not, and let you brute-force shutdown or start a server.
There wasn’t a whole lot to manage. If you wanted a change, you rebuilt the server.
Wanted to release a patch? Our host coder had to log into a particular box, open up a manual SQL connection to the server and manually update the database tables (which were seriously over-engineered for our usage), restart the auth server, and see if the changes worked.
There was a reasonable amount of monitoring going on, but it was done the extremely hard way (manually crunching of log files).
*Some* game management could be done by bringing the servers down, changing database records and restarting it, but that was pretty limited.
So I started out building tools with Roxen webserver using their RXML language to make it drop-dead trivial to create useful management and monitoring tools. RXML is a very matured version of what JSTL might hope to become (bear in mind, RXML is 10+ years old).
However, Roxen is something of a dying sun (if you follow the first link, note the dates on the right), while JSTL has become mainstream. I am already using a lot of JavaScript and AJAX on recent internal tools, and I’ve done a little retrofitting. That just made switching to JSTL a bit easier, and the time had come for me to try it all out on a scratch pad.
At the same time, this seemed like it might be a useful beginning for something we’ve wanted to do for a long time – carefully exposing some of the game’s data in a format that can be used by afiliate sites.
So while I’m not CRS’s “web guy”, I have nothing to do with our external websites todate, I am the internal “web-tools” guy.
And so, this brings me to my little preview: Wiretap. (Edit: This was formerly a link to zombo.com to make sure you read on) No, this isn’t a joke, but I wanted to make sure you understand that this is a preview. The content was chosen because it was something I needed to work on, not because its what we intend to provide (although for the time being, I guess we *are* providing it).
The URL, which I ask you not to share, since I’m not trying to load or stress test this service, is web3 dot wwiionline dot com.
Disregarding what content is included, not withstanding the content you think should be included, I’m looking for feedback on the documentation, the tutorial, the scripts, the XML and JavaScript. I’m looking to see what kinds of questions the material is going to raise so I can maybe put together an FAQ before we begin investing real time in it: everything so far has been done in my spare time while playing EQ2.
Why did you roll your own ajax and dom utilities? THere are about 500 frameworks out there that have done all this and are well tested.
I just used the tools I use. And since I use them, I decided to include them to be on the same page as anyone working with the files. I never tested the XML or JS I’m using with anyone elses framework.
I added a squadlist.
Learning AJAX is on my todo list so this was nice push =)
The stuff I had a look at was pretty easy to understand so I’m looking forward to when more stuff is added. Then I just have to come up with some use for it but that’s not really the hard part =)
I am actually in the process of building a tomcat server. Now I don’t know what to do first. Work on this, or work on getting my XP machine back up fully to play.
I think a captures list will be next :)
Ah…if only you had this stuff two years ago when I *might* have had time to do something with it.
The really clever web guys would use something like this to poll your data at regular intervals into their own database to make it possible to scroll through a campaign.
Seems simple enough. I wish there for a possibility to get current map state (CP ownerships), and a list of captures similar to the current list of HC unit moves. Also, we need weather report and perhaps a forecast :)
I’m just about to do the CP Ownership one.
Very cool. I used to do something similar with an online league, the game did not have it but the league offered some of the info through XML queries, and it was very useful.
One “trick” I used to use there was to query the XML and sometimes store it locally (or the resulting transformed page) so I would not overload the server. I also use something like that to be able to display TeamSpeak’s server info.
Right now I have a script that takes a snapshot of the front twice a day and then I create an animated GIF to see how it went. Useful for post-analisys ;).
With the XML… AJAX, Flex… generating full HTML pages… nice :D
Salute!
Grr. I’m trying to do something in XSLT to automate generation of the documentation. I’m trying to write an xslt:template that will build the argument list for a query. However, my XSLT is rusty and I can’t remember the easy way to do something like this (substitute [] and <>]
[xsl:if test='@optional']{<i>[/xsl:if]
..describe the argument..
[xsl:if test='@optional']</i>}[/xsl:if]
What I wind up doing is:
[xsl:choose]
[xsl:when test='@optional']
{<i> ... describe the argument ... >/i>}
[/xsl:when]
[xsl:otherwise]
... describe the argument ...
[/xsl:otherwise]
[/xsl:choose]
Which is ok; but is there a cleaner way I can do this?
What a cool little interface you’ve created – we’ve been dying for one of these for ages. Now if it could also link with the CSR in some way, that would be cool, that is the data we most want on our squad site. Though I understand this is likely a pipe dream of ours.
Do you have any problem with us polling this regularly(ish) and then storing the results in a database so we can build up a campaign history? I can fully understand if you do. By regularly, I mean once an hour, and likely just the CP ownership data when you’ve done that. With this data, I’d like to look at making some animated campaign maps (should I ever find the time!). This wouldn’t be too difficult as you supply the X/Y coordinates and I’m sure both sides would be interested to see these to analyse their campaigns…
Anyhow, I dream and digress. Fantastic stuff you’ve got here Kfsone.
S!
Sure, polling is ok, try not to drown or swamp it, data has a granularity of about 5 minutes, so you don’t need to poll more frequently than that for the same data, really.
I added the current CP states – within 5 minutes – see for a list and documentation.
I’ll link that to the front pages shortly.
But the CP states is
/xml/cpstates.xml
/xml/cpstates.citys.xml
/js/cpstates.js
/js/cpstates.citys.js
Why am I seeing Zombo? :)
Doh!….I’m a dummeh..
Kfsone, I do XSLT all day, but don’t quite get what you’re after, but why can’t you just do:
[xsl:if test='@optional']{
..describe the argument..
}[/xsl:if]
You can mix the [xsl] tags with html tags as the XSL tags are in the XSL namespace whereas the html tags have no namespace.
Perhaps I don’t get what you mean, but I’m off to bed in 30 – if you email me the full XSL you have, I’ll try to turn it around quick for you if I can…
Unless I’m mistaken, is “hcstatus.xml” a list of units and their locations? I still have that brigade tool and my biggest problem is having to update the current map state by hand, so this could be quite the help indeed for us strategic types…
And in the squad lists, are those variables (country, branch, etc.) just little things thrown in there, leftovers from old plans, or hopeful dreams? (I know better than to speculate about the near future. ;) )
Defting: It *always* describes the argument; but if the argument tag has an “optional” attribute, then I want to put it in italics with {…} around it. Take a look at my XSLT (its a bit crummy,). It’s the “xsl:for-each select=’attribs/attrib’” chunk — It was easy enough to put {}s around the block with xsl:if, but I couldn’t work out how to put it in italics or a different color.
That chunk was originally [xsl:apply-templates match="attribs/attrib"] but then it had this nasty side-effect of dumping the other attributes into the output too (which are at the same level as attribs, so I found that a little bizzare)
Victarus: Yes it is :) Make sure you check out for a list and description of the ones I’ve done so far.
HC Unit Status examples:
Individual unit:
German units:
lol, I wish you had made this post about a month or so ago then – right now I have a completely arbitrary system for CP IDs. Now I need to either make a list to convert them whenever I reference the “official” IDs or go over the one I have and make them match. (Fate is a horrible, evil thing sometimes. :p )
Well this is definitely a motivation for me to learn networking & xml at least. Hopefully the ability to open a map to fool around with brig movements will encourage a little more planning which, in turn, will make stalemates much less common, adding to the fun of the overall map. A little optimistic maybe, but it’ll help a little at least. :)
I added the octet x and y of the CPs to the meta-data files. (octets are 800×800; so to get the aproximate x/y in metres, multiply by 800)
This looks excellent kfs, nice work!
Do you plan to provide data for ab/depot/fb/etc ownership changes? Or would that be too finer resolution?
I’d like to write a system tray notification tool that would display a small alert upon change of faculty ownership, fb ownership, cp ownership/control, brigade movements, AO placements, etc.
Idealy there would be a full xml listing (that you could cache for, say, 30 minutes at a time), and an xmlquery for recent changes. So i could establish state by grabbing the whole xml once and roll forward using the xmlquery, then poll the xmlquery every so often.
Hi Kfsone,
How about…
…
[span class="mandatory_arg"]
[xsl:if test=’@optional’]
[xsl:attribute name="class"]optional_arg[/xsl:attribute]
[/xsl:if]
[/span]
…
And then link to a CSS that defines the attributes for the classes mantatory_arg and optional_arg. If you don’t want to add another file, then simply put the css styles at the beginning of the generated html.
In the long run, it pays to move the styling to a CSS, and it also makes those kind of things simpler.
Salute!
Oh, I did not see the ‘{’,'}’ around the optional arguments definition… but that has to be solved with if’s, if you want to add it in text and styling it with different font/color is not enough. And “..describe the argument..” should be in there just before the [/span]… it’s just too early for me :)
I thought maybe you could use a variable, in another language I might have done:
var pfx = "", sfx = "" ;
if ( node.getAttribute('optional') ) {
pfx = "<i>{" ;
sfx = "}</i>" ;
}
output = pfx + describe(node) + sfx;
I also tried defining a template
<xsl:template
<i>{<xsl:apply-templates}</i>
</xsl:template>
<xsl:template
... describe the node ...
</xsl:template>
But I kept getting other nodes at the same level as “attribs” dumped into the output :(
Very likely we’ll do facilities too. But I suspect we may want to increase the delay on that information and also monitor the provisioning costs.
Implementing the delays may actually obviate the ‘expense’ of the queries, for instance; I delay the HC Unit information by copying the current data into a shunt table every 10 minutes, and then copying the shunt table into the published table before we next copy into the shunt, so the information you get is 10+ minutes old.
I dont know if you know my little unfinished game called “THE HC GAME” ( and)...
I could try to implement “read real world” so it could read the current game world and import it on my game map. As soon as I figure how to know all brigades positions on map I will shoot a try…
BTW, I gave each city a IDnumber and x,y coordinates, and I am doubing if implementing same numbering as CRS had or continue with my own datas…
————-
…
[xsl:for-each select="attribs/attrib"]
[!-- changes start here --]
[xsl:variable name="pre"][xsl:if test="@optional='true'"]{[/xsl:if][/xsl:variable]
[xsl:variable name="post"][xsl:if test="@optional='true'"]}[/xsl:if][/xsl:variable]
[xsl:variable name="elementName"]
[xsl:choose]
[xsl:when test="@optional='true'"]i[/xsl:when]
[xsl:otherwise]u[/xsl:otherwise]
[/xsl:choose]
[/xsl:variable]
[xsl:element name="{normalize-space($elementName)}"]
[xsl:attribute name='title'][xsl:value-of select="@tip"/][/xsl:attribute]
[xsl:value-of select="$pre"/][b][xsl:value-of select="@name"/][/b][xsl:value-of select="$post"/]
[/xsl:element]
[!-- changes end here --]
=
————-
This gets the optional elements to be surrounded by ‘{’ and ‘}’ and be in italics, while the mandatory ones are underlined.
Checked against your data.xml file.
Cheers!
I bet someone could write a sidebar app for Vista that would show this data.
Kfsone – got what you mean now – was late and brain wasn’t working.
To get your templates to work use:
—
[xsl:template match="attrib[attribute::optional='true']“]
[i]{[xsl:call-template name="attrib" /]}[/i]
[br/]
[/xsl:template]
[xsl:template match="attrib" name="attrib"]
[u title='{@tip}'][b][xsl:value-of select='@name'/][/b][/u]
=
[xsl:choose]
[xsl:when test="@type"]<[xsl:value-of select='@type'/]>[/xsl:when]
[xsl:when test="@values"][xsl:value-of select='@values'/][/xsl:when]
[/xsl:choose]
[xsl:if test="@optional='false'"][br/][/xsl:if]
[/xsl:template]
—
The only bit I don’t like is the if-test for the false @optional attribute to output the trailing [br/] which in the optional=true template is called after the trailing }, but can’t be called by default in the attrib-template otherwise it will break before the tailing }.
Ok – thank you both :) And, good catch, Defting. That br/ originates from when I couldn’t get the argument strings to work :) Had completely forgotten how variables worked, and the difference between match= and name= / apply- vs call- with templates. I still don’t exactly get why apply-templates match=”attrib” was dumping the rest of the upper-level nodes but…
how about adding factory states when you add stuff next time?
oh and I just have to ask… would it be possible or rather, would you do a non-delayed list of towns with bomber ews on? Did this little thing a while ago in java where I typed in the names of the towns that set off ews and got lines towards the factories so I could see what way they were flying or if they were going to the factories at all. Anyway, it would be cool to have it update itself so I don’t have to check the map every time EWS goes off somewhere.
Is one of the goals here to create an application that could essentially tell me when I should log on?
I play 3 times a week during a set time, but I’d gladly change these times based on the status of the gameworld – if I could look on the web or get an automated message on my blackberry.
We all hear about great battles that take place when we are NOT online – and its a shame that we miss them simply because the technology is not there to vibrate my pager while im dozing off in front of Grey’s Anatomy with the wife!
Help me, please!
Trout
We deliberately delay the data. We don’t want the HCs knowing the other side has moved within seconds of them moving a unit. We don’t want you having supercomputer automated ninja ews tracking powers.
It wasn’t a goal I had in mind, but that sounds like its in the spirit of the sorts of things I’d hope to be able to enable. I don’t currently keep AOs in a database (I do track statistics, but not where actual AOs are). I probably should, with a short delay on exposing that data, so that you could track things like that.
- Oliver
Firefox says that the current datasets.xml isn’t well-formed:
XML Parsing Error: not well-formed
Location:
Line Number 2, Column 6:
Fixed.
Added captures and facilitylist.
Added captures and facilitylist.
Yay! This is great!
A couple of comments:
/xmlquery/captures.xml
- The hours param doesn’t appear to be limited to 168 (plugged in 10000 and got data back to 2006-11-10 12:04:04.0).
- Also, it would be easier if the hours param wasn’t required when using the fromid field.
/xml/facilitylist.*
- Is it possible to get a higher resolution for the x/y coords for facilites? Many that are within >800m of each other have the same coords, which isn’t very useful for plotting a town on a map.
Lastly, i’d be nice if we had a way to get the owner of all facilities (ie, xml with just id and owner, updated infrequently) that we can maintain using /xmlquery/captures.xml
(or even just for the facilities in contested cp’s)
Of course, the downside to Ajax is that you can’t pull 3rd party data. If someone wants to make Ajax tools that make use of the XML data in an Ajax page, they’re going to have to pull the data to their own site or Proxy the queries themselves.
Finally!
Now that saves me from pulling all the CP info from the map pages and CSR – admittedly I did get a reasonable way with some RXML for tracking the opposing HC characters movements and tying back to their logical brigades. Then again, that was 18 months ago and pre-dated having any kind of in game link! :p
Methinks it’s still past time to turn off my old wwiiol stats pages.
asn
Heh, tomorrow I’ll add a 15 minute delayed all-facilities status and a 5 minute delayed “facilities that don’t match CP”.
My game (THE HC GAME) can now read the live cities status. Expect an update soon reading brigades.
Anyway to get cities with AO?
We don’t currently export that information in a useful format to a database, but I’ll be adding it after I get done with current projects.
First off… This is a great start KFS1. Thanks.
Darn it now you are going to force me to update my map/rdp widgets. :)
Question 1) How do coordinates in octets map to geographic coordinates?
Question 2) This may be simpler. What are the dimensions in octets of the status map on the WW][OL homepage?
That’ll do for starters. Woot!
Actually, one of the pages describes octets. Octets are our 800×800m tiles and 0.0 is 0.0.0N 0.0.0E; while ox=1,oy=1 is 800m north and 800m east of 0.0.
I’d have to ask Ramp for the dimensions.
finally came to check the site out. Lots of cool info here. I’ll be visiting more often. & you of course know I have nada to offer LOL
& ya I cant type my tag right the first time either ;P
where’s the edit button!
What is the standard identification means for the eight 400m x 400m right triangles that make up an octet?
Are there standard ways of referring to which of the faces of a 400m x 400m right triangle one is referring to, and/or which of the vertices?
Thanks for your work on this. I’d sure like to be able to obtain a list of all members of our squad (according to the CRS database) regardless of when they last logged in. As far as I know there’s no way to obtain the list OUTSIDE of the game. Do you have a query/script for that?
That’s currently something that we have agreed would not be delivered outside of an official package arrangement – i.e. outside the bounds of what I can expose in my private experimentation. That’s not to say we won’t do it, or that we will charge for it, just that its not something we want to release without this being an official CRS deal.
hi,
I see your work, this is very good.
I see that you don’t want give some information for squad people, but can we have the same information for a player than the csr, with the use of a xml command ?
Tanaka.
hi,
i sent you an email asking if we can have some information about what we can have from specific location
do you received it ?
I work for the 3e DLM Squad (Squad Id : 16), where i am XO and where i work with the 2 other website admin
I just tried to include a Data page to my NEW web site for the C-Hawks.
If I go here and go to the bottom the page the link “Click here for the completed example.” It works Great. But from my page, I get a page error and nothing loads.
The code is identical to the source code you have.
Does anyone know why it’s not working?
Already answered that here earlier and on other threads. Ajax doesn’t allow you to pull data from a different source than the html/javascript you are viewing. So you have to either copy, mirror or proxy the data for yourself.
kfsone Says:
March 5th, 2007 at 8:52 pm.
no news ?
Tanaka, from the original post:
I don’t see us picking this up as an official project until after we’ve gotten TOEs out of the way. I’m currently working on finishing up some of the management tools which I hope to have done by Monday so I can move into more active beta testing.
oh, ok kfsone,
When i read your first answer after my question, i understood that this is already made and we had only to ask for the tools.
Didn’t understand this will be a possibility !
I understand you must finish what you do for the official part, because i will use it faster.
excuse me, but i am french speaking man, and sometime i don’t see subtelity in the language
S! Kfsone,
I was wondering if there a XML feed for a sortie. I’m working on a webapplication for the ww2ol community. And I need to read a sortie. I can produce a script that can read the HTML source code of a sortie, but it would be easier to use a XML feed for it.
The sortie is read only once, and then stored in my own database. So not a lot of traffic for CRS. And the player need to submit thier sorties (sortie id’s), so not an automatic polling system.
But anyway my question is:
Is there a XML feed for a sortie? I would like to submit a sortie id and get some data back. For example:
- date time
- campaign
- persona id (pid)
- player name
- kills
- kills in detail (unit, player)
and maybe more.
I hope you can help me!
Falcko
hi falcko
i ask for it, but this is not the priority first atm
found your own system to get it, i did, this is long, but work
you want it ?
if you want something i make a “zip” of my own program, you can get here :
Use it with precaution, to get the entire information for a squad of 30 members, this is 2 x 6 hours for each big table “MembreSortie” and “Membrekill”
Thanks Tanaka!
I will look into it.
Last week I made an PHP script that will read the sortie from the HTML page, so i’m good for now. Just like I did read the kill stats to make the banner below:
Falcko
Falcko, this is what I used to do until I extended it too much and CRS blocked my site from scraping their site. Just before it was blocked I was scraping approx 1,200 players at the time.
Was a fun project, I had quite a lot of stats built up, not sure I have the database anymore I deleted it I think.
1200 players !!!!!!!!
i have only 35 players !!!
Ok, been tinkering with CP Ownership to see where AOs are at the moment. At this moment I see several AOs per side, but in game it is only 2 AOs per side?
Is CP Ownership delayed?
It’s showing AOs that have come down but not been un-ao-ified. Not much help :(
Oh, and I’m having trouble getting more than 1 Ajax Object running per page, which is limiting :(
Did that clear up the non-AO towns?
Top dog :) Thanks KFS1 :)
It’s gone again kfs, it’s reporting too many AOs.
Found a new bug in
It never shows the Axis FBs as open, open is always false for them, the French/British FBs are fine.
Oh, I know you’re busy with TOEs and this is a side project, so don’t worry about it, thought I’d just tell you :)
I’m not seeing anything like that.
or more concisely
So to find all active FBs to say Luxembourg I would have to poll all surrounding towns? Seems overly excessive on the XML polling.
Would make sense to expand facilities.xml to include inbound open fb’s also.
Seems that when the attacking force cap the AB (before the town is captured) the open=’y’ tag disappears, which is rather annoying.
Do you mean it never comes back? Its supposed to close when they cap the town but it should open again eventually. I looked thru the code and I don’t see any route by which the AB could ever be opened without updating the database.
Say the Allies are attacking Trier, they will eventually have to cap 3 of the 4 ABs in town and then make sure the last AB is capped last.
Once the allies get to this stage, the capped ABs never show up in the Allies list, if the Axis cap them back they return to the list.
I’m building a Java model of all the various objects and their relationships with navigable links between them all, and it’s coming along very nicely. I’m not sure what I will do with it afterwards, but it should be possible to give it a GUI or web front end of some sort. Early days yet though :)
The documentation for the CP Ownerships query appears to differ from what is actually returned. It says:
ao= Side (or 0) which has an AO on the town
But the ao element actually contains:
Let’s try that again, since it gobbled the tags:
ao=”true”
The Facilities query appears to be the only way to determine the current ownership of a facility, but it’s necessary to specify a specific CP in the query. So, to determine the ownership of all capturable facillities, it would be necessary to issue 795 separate queries, one for each non-bridge CP (unless I missed something, in which case please feel free to point it out).
How about adding a new option ‘cp=all’ which includes all facilities for all CPS, but only where the the current owner of the facility differs from the current owner of the CP?
That would still be a lot more information than you need: as of 1.27 its really only the side that matters, and you can tell that from getting a list of who owns all the CPs. You then only need facility level detail for contested towns, and I’ll look at adding an option to return all contesting facilities.
Re aos=true – it appears tomcat coerces any tinyint(1) into a boolean value by default. Fixed.
I noticed you fixed it, it broke my app of course :)
A few other minor things while I think about it.
The country metadata should probably have a ’side’ element to tie the two together.
I’m not sure I understand the subtle distinction between ‘owner’ and ‘controller’. Especially as CP states defines controller in terms of country, whereas firebase status defines them in terms of side.
I don’t use cpdetail.xml because I am using sets and maps to hold related items, but I couldn’t help noticing when I parsed it that there are a small number of CPs where there is a discrepancy between for example the number of ABs and the actual number in the facilities list which are linked to that CP. I don’t think it’s my bug and I didn’t keep a list of the differences, sorry. I should have done.
In cpdetail.xml there is a ‘links’ attribute. Isn’t this just the same as the one in cpstates.xml?
My app is working quite nicely in terms of linking everything together, although at the moment it’s just dumping stuff about towns with AOs, for example:
Attigny
CP id: 307
Contested: no
Has AO: yes (Allied)
Original country: France
Original side: Allied
Owner: Germany
Controller: France
Depots
Attigny Railway Station
Attigny-Vouziers Depot
Attigny City
Attigny-Rethel Depot
Firebase: Attigny-Rethel FB (Germany)
Attigny-Mazagran Depot
Depot link (no firebase): Mazagran-Attigny Depot
Attigny-Launois Depot
Army bases
Attigny Armybase
Firebases
Attigny-Launois FB, Closed
Attigny-Vouziers FB, Closed
Vouziers-Attigny FB, Closed
Attigny-Rethel FB (Germany), Open
Rethel-Attigny FB, Closed
Launois-Attigny FB, Closed
Outward links
Attigny-Vouziers Depot -> Attigny-Vouziers FB (closed) -> Vouziers-Attigny Depot
Attigny-Rethel Depot -> Attigny-Rethel FB (open) (owner Germany) -> Rethel-Attigny Depot
Attigny-Mazagran Depot -> Mazagran-Attigny Depot
Attigny-Launois Depot -> Attigny-Launois FB (closed) -> Launois-Attigny Depot
Inward links
Attigny-Vouziers Depot <- Vouziers-Attigny FB (closed) <- Vouziers-Attigny Depot
Attigny-Rethel Depot <- Rethel-Attigny FB (closed) <- Rethel-Attigny Depot
Attigny-Mazagran Depot <- Mazagran-Attigny Depot
Attigny-Launois Depot <- Launois-Attigny FB (closed) <- Launois-Attigny Depot
I’m adding the unit stuff next. It’s been an entertaining diversion :)
Added units:
Antwerp
CP id: 320
…
Deployed units
Army: 1st Infantry Division (1st Corps)
Air Force: 76 Squadron (CAS Brigade) (70 Bomber Wing)
Navy: 19 Destroyer Flotilla (Nore Command)
Not a bad afternoon’s work but that’s enough for today :)
There seems to be a problem with the firebase open status returned by the facilities.xml?fbs=all and facilities.xml?fbs=open queries.
Today, Chilly was axis and Charleville was French and therefore one of the pair of firebases (1815 and 1818) should have been open, shouldn’t it? Neither was returned as being open in either query.
Ignore that, it was my bug to do with town ownership :)
kfsone, I’ve got enough of an app for you to have a look at now, if you want to. Email me your email address and I’ll send you a link. I have a todo list as long as your arm but it’s coming together.
kfsone@playnet.com
Why not post a link to it? There’s a few of you working on apps, so far each with its own special emphasis. Quite possible y’all could be pooling some of your resources and/or focusing your own projects on your preferred aspects :)
OK, it’s here:
Read the readme first:
I will update it periodically whenever I work on it.
In the capture list query, there are ‘from’ and ‘to’ attributes. Do these indicate the country ownership of the facility? If so, they are currently always the same, so it’s not working. Or have I got the wrong end of the stick?
I notice that quite a few entries in the capture list have squad=”0″ – does this have some meaning, or is it a bug?
I was also wondering what (if anything) would go into the capture log when the AO is pulled on a contested CP, causing all attached facilities to revert to the town owner.
sres: “Seems that when the attacking force cap the AB (before the town is captured) the open=’y’ tag disappears, which is rather annoying.”
The AB stays closed until it is spawnable (you obtain ownership). If the database reflects that, its accurate.
SLR: I already said somewhere else that the current 1.26 host is writing the wrong data to those columns. You’ll have to wait for 1.27 for a fix. Squad 0 is no squad.
Of course… I completely forgot some people aren’t in a squad, and of those, a few are capable of capping things :)
Lone Wolfs are valuable. Never rule out the power of 1.
So is 1.27 ready for the next reset? I know, I know, I just want an odds 50/50 60/40.
A WIRETAP-related bug report:
file:
line: 3
The attribute tag ‘version’ is misspelled as ‘versioh’.
/xmlquery/cps.xml/cps/cp@ao is no-longer a boolen or a side number, it is now the id of the attacking brigade.
I noticed, thanks.
Has the cpstates query gone a bit wrong? There are a lot of CPs shown as being owned and controlled by country 2, i.e. USA. I think it’s a large proportion of the bridges.
2 = destroyed I think
OK, thanks. All the data feeds seem to have stopped updating now by the way – nothing new for a couple of hours.
Are your servers synchronized via ntp with any time servers? You seem to be returning capture times which are in the future by anything up to 30 seconds.
On second thoughts maybe if I spawn in quick I can kill the capper :)
My application reports that there are occasional gaps in the capture logs:
Capture id 836 missing
Capture id 1829 missing
Capture id 4580 missing
Capture id 4801 missing
Capture id 4803 missing
Are these numbering gaps just an artefact of some internal mechanism for allocating them, or do they represent missing data?
I’m trying to get my head round a discrepancy in the data between CP ownership and the captures which change CP ownership.
Take Leuven (id 272) for example. Its original owner was England, it does not appear in cpstates.xml implying it is still owned by England, and it shows on the map on the WWIIOL site as being owned by England. It seems fairly comprehensive therefore that it is owned by England. However, the ownership changes in the capture log are:
Wed Aug 29 18:15:29 BST 2007 ENGLAND -> GERMANY
Wed Aug 29 18:44:58 BST 2007 GERMANY -> FRANCE
So, why isn’t Leuven owned by France? Is there some other way apart from a capture that a town can change ownership between the allied countries?
Interesting how this data exposure to benefit gameplay also has potential as a means of allowing selected members of the community to aid in bug identification. 8^)
The gaps you are seeing are non-capture events, and side 3 is neutral – it was already in the meta data, I hope its a little more obvious now.
All of the servers are ntp synced to a strata 1 server. How about you? Or are you running the “linear time is a myth” operating system from Microsoft?
I don’t think blaming Microsoft is the answer in this case ;) My dev system is XP/Vista, and of course the clock is wrong as usual, but it’s only two seconds out, compared it to my office clock. That is synched to an atomic clock every night by radio signal, and is always accurate.
Just now I got a cap time which was 13 seconds in the future as far as my dev system is concerned (i.e. really 11 seconds compared to the atomic clock ). Maybe you should check the ntpd logs to see if your syncs are really working, otherwise it’s a bit of a mystery.
What is a ‘non-capture’ event? Sounds interesting.
Nope. All of the servers are within 0.012 microseconds of 15 NTP servers I pointed them at ranging from Stratum 1 through 3. Windows provides notoriously unreliable time keeping.
I will check tomorrow that I’m not adding the capture duration to the capture time, but the clocks on those machines take about 399 days to drift the same amount as the typical desktop PC does in a day, and the operating system keeps time with significantly greater accuracy than any windows build todate.
I am a software engineer and do appreciate a lot the topics and work dedicated to enhance the game play of battleground europe.
Is there any script around or any page that will allow me to see a squad member list?
This could be very useful for squad admins since they dont have to go manually doing screenshots in the game and then updating squad roster by hand.
…or is there any crs page that allow us to see our squad roster like the old days?
WireTap is still “unofficial” and “alpha”, at this time there are severe limits on what I can expose. The squad info is something that the company still sees a possible saleable on – e.g. having the CO pay a small extra fee in order to obtain a password to let his users access the info via. So the squad info we’re exposing is minimal right now.
Who do i need to get in contact to pay to get a password for myself to get access to squad data so doing maintenance in my site becomes easier?
Nowadays I have to do a lot by hand. If the squad info access is something saleable then I wont hesitate in paying a fee to get access to the data. a mysql database would be great but if i have to fetch it from a web page that would be ok.
Thank you for the info. I am looking forward in hearing from you.
Regards,
You’d have to contact rafter@playnet.com or maypole@playnet.com and talk them into establishing WireTap as an official Playnet service with free and chargeable components.
Right now, WireTap is a service of me, that the company has allowed me to provide within certain constraints; one of those constraints is certain info that they feel it would be damaging to just give away now and then later try to charge for.
I already sent them a message yesterday and have not gotten a reply yet. I am going to resend it because the subject could be filtered as spam (It said: access to web tools). 8-( I did not realize it till now.
I want to thank you for your time. I am hoping I can get access to some data. It doesnt bother to me to pay for it.
Regards,
We had a LOT of people out sick today, seems someone brought something nasty back from the AGC con last week.
KFS1, is there a way to search the capture ticker for past captures. Specifically I want to know what happened in Ciney AB Tuesday Sept 11 9PM Mountain when the allies capped the ab under the nose of 6-7 axis players who were in the bunker.
If it’s an invisible ei then he would have known he was invisible because no one was killing him.
edit: Really, really stupid segment removed
NM KFS1 I figured it out.
Can we have listed here or on wiretap, a list of current apps that uses WireTap data?
The ones I know:
BEview:
BGEIV:
SLR’s:
or
I still think there’s something fishy with the capture times.
My application uses the system clock in conjunction with an adjustment factor which is deduced by an ntpd query to a source I believe is reliable to ensure that it is spot on. Certainly it is within tens of milliseconds anyhow.
The ‘Date’ field in the http header from your server is always pretty close to the expected time, indicating the time of your web server and my system are near enough in sync.
However, the capture query still returns capture times which are anything up to 1 minute in the future, and I don’t really have an explanation for that, unless those times are wrong.
The same thing happens on windows and linux BTW.
Only up to a minute? Rounding?
The highest discrepancy I have seen so far is 55000 milliseconds (it’s all in milliseconds so it’s not a rounding issue).
OK here’s an example of a capture query that’s a bit odd.
The HTTP header returned from a capture query contained a Date field with “Wed, 26 Sep 2007 14:22:58 GMT”
According to my calculations (well Java’s calendar class anyway) that turns out to be (in seconds):
1190816578
In the file returned in the query, capture 18156 was included which had:
at=’1190816636′
So, the capture time was 58 seconds later than the query it was returned in.
It’s interesting that the 58 second discrepancy occurred at 58 seconds past the minute as far as the web server is concerned. It could be a coincidence. I’ll see if there’s a pattern.
The 58 seconds past the minute was a coincidence. At 14:47:43 I got a capture which was 60 seconds ahead of the query it was returned in, a new record :)
Finally, the HTTP date conversion to seconds checks out using a different source:
$ date –date “Wed, 26 Sep 2007 14:22:58 GMT” +%s
1190816578
So to sum up, capture times are often in the future as far as the web server is concerned, and the web server time appears correct, implying the capture times are not.
I now rest my case and await further developments :)
Nope. All of the servers are within 0.012 microseconds of 15 NTP servers I pointed them at ranging from Stratum 1 through 3. Windows provides notoriously unreliable time keeping.
Er? I usually set up a local time server and then pointed everything else at it. That way I have to really only worry about judder on the one host’s connections outbound. Also makes it simple if you decide to get fancy and go with a radio time tick receiver, and lock the heck out of the firewall too… only the one client requires a rule to go out, instead of all of them.
Could be a mySQL issue and how it creates a snapshot of the data that is being queried in the select statement.
How long does it take you to do the total request, From query request until the start of the return of data?
Is it only 1 capture and 1 capture only? It could be how the transactions are fed into the database. The next insert is created and held open until the data is fed in and committed.
This uncommitted record is grabbed by the snapshot and data fed into after the start of the query.
You have to keep in mind this is one of MySQL’s weakest points in handling transactional data.
It’s all conjecture, I know Oracle and Postgres do not have this issue. But I find bug listings for MySQL on this type of issue.
If we’re speculating, then maybe there’s a conversion going on to get seconds since the epoch which is returned in the XML file from some other native format, and there’s a bug in it.
It can’t take long to process the query server-side. The whole round trip time from client to server and back again is only a fraction of a second when requesting captures starting at a known recent capture id.
And? I said:
I don’t recall stating what our NTP configuration was, only its effect :)
I think something has gone a bit awry with the rdpoutput.xml query:
[B@11d0be7
It gobbled the tags as usual but take a look and you will see what I mean.
I’m very very glad by your contribution. Wiretap it’s a great resource for players community, awesome work!.
Thanks a lot mate.
S!, 1SC – Covifox and sorry lang :(
* I’m working on it right now… ^^
Seems you’ve broken the resources page on web3 mate.
Damn. I thought tomcat was stable.
Hi, Kfsone and thanks for your Wiretap -service.
Here’s one new:
Ok, I have a question (possibly stupid) about the coordinates in, for example, the deathmaps.
From the wiretap documentation:
“(x and y in meters from N0.0.0/E0.0.0)”
Ok this might be the stupid part: What map projection system should be used calculated the actual coordinates?
I’m trying to plot coordinates on google maps and need to calculate lat/long coordinates from N0.0.0+x meters / E0.0.0 + y meters…
Use
I have completed a version showing the FB line and kill ratios on a webpage image. It also includes graphical movements history and a campaign viewer.
Fun stuff that wirefeed.. something to chew on for many hours to come :P
S!
GenXS
KFS1, could you possibly add a xml feed with the current campaign number and day in the campaign ? This would help enormously with the archiving me and others are doing. For example see the campaign viewer on. I would like to add the campaign day printed to the image but can’t find where to read it.
Second, any luck on the new image map ? Or is that delayed due to the new CPs coming on the map ?
And third, my tool keeps track of the amount of CP’s allied and axis. Is it correct that there are currently 597 victory related CPs on the map ?
Thanks in advance.
GenXS
S! Kfsone
I’d find it helpful if you’d add “from” and “to” for FBs to facility list:
where from would be the id of the cp the FB opens from and to the id of the cp the FB opens to.
Added config.xml which has as many database-held configuration values as I’m able to expose.
Zeta: You can get that information from links.xml or links.js.
I did, however, add a list of open FBs with ownerships:
Thanks, KFS1. I never noticed the FB-attribute in the links file. I was afraid I’d have to parse the info from FB names.
(btw, the problem with my server not opening some of the wiretap files dissapeared ‘by itself’ just like it started — I’m content to leave it to be ‘one of those things’ and not think about it anymore :)
??
after some days spen to read the Xml data by php (no ajax, no js, with good final result, until the Xml response was right)…
now the link don’t works more, because the SQUAD field is always and only set to 0…
why??
this resource don’t works frome some days…
it displays always and only results from squad=0
why?
opps, sorry, only now I can see online the first post :-(
Revealing the squad affiliation was the single most source of complaints about WireTap so we decided to make the call to reveal it. Sorry :(
very sorry me too… and I really can’t understand why
someone feels embarrassed about his squad??
I have made another php
in wich I read NOT names but only the squad recurrence (how many captures by squad in the last ten days)
is not possible to have an XML like first but without names?
ty
ty
S! again KFS1
Would it be very easy to add cut-off / receiving supply -info for CPs? For example to cpstates.citys.xml .
We can of course figure if a CP is cut-off or not by ourselves, but I thought I ask you first before I start coding. :)
Thanks again,
Zeta
And another too :) : town/facility altitudes?
under, several axis factories have a ‘0′ rdp status which (if i understand it correctly) means that they don’t contribute to the current rdp cycle – is that intended or just a bug?
Pedro: Factories that are too damaged don’t produce RDP points, and neither to factories that are captured by the enemy.
Two things can cause a factory not to contribute:
. Enemy ownership,
. Destruction (”destroyed” visible state in-game)
In the case of the latter, they don’t start contributing again until they visually rebuild in-game: that makes a large scale raid on a single factory that destroys more effective than the same amount of ordnance spread across multiple factories without causing destruction.
I have a question regarding the deathmaps: Do they record all deaths (like a noob crashing his aircraft during takeoff) or only actual kills where a player kills another player?
Any idea when we might get this great service fully operational again?-)
S!
I need help with two things.
the first is how to read this unix_timestamp: at=”1238220430″ its been driving me nutz.
the second thing is im trying to create graphs like killban has on his site, there is nothing wrong with his and i think they are great but i want separate graphs for separate factories. after acouple days ive finally figured out how to convert the xml data into a form i need for the charts, but now i need to be able to separate the different factories from the factorylog.xml. i thought i could use the query function but i guess only the “limit” query works for this xml file.
how can i go about separating the factories?
thanks!
Erh, ‘at=”1238220430″‘ isn’t a Unix time, 1238220430 is a Unix time.
Nobody can answer your questions because you’ve said “I’m trying to do something and can’t”. Are you using Windows or Mac (Mac uses Unix times)? Are you using a programming language or doing this in notepad?
Link: Wikipedia definition of ‘Unix time’
Link: MSDN article on converting Unix Time to Windows time structures
Im using XP and am using a series of .vbs and .bat scripts
- .vbs to download the factorylog (for some reason it doesnt want to download the log when i put the URL with ?limit=135 at the end of it…)
- a .vbs that replaces all the fids to their factory names
- a .bat to seperate the different factoies
- a .vbs that changes the format so it shows correctly on the chart
im still having to figure out how to make the graphs show a specific period of time.
Well boys Ive done it! It can viewed here:
There are 4 different versions of the page, the 1st being the page with Maps and 1 Hour Graphs, the 2nd With just 1 Hour Graphs, the 3rd with Maps and 1 Day Graphs, and the 4th with 1 Day Graphs.
Let me know what yall think
Thanks for putting out info on Wiretap KFS1!
Sweet, Snipe, but Chrome, Spyware S&D, Spybot and MalwareBytes all detect “snipets.myvnc.com” as a malware host (although this seems to be because of myvnc.com rather than snipets specifically). The only way I could view your site was to bring up a virtual machine and disable the browser security inside it :(
8O *runs off to scan meh server!*
the .myvnc.com is from so i dont have to remember my IP every time i want to access my site… thats weird ive viewed the site with that link from 3 different computers using IE7 and Firefox, and even two more US Army computers and none of them said anything.
use this
having a personal server/website is almost not worth the headache :P all learning i guess
Any news on when Wiretap will be operational again?
S!
ive got a question for ya. Bell0 has a good program out that show your last 5 kills and last 5 killers on a G15 keyboard LCD. and thats pulling the data from the main page of a player, so it only updates when you complete your mission.
well i had an idea of using the “enemies” tab to pull the data from as the enemies tab updates as soon as you die/kill some one. i think i know of a way of doing this but im having one problem. the enemies tab cannot be sorted by date, it only sorts by number of kills on that person.
now my question is: is there a way to sort the enemies list? so that the most recent kills would be at the top of the list
sry to post here but its the only place i knew of
p.s. meh wiretap graphs are still kickin :D
thanks | http://kfsone.wordpress.com/2007/01/24/wwiiol-web-geeks-needed/ | crawl-002 | refinedweb | 9,174 | 69.82 |
Localization setup with babel-plugin-ttag and webpack (the hard way)
This post will describe hardcore but flexible setup with webpack and
babel-plugin-ttag (without
ttag-cli). We recommend to use simpler approach with
ttag-cli, but if you want more flexibility in your translation process - this post is for you.
This tutorial is based on Webpack 2. It should work in a similar way with webpack 3/4 wihout much changes
1. Initial setup1. Initial setup
1.1 Why should I care about dev and prod setup?1.1 Why should I care about dev and prod setup?
There are different requirements to development and production setups.
Requirements for the dev setup:
- Faster builds.
- Simple setup.
- Fast feedback.
Production setup:
- Smaller assets.
- Less work to load locale (faster locale load).
According to this requirements, ttag provides you options for making efficient production and development setups.
1.2 Application overview1.2 Application overview
For demonstration purposes, we will implement simple clock application. An example is available on JSFiddle.
All sources for this example are available
under the
examples directory of the
ttag repository.
1.3 Installation1.3 Installation
- First we need to create separate folder run
npm initand follow all installation instructions.
mkdir ttag-counter cd ttag-couter npm init npm install --save ttag && npm install --save-dev babel-plugin-ttag
- Also we need to install webpack and babel loader for webpack.
Tip: follow the installation instructions from Babel official documetntaion
npm install --save-dev babel-loader babel-core babel-preset-env webpack
1.4 Basic app setup1.4 Basic app setup
Now we are ready to make a basic setup for our application. It will consist of an
index.html and
app.js files.
Let's add
./dist directory and add
index.html there:
<html lang="en"> <head> <meta charset="UTF-8"> <title>Webpack with ttag demo</title> </head> <body> <div id="content"></div> <script src="./app.js"></script> </body> </html>
Nothing special, just some html boilerplate.
Let's add
app.js file also, that will contain our simple business logic:
import { ngettext, msgid, t } from 'ttag'; const content = document.getElementById('content'); const view = (hours, minutes, seconds) => { const hoursTxt = `${hours} hours`; const minutesTxt = `${minutes} minutes`; const secondsTxt = `${seconds} seconds`; return ` <h1>${ t`webpack with ttag localization demo` }</h1> <h2>${ t`Current time is` }</h2> <h3>${hoursTxt} ${minutesTxt} ${secondsTxt}</h3> ` }; setInterval(() => { const date = new Date(); content.innerHTML = view(date.getHours(), date.getMinutes(), date.getSeconds()); }, 1000);
This is simple program that will display the current time:
Let's make setup for webpack. Here is our
webpack.config.js:
module.exports = { entry: './app.js', output: { filename: './dist/app.js' }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader' } } ] } }
And now we can execute
webpack to build our
app.js file and open
index.html in a browser.
1.5 Wrapping strings with ttag functions and tags1.5 Wrapping strings with ttag functions and tags
Let's wrap our literals in
ngettext and
t:
import { ngettext, msgid, t } from 'ttag'; const view = (hours, minutes, seconds) => { const hoursTxt = ngettext(msgid`${hours} hour`, `${hours} hours`, hours); const minutesTxt = ngettext(msgid`${minutes} minute`, `${minutes} minutes`, minutes); const secondsTxt = ngettext(msgid`${seconds} second`, `${seconds} seconds`, seconds); return ` <h1>${ t`webpack with ttag localization demo` }</h1> <h2>${ t`Current time is` }</h2> <h3>${hoursTxt} ${minutesTxt} ${secondsTxt}</h3> ` };
Tip: Check both
ngettextfunction reference and
tfunction reference
Let's rebuild webpack and see what do we have in a browser:
You can notice that plural forms are working without any extra configuration (i.e.:
1 second is displayed properly).
This is because ttag uses English locale by default.
2. Extracting translations to the .pot file2. Extracting translations to the .pot file
Let's extract our translations to template file (
.pot). ttag will extract translations only if it has
extract.output` setting,
let's modify our webpack.config.js to be able to work in the extract mode.
module.exports = ({ extract } = {}) => { // webpack 2+ can accept env object const ttag = {}; if (extract) { // translations will be extracted to template.pot ttag.extract = { output: 'template.pot'} } return { entry: './app.js', output: { filename: './dist/app.js' }, module: { rules: [ { test: /\.(js|jsx)$/, use: { loader: 'babel-loader', options: {plugins: [['ttag', ttag]]} } } ] } } };
Let's extract all translated strings by executing
webpack --env.extract.
The resulting extracted
.pot file:
msgid "" msgstr "" "Content-Type: text/plain; charset=utf-8\n" "Plural-Forms: nplurals=2; plural=(n!=1);\n" #: app.js:5 msgid "${ hours } hour" msgid_plural "${ hours } hours" msgstr[0] "" msgstr[1] "" #: app.js:6 msgid "${ minutes } minute" msgid_plural "${ minutes } minutes" msgstr[0] "" msgstr[1] "" #: app.js:7 msgid "${ seconds } second" msgid_plural "${ seconds } seconds" msgstr[0] "" msgstr[1] "" #: app.js:10 msgid "webpack with ttag localization demo" msgstr "" #: app.js:11 msgid "Current time is" msgstr ""
3. Add a locale (
.po file)
Let's add Ukrainian locale (
uk). We can use
msginit tool for creation of
.po file with all appropriate to
uk
locale headers:
msginit -i template.pot -o uk.po -l uk
Tip: If you want to skip this, just copy and paste it from the example source.
Either if you generated the
uk.po from the
pot file or copied from the example source - the next step will be to
add translations to
uk.po. Translations can be added by translators (nontechnical persons) and developers.
It's up to your process.
Here are some translations:
#: app.js:5 msgid "${ hours } hour" msgid_plural "${ hours } hours" msgstr[0] "${ hours } година" msgstr[1] "${ hours } години" msgstr[2] "${ hours } годин" #: app.js:6 msgid "${ minutes } minute" msgid_plural "${ minutes } minutes" msgstr[0] "${ minutes } хвилина" msgstr[1] "${ minutes } хвилини" msgstr[2] "${ minutes } хвилин" #: app.js:7 msgid "${ seconds } second" msgid_plural "${ seconds } seconds" msgstr[0] "${ seconds } секунда" msgstr[1] "${ seconds } секунди" msgstr[2] "${ seconds } секунд" #: app.js:10 msgid "webpack with ttag localization demo" msgstr "Демо локалізації з ttag та webpack" #: app.js:11 msgid "Current time is" msgstr "Поточний час"
In the future you will add more string literals to your app, and you will need to update
.pofiles. we suggest you to use
msgmergefor that. Here is an example:
msgmerge uk.po template.pot -U
4. Localization with dev setup4. Localization with dev setup
As mentioned earlier, the requirements for the development setup are:
- Faster builds.
- Simple setup.
- Fast feedback loop (validation).
To be able to use our translation we need to load the
.po file somehow.
Let's use po-gettext-loader with json-loader
npm install --save-dev po-gettext-loader json-loader
Ok, we are ready to load our translations via loader, let's modify our webpack config:
const webpack = require('webpack'); module.exports = ({ extract } = {}) => { // webpack 2+ can accept env object // ... return { // ... module: { rules: [ // ... { test: /\.po$/, use: [ {loader: 'json-loader'} {loader: 'po-gettext-loader'} ] } ] }, plugins: [ new webpack.DefinePlugin( { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'debug') } ) ] } };
Please note some of the changes here:
- Use
json-loaderafter
po-gettext-loader, because we need our translations object to be used on the client-side.
- Added
DefinePluginto be able to split development and production logic inside the app.
Note: Webpack 4 has changed the way you deal with development and production setups, please take that into account when working with it.
After this step, we can simply require
uk.po file and apply
uk locale at the application startup.
Let's create a separate
localeSetup.js file:
import { addLocale, useLocale } from 'ttag'; if (process.env.NODE_ENV !== 'production') { const ukLocale = require('./uk.po'); addLocale('uk', ukLocale); useLocale('uk'); }
Notice that locale initialization logic is wrapped with the
ifcondition because we need that logic only during the development setup. In the production mode all assets will be already translated on a build step.
After that we need to
import localeSetup.js at the top of
app.js file:
import './localeSetup';
Note:
import './localeSetup'must be the first
importin your entry bundle, to setup locale before other exports evaluation.
As you know, ES6 exports are evaluated before module execution. So, to apply translations to exported values also, we need to make locale setup as soon as possible.
Let's build our app with
npm run build and you will see that all translations are applied.
And here is what we can see in the browser:
A few cool things here:
- Translations are working.
- You can run webpack in watch mode and it will watch for changes in
.pofiles and will rebuild app if some translation is added or changed.
- Validation is also working, just great!
I hope you have understood the main idea of how we can load locale in development mode. In the real app, you will don't know what locale is selected on a build step, so you may decide to place it somewhere in the initial app state or pass it through some global var, or you can use webpack code splitting features and load it asynchronously, it's up to your application requirements and design.
5. Localization with production setup5. Localization with production setup
The main requirement for production setup are:
- Smaller resulting assets.
- Less work on a client to load locale.
babel-plugin-ttag allows you to precompile all your translations in the resulting bundles in compile time.
It will strip all ttag tags and functions and place all translations in their places. Little pay for
that feature is that we should make a separate build for each locale. I think it's not a big trade off for
making your end user happier.
babel-pugin-ttag will apply translations from some locale if
resolve.translations
setting is present.
resolve.translations must be set to the path to the
.po file.
Note: we also should strip ttag tags and functions for the default locale. Default locale is resolved when
resolve.translationsis set with the
"default"value.
5.1 Making separate build for each locale5.1 Making separate build for each locale
Let's modify our webpack config in a way that it can configure ttag options to make an appropriate transformations for some locale.
module.exports = ({ extract, locale } = {}) => { const ttag = {}; if (locale) { // we should pass default for the default locale. ttag.resolve = { translations: locale !== 'default' ? `${locale}.po` : 'default' }; } // ... }
Let's also change the resulting output filename to be able to compare it with the previous versions:
output: { filename: locale ? `./dist/app_${locale}.js` : './dist/app.js' }
Let's build localized assets with commands
webpack --env.locale=uk && webpack --env.locale=default.
Tip: if you are still using webpack 1, you can use simple env vars instead of webpack env. For example:
LOCALE=uk webpack && LOCALE=default webpack.
To see that it works le'ts modify
src attribute in
index.html:
<script src="./app_default.js"></script>
and
<script src="./app_uk.js"></script>
This step is done manually just for the demo purposes, in the real world url will be modified by html-webpack-plugin or some backend code rendering the page.
5.1 Replacing ttag library with a mock5.1 Replacing ttag library with a mock
So, if we are placing all translations at a build time there is no need to include the original
ttag library in the resulting bundle. There is special mock for that case inside ttag lib -
ttag/dist/mock.
Let's add a webpack alias for that:
resolve: { alias: { 'ttag': locale ? 'ttag/dist/mock' : 'ttag' } }
This will minimize the resulting bundle size. Don't forget to use
NODE_ENV=production to avoid translations to be
bundled in the resulting assets.
6. Results comparison6. Results comparison
Let's build all variants and compare the output size
webpack && NODE_ENV=production webpack --env.locale=uk && NODE_ENV=production webpack --env.locale=default
The resulting files inside
./dist:
17K app.js 5,5K app_default.js 6,1K app_uk.js
Minified versions:
6.9K app.js 1.8K app_default.js 1.9K app_uk.js
As you can see production setup reduced the resulting bundle size. | https://ttag.js.org/blog/2018/09/05/hardcore-webpack-setup.html | CC-MAIN-2019-09 | refinedweb | 1,966 | 51.44 |
Hello all,
I have a question that is just a matter of opinion. I would like to see people explain their point of view on the subject: should one use the keyword "using", or should one preface a namespace every time something in it is referenced? And if you're in favor of using using, do you use "using namespace" or just the referenced item, eg. "using std::cout"?
Myself, I don't use "using" in any case (with the exception of programming contests, where speed is more important than good code). I find that it entirely kills the entire use of namespaces. I barely use "using", and yet the few times I did use it I ran into trouble, the only one I can remember now was "int map[25][25];". And somehow I find it tells the reader of the code a lot more on the object to specify, each time, where this object is located.
Honestly, I'm quite surprised how many people use using, and the fact that that keyword even exists.
So, what are your guys' thoughts? | https://cboard.cprogramming.com/cplusplus-programming/109157-cplusplus-ab-using.html | CC-MAIN-2017-26 | refinedweb | 182 | 76.96 |
Someone is trying to talk me into switching from PHP to Python.
This may sound funny, but one of the things that concerns me is how the formatting works in Python.
Everyone seems to think Python is much easier to read, due to things like eliminating curly braces { }.
This point worries me!
When I am working in NetBeans on my tiny MacBook monitor, and I have 300 lines of code nested inside an IF-THEN-ELSE, I want my curly brackets to see how things are grouped, damn it!! :mad:
Can anyone here explain how the visual formatting/hints would occur in NetBeans (or a similar IDE) in such a scenario??
Sincerely,
Debbie
Simple, take your block of code, create a python file, paste it, remove the curly braces
Remember python uses whitespace to determine which block the code is associated with.
First of all, I don't use Python, so telling me to create file is pointless.
Secondly, I think you missed the entire point of my OP...
It is a VERY IMPORTANT feature to me that my IDE helps me see where a block of code begins and end.
If have a IF-THEN-ELSE, where the THEN portion is 3 pages long, then I can't see it all on one MacBook screen, and it helps IMMENSELY to click on the curly brace and have the IDE help me figure out how far down to scroll to find the ELSE portion.
(It's also nice to have code collapsing/expanding too.)
See example below...
I was hoping someone here codes in Python uses NetBeans - or something very similar - and can tell me how the IDE would know where the end of a block of code is like in the screen-shot above.
Well python forces proper indention, it's actually part of the syntax. So blocks of code will look the same in the IDE, just without the brackets.
Just a random picture I found of some python code in Netbeans. You can see on the left it has the option to collapse it, so it knows where the code block starts and ends.
Also, if you have such large pieces of code you should consider moving them into functions, classes, or new files. This helps readability. Personally if I start hitting 10 or so lines in an IF statement, I start thinking of ways to make easier to read. Sometimes it's unavoidable, but most of the time it's not. This goes for any language I use.
That section on the left the folding indicators combined with the blue grouping lines would also exist in your python code. There would be no yellow highlighting of the curly braces, because they don't exist in python.
My point was, you have the tool at your disposal. You simply could create a myfile.py file, paste your block and see the formatting.
Screenshots at (granted, they don't indicate folding options at the if statements, but I thought certainly that was available -- so maybe the screenshots are a prior version)
How does it do that?
(That is somewhat scary if Python of my IDE start telling me how to format things?! Um, my code is about as "pretty" as they come!!) :rolleyes:
Well that sort of helps, but I wish I had a better idea how it would handle a really long If-Then-Else.
Well, maybe if I start learning OOP and learn how to break down my code, I can achieve smaller blocks of code, and this thread will become not applicable!
However, even if I learn and master things like OOP and MVC, any serious system will have blocks of really long and complicated code...
Well, if you have some structure like an IF-THEN-ELSE or a LOOP, how would NetBeans and Python help you figure out where the beginning and end are at?
Sorry, that went over my head.
I thought to use Python I'd have to install software and do a whole bunch of complicated stuff...
Spacing. You have to indent that code 4 spaces from the indentation of the if statement.
def mymethodname
if blah blah blah:
if
else:
else
To execute it, yes, but just to see how it is formatted, no. Netbeans should have that built in.
Yeah, I agree it's weird. But it doesn't seem that bad. I'm actually still learning Python myself so I'm no authority on writing it, I'm just kinda using it here and there to get familiarized. cpradio seems to be much more familiar with it.
But if you'd like to learn it I do suggest the codeacademy course, it's interactive.
Yes, Code Academy has an excellent course over Python, but if I recall correctly it is better to take the Ruby one first, as there are things that you go over in the Ruby one that will give you "ah ha" moments in the python one (especially the latter tutorials, that don't guide you very much).
Ruby did a lot of hand holding, Python threw you in and said "learn to swim!"
I don't do a lot of python, but I picked it up a few years ago when I needed to write plugins for kexi (an access database replacement for Linux).
[ot]
Why are they trying to do that? And why python?[/ot]
Nothing personal, but it seems you don't use an IDE?
I indent and space the hell out of my code now, but that isn't what my original question was about.
Spacing and indenting don't help you to easily see where the end of Do-While, of If-Then-Else, or whatever is.
Code highlighting and hinting do.
I don't care if Python doesn't use curly brackets, but I am hoping it - or NetBeans - would make it easy for me to see what is logically grouped together.
And as far as trying it out... Sure, I would do that, but since I don't know Python code/syntax, it seems sort of hard to do.
Because PHP is considered amateurish when it comes to writing enterprise code and doing serious OOP.
And now that my website is nearly done - and looks very nice might I add! - I am thinking of taking the next big leap, and getting into some hard-core programming.
A lot of people would say to go with C++ or Java, but I think there are some obvious pitfalls there.
And at least one person I respect pointed out that Python is older than Java, a good choice to get your feet wet in the OOP world, and is much, much easier to learn.
In my free time I am just checking things out and trying to come to a conclusion later this summer...
(I have always dreamed of being a Java Goddess, but considering how every time I try and learn Java and OOP I fail, maybe that is a sign I need to back off and try something easier.)
As far as the whole PHP-war I likely just started would go, HEY, if I didn't like PHP, I wouldn't have spent the lat 4 years writing my website in it.
And, yeah, I know that it was used to build FaceBook and WikiPedia and lots of other major sites.
But for those that want a strongly-typed language, and coding rigour, and a true object-oriented language, PHP will never be the choice!!!
PHP has been VERY good to me, but I think I am ready to step up to the next level, and maybe Python would be a good stepping-stone? :-/
Okay, now I'm starting to get a bit ticked off, as I feel you are not listening to what I'm stating or you just blatantly want a different question answered that was never asked...
I use several IDEs. From Visual Studio (for .NET work) to phpStorm and many in between. I write in PHP, .NET (C#, VB.NET specifically), Ruby, Python, and Bash frequently. I'm very familiar with IDEs and if you are too, then you'd know that if NetBeans supports Python (and it does) that it would have support for highlighting, syntax, folding of method declarations (and likely if blocks), code hinting, etc. ()
I feel like I've answered your question and if you really really want to know how netbeans handles python, TRY IT! Find a python script, open it in NetBeans and see how it looks and feels. Sickbeard is a well-known application written in python, feel free to download it and open one of its files within NetBeans.
I don't know how much better I can explain it to you other than, NetBeans supports Python, supports its indentation syntax (because it has to), and therefore can and would give you a similar experience to what you have with PHP and NetBeans.
I'm not sure why you are even considering moving to a language you don't understand/know. That is illogical. PHP's declaration of being amateurish is unfounded at best and primarily based on the number of users that use PHP poorly. No offense, but I can find just as many users that use Python poorly, .NET related languages poorly, etc. Does that make them amateurish? No. It simply means there are crappy developers out there who don't bother to learn best practices or bother to think about how they code something.
Personally, anyone who claims one language is superior over another loses a lot of respect from me as a developer. No one language is perfect for everything. Pick the language for the given job/requirements you have. Don't try to fit the language into the job.
Nothing screams enterprise like Java. That doesn't mean Java is the way to go though. Mostly I feel that enterprise is overrated. It's usually so much wrapping and bloat going on you can't see the forest for the trees.Regarding PHP and OOP, it used to be quite bad in PHP 4, but in PHP 5, especially since 5.3, it's quite good! There are a lot of reasons not to like PHP, but "not serious OOP" isn't one of them.Besides, you've said on more than one occasion that you're allergic to OOP, so this argument should convince you least of all
Aw, you're still in that phase where you think a website can be "done". That's cute
Yes, but C++ is older than Python, so ...
That's pretty obvious, since PHP isn't strongly typed. And even python is, it's also dynamically types, which has it's own pitfalls.
Are you considering other languages as well? I've been playing with Google Go myself, and I have to say I really like it. It's strongly and statically typed, and extremely fast!
Amen!
:rofl: Mine has been in the works since 2001 and even today, it isn't finished :lol:
I wasn't trying to tick anyone off. I just felt you missed my original question.
Since I have NetBeans for PHP installed, I can't do your test.
Maybe later this summer I can install NetBeans for Python and find/write some code and give it a good test.
Because C, C++, Java, and Python are more serious, industrial-strength programming languages. PLUS, C++, Java, and Python support real object-oriented programming.
That's why.
Would you learn sailing in a sailboat or a bathtub? (Unless you're from Arkansas!)
PHP offer pseduo support for OOP. That is a fact, not opinion. I never said anything about PHP's declarations...
Different topic.
All languages have crappy developers.
But C++ and Java are true OO languages. PHP isn't.
That may not matter to the quality of the end app, but for someone who wants to learn proper OOP, it does matter!
Then you are too attached to certain languages.
I used to hear the same drivel out of people proclaiming that MS Access was a "true" RDMS, and that VBA was a "true" programming language... :rolleyes:
PHP is one of the best languages for the web, but it isn't strictly typed language, and it's support for true OOP is questionable.
Exactly.
So why are you implying that PHP is on the same level as C++ and Java when it comes to enterprise development and OOP?
I have.
I am trying to do that, and it may be Python...
So, cpradio... How do you REALLY feel??
I never said it was either. (Isn't this a Python forum...)
Which is why so many modern developers like Ruby On Rails, Python, etc.
If you want to really learn OOP, why do it in PHP?
I think it is time for me to step out of my conform zone...
For v2.0
One of my final wishes before death is to conquer OOP.
I'm not allergic to it, I just know it is my eternal Achilles Heal.
v2.0 is almost done. Nothing "cute" or "dreamt" there.
Obviously my site will continue to evolve.
So nothing.
My point was Python is not some new, fad.
From my limited research, and one person I respect, I think Python is a stronger language when it comes to structure and OOP.
Yes, I am casually researching how to take my development skills to the next level.
When I learn OOP, I want to learn it with a language that really takes me to the next level. (I highly doubt PHP can do that.)
If I could conquer Python or Java or C++ or some other industrial-strength OO language, I think it would do worlds of good for me and my development skills.
I really like PHP, but I have always found it to be a sloppy language.
I want to get away from writing everything in one script that is my 500 or 1,000 or even 2,000 lines of code.
To accomplish this, I think I need 3 things:
1.) Learn MVC or something like it
2.) Learn OOA&D
3.) Program in a serious OO language and try to start writing code that you could get paid to do, that an entire development team could work with, and code that could be used by Google, Twitter, Amazon.com or Wall Street.
BTW, another reason for my "snobbiness", is that I hope to write my own apps for the Apple Store, and that means needing to know Objective-C, and that means I need a hell of a lot more competency than writing HTML, CSS, and PHP all in one barf script!!!
C++ is not a good language to learn. It's for low level systems programming and optimization, but even there it's losing ground to other languages that are generally easier to write, like C or Java. Pure [CGI programming has been dead for quite a few years. When you see on lists, [URL=""]like wiki](), where sites use C++ it's mostly for the backend processes and not the web processes themselves. For instance, at my job the C++ runs some of the legacy CGI stuff built in the 90's that unfortunately is still floating around in a few places and it also does the majority of the data crunching where it's used to process terabytes of data. We're actually moving most of these processes into pure Java so that they are easier to maintain, but it's not high priority.
You might be referring to C#, which has been the core language used in ASP.Net programming for the last 5 or 6 years. It's actually a really great language and the .Net web stack is very easy to learn, but it's a Microsoft product. C# and Java are also very similar. C# was created as Microsoft's answer to Java and was made to be similar. They have gone different ways over the years, but still syntactically very similar.
ASP.Net (C#) and Java are the reigning kings of Enterprise Web Development.
Sadly, the entry bar for Java web development is set pretty high. I don't mean that to be pretentious or elitist, I mean it as a bad thing. It shouldn't be so complicated, but it is and the resources for learning are sparse.
However if you're really interested in it, the Play Framework makes it a lot easier. But, you should have a pretty good understanding of basic Java programming first. There are tons of resources for Intro to Java programming. Lots of highly rated ones on Udemy.com. If you want a framework that's more enterprisey and used in more places, then Struts2 or Spring MVC is what you should be looking in to. They are way more complicated than they should be and can be difficult to learn for even seasoned Java developers.
If you want to learn MVC, there are plenty of MVC Frameworks for PHP. There is also a really great tutorial for how to build your own MVC in PHP. I've personally done the entire tutorial series and it's one of the best tutorials I've ever come across in any language. It would have really helped me learn MVC initially if I had went through this first. (I learned MVC with ASP.Net)
11 videos and you should have a good understanding of core MVC concepts after about Video 6, though I do suggest doing all of them. This series will also give you a good feel for OOP in PHP, the framework you create is fully object oriented.
I am not a fan of PHP, but it does have it's place. Since you're already pretty familiar with PHP, I would suggest this be the route you explore before jumping into a new language. This way you won't need to learn new programming paradigms on top of learning a new syntax and code structure.
Programming is programming. Syntax is syntax. Knowing how to program is the most important thing, concepts can be transferred between languages and syntaxes. Once you learn to program in a language it's easier to pick up new ones. That's why you see developers nonchalantly naming off 5 or 6 or 10 languages they know.
Well, 2 weeks ago that was true. Today and for all foreseeable days in the future, you should learn Swift. It was the major keynote at the Apple World Wide Developers Conference last week. They have pumped a lot of time and money into it being the replacement for Objective-C, which has been out since the 80's. From what I understand is that it integrates seamlessly with Objective-C, so if you're set on learning Objective-C then it's not a waste. Swift is aimed at being easier to learn and use.
next page → | http://community.sitepoint.com/t/viewing-python-in-ide/44674 | CC-MAIN-2014-41 | refinedweb | 3,176 | 80.82 |
Feedback on Bigdaddy data center
About a month ago I alluded to a data center called “Bigdaddy” that people could check out as a preview. We’re ready to collect feedback on the Bigdaddy data center now. Let’s start with some Q&A.
Q: Why are you giving this a name? Isn’t that normally the privilege of Brett Tabke and the moderators at WebmasterWorld (WMW)?
A: Brett and WMW normally name updates. But this is neither an update nor a data refresh; this is new infrastructure. It should be much more subtle/gentle than an update.
Q: Why is it called Bigdaddy?
A: That’s a good story. Bigdaddy got its name right here:
At Pubcon, there was an hour-long Q&A session one morning. After the session was over, a bunch of us skipped the next session of talks to talk more in the lunch room (that’s me in the blue shirt). I knew we had a test data center that would need feedback, so I asked for suggested names. One of the webmasters to my right (JeffM) suggested “Bigdaddy.” Bigdaddy is his nickname because that’s what Jeff’s kids call him. So I said I’d use that the next time we needed a name for feedback.
Q: Why did you wait so long to ask for feedback?
A: There were a couple reasons. First, I knew that Bigdaddy wouldn’t go live before the holidays were over. Second, the team working on this data center wasn’t showing it 100% of the time; at night, they’d take it out of our data center rotation to tinker with it. That would have been a recipe for confusion. Now we’re past the holidays and the Bigdaddy data center is live 100% of the time. In fact, Bigdaddy is now visible at two data centers: 66.249.93.104 and 64.233.179.
Q: What’s new and different in Bigdaddy?
A: It has some new infrastructure, not just better algorithms or different data. Most of the changes are under the hood, enough so that an average user might not even notice any difference in this iteration.
Q: I noticed some ranking changes across all data centers. Was that Bigdaddy?
A: Probably not. There was a completely unrelated data refresh that went live at every data center on December 27th. Bigdaddy is only live at 66.249.93.104 and 64.233.179.104 right now.
Q: Is there specific types of feedback that you want?
A:).
Q: What else can you tell me about Bigdaddy?
A: In my opinion, this data center improves in several of the ways that you’d measure a search engine. But for now, the main feedback we’re looking for is just general quality and canonicalization.
Q: Will this datacenter make me coffee? Is it the solution to all possible issues ever?
A: No. No data center will make 100% of people happy. For every url that moves into the top 10, another url moves out. And the changes on Bigdaddy are relatively subtle (less ranking changes and more infrastructure changes). Most of the changes are under the hood, and this infrastructure prepares the framework for future improvements throughout the year. If you see a webspam or quality issue, let us know so that we can work on it.
Let’s finish off with a couple more Q&A’s.
Q: I see something weird on the Bigdaddy data center. Should I leave a comment on your blog?
A: Please don’t; that’s not the best place to leave it.
I would leave the feedback either in a spam report (for webspam) or the “dissatisfied” form for any other feedback. The only Google person reading the comments on this blog will be me, so your feedback will get the best bang-for-the-buck if you put it into one of those two forms.
Q: Are you sure you don’t want me to just drop a quick comment about my problem here? Right now?
A: I’m about blogged out for the day, and there are better places to discuss this stuff (WebmasterWorld, Search Engine Watch Forums, etc.). The best way to get people to process your feedback is to use the spam report form or the dissatisfied link, make sure that you include the keyword “bigdaddy” and try to be as specific and clear as you can.
Okay, now let’s get to the meat of this post: how to give us feedback on Bigdaddy. I’d be delighted to get webspam feedback, but I’m most interested in hearing feedback about canonicalization, redirects, duplicate urls, www vs. non-www, and similar issues. Before you send in a report, please read my previous posts on url canonicalization, the inurl operator, and 302 redirects. Now here’s where to send feedback:
Reporting spam in the bigdaddy data center
I definitely want to hear about webspam that you see in Google. The best place to do that is to go to . In the “Additional details:” section, I would use the keyword “bigdaddy” in your report.
Reporting other quality issues in Google’s index
Do the search that you’re interested in on 66.249.93.104 or 64.233.179.104, then click the “Dissatisfied? Help us improve” link at the bottom right of the page. Again, fill in details and use the keyword bigdaddy so that folks at Google can separate out feedback specifically about this data center.
If I see feedback reports that aren’t helpful, I’ll try to provide suggestions for how to give solid reports that we can use.
Update: 66.249.93.104 is the preferred data center to hit. I edited the post to make 66.249.93.104 the first IP address listed.
Update2: Made the WMW and SEW links more specific/correct.
Lee Said,
January 4, 2006 @ 12:50 pm
Hi Matt
Thanks for all the information this evening - all very useful!
Just a quick question - what was going on a couple of days back? Many people at WMW were seeing the test DC results on their default Google - including myself.
Anh Said,
January 4, 2006 @ 1:03 pm
Your link to WMW isn’t working. Is it down?
Barry Schwartz Said,
January 4, 2006 @ 1:04 pm
I remember that, you didnt get the angle where goodroi and I were laughing at you.
Busy day Matt - lots of awesome information. Really nice to see.
Supplemental Challenged Said,
January 4, 2006 @ 1:05 pm
“I’m most interested in hearing feedback about canonicalization, redirects, duplicate urls, www vs. non-www, and similar issues”
No change whatsoever, and sorry, but reordering the site: search doesn’t count. Duplicates still exist. Redirects continue to be ignored. Nonexistent URLs continue to be shown.
Where’s the beef?
Jeff S Said,
January 4, 2006 @ 1:08 pm
Thanks matt very useful info, i have one quesiton right now i see very big differences when doing a site: command on the current and the test datacenter and also see different pages indexed in 1 and not the other, will data be combined or is this how its going to be?
Tim Said,
January 4, 2006 @ 1:14 pm
Matt,
If there is any chance you could elaborate a little bit about the December 27th “data refresh” I would very much appreciate it.
- Tim
Adam Senour Said,
January 4, 2006 @ 1:24 pm
They seem to be two different sets of results. Which update is out of rotation?
(looks like the new one…over 50,000,000 results)
(looks like the old one…19,200,000 results)
Personally, even though I’m not ranked as highly in the 64.233.179.104 one, I prefer it simply because none of my clients lost and one of my clients got back some significant positioning. If I’m the only one not ranking first-page, quite frankly I don’t care as long as I’m not buried.
One other thing: at least from an upper/lowercase standpoint, there’s still an issue with URLs. I even coded a 301 redirect in the case of one of my clients to attempt to help remove some of the duplication from the index.
If you look at #7 and #9, they’re actually the same URL but one is capitalized using the standard rules for such whereas the other is lowercase. They’re the same URL, and in the case of the upper/lowercase one, there’s now a 301 redirect coded specifically to take you to the lowercase URL.
I don’t know if this is significant, but I used ASP to create the following:
Whereas the Cat_URL represents the absolute lowercase version of the URL (i.e. Low_Dead_Page).
Is this not something big G recognizes? Or am I redirecting too quickly?
I’m willing to fix it if it will help. But I’m not sure what else I could do with that code snippet.
Dirson Said,
January 4, 2006 @ 1:39 pm
Feedback about searches in other languages (e.g. Spanish) are welcome?
Kentucky Redneck Said,
January 4, 2006 @ 1:50 pm
Matt
The new datacenter results looks great to me
cant you just go ahead and flip that big google switch and turn it on…. I’ll send you a Ale8
Robin Kay Said,
January 4, 2006 @ 1:56 pm
Just wondering if this is part of a canonicalization problem. On big daddy our index page is always in the 2nd position when doing a site: search, above it in number one position is usually a variety of recently crawled pages.
Other than the above concern, I think it has solved a lot of the canonicalization problems we seem to have had since last Feb.
Any insights on possible future pagerank you can give me or other webmasters who lost pagerank due to the canonicalization problems last Feb. would be greatly appreciated. Basically just give us a heads up if we may soon get our old pagerank back or if we are starting over. Either way it is just good to know where we stand.
Thanks for your awesome post it will help webmasters greatly and also thank you google for addressing these redirect and canonicalization problems.
claus Said,
January 4, 2006 @ 2:00 pm
Good stuff, those posts. Wonderful
And the “Bigdaddy” testbed is interesting too, especially with the Braille Google logo - makes it look even more special *LOL*
Opotamus Said,
January 4, 2006 @ 2:02 pm
“Q: Will this datacenter make me coffee? Is it the solution to all possible issues ever?”
Please email me when you can answer yes to both of these questions.
Ilya Said,
January 4, 2006 @ 2:11 pm
You gave 2 datacenter IPs. Can you explain why the result set seem to be different between them?
Ugo Said,
January 4, 2006 @ 2:19 pm
Hello Matt,
I see different results (from France) between 64.233.179.104 and 66.249.93.104.
The first one seems to be the actual with slight changes, the second one is radically different and I see REALLY less spam on it.
stuntdubl Said,
January 4, 2006 @ 2:30 pm
Hmmm…I wondered why there was no one in our “link buying session” after your coffee talk (where you just told everyone not to buy links)
Great piece of work, can tell you’ve been working quite hard on this one. Congrats.
Howard Said,
January 4, 2006 @ 2:42 pm
Should 64.233.179.104 and 66.249.93.104 show the same results?
rob Said,
January 4, 2006 @ 2:45 pm
Did you guys sit around and shout ‘whooooooooose your daaaady’ at any point?
Did any women give you strange sideways glances?
Jon Wright Said,
January 4, 2006 @ 2:49 pm
Wahey!!! My first “bigdaddy” report is on its way
I’ll look on with interest
Matt Said,
January 4, 2006 @ 3:09 pm
Lee, the Bigdaddy data centers can be (I believe) in the regular rotation. So at times we may send part of traffic to those data centers.
Mmm. Ale8. Mmm.
stuntdubl, all part of my cunning plan to pull people towards the white.
rob, that never even occurred to me. But now I’m feeling an uncontrollable desire..
rob Said,
January 4, 2006 @ 3:21 pm
>But now I’m feeling an uncontrollable desire..
LOL, u go dude, trust me, said loud, in the right places, its quite invigorating!
Interesting index too. Um..just need to figure out why my aff sites on page 3 + for all queries…
Adam Senour Said,
January 4, 2006 @ 3:22 pm
God I’m glad I don’t work there. The last time I heard that yelled was in Catholic school and I was 12 and…never mind.
Matt Said,
January 4, 2006 @ 3:29 pm
Dirson, yes absolutely we’ll take feedback in Spanish or other languages. The “Dissatisfied?” link may only show up on google.com, but you can do the search on google.com, click the link, and then say “this is feedback for a Spanish search. Here’s the url. …”
Search Engines Web, most of the changes is new infrastructure. Then there’s a few new algorithms to handle the underlying changes. But there shouldn’t be much algo changes as far as spam, relevance, ranking, etc.
Tim, just the normal mode of automatically refreshing algorithms with newer data. We wanted to wait till after holidays so that there wouldn’t be too many changes during the shopping season, so the data refresh may have been a little larger than a typical refresh. Sorry I don’t have much more to offer than that.
Pat Said,
January 4, 2006 @ 3:41 pm
Hi Matt,
I’m replying to your call for feedback on bigdaddy.
My site was severly dropped in the SERPS last September 22, for what I assume was either a duplicate content penalty and/or a Canonicalization issue.
First on the canonicalization issue. My site is
and on specific term searches such as
site:greennature.com mushrooms
The results first turn up all the “www” versions of the pages on my site. All of these pages are marked as supplemental.
I have a 301 redirect to the non “www” version of my site for all 10,000 pages. So, I assume that when the vast majority of my searches turn up “www” supplemental pages first in the results, Google has a Canonicalization problem with my site.
With respect to duplicate content, Google has my site listed at 74,000 some pages and I only have 10,000 pages. Somewhere along the line, Google picked up many duplicate copies of my pages and then gave me a duplicate content penalty.
In November I completely changed the CMS system I was using and updated my site. All of the old pages that were duplicates are now non-existant and return either a 404 or 410 code in the headers. I’ve checked this multiple times. Google has since spidered my site at least three complete times and still the problems are not resolved.
I have tried very hard to build a solid content site, enjoyed by the public. I’ve also tried very hard to stick to the Google guidelines.
If you look at my site, you will see that I use no spam or tricky SEO tactics.
Please, please, please Google, can you help me fix this problem?
Sincerely,
Pat Michaels
Publisher, Editor, Webmaster
Mike Said,
January 4, 2006 @ 3:49 pm
Sometimes I wish I had a better idea what google considers webspam. I know that there is a link that gives some definitions, but there is an option for other. Could you shed some light on what other may mean? Or maybe give me a link to what you would consider to be close to other?
Thanks for the great info Matt
alberto666 Said,
January 4, 2006 @ 3:52 pm
I’ve still seen some results as:
Both at time, in the same search.
It may be still improved.
AngelC Said,
January 4, 2006 @ 4:11 pm
This new datacenter have more images?
Philipp Lenssen Said,
January 4, 2006 @ 4:27 pm
It’s interesting to see how Google (well, you) now actively seeks a conversation about results *before* letting them loose on the world. Matt, I’d be interested to know how many feedback reports you get (either by spam reports or the dissatisfied link) and whether or not you’re able to read all of them.
benj Said,
January 4, 2006 @ 4:40 pm
OK, this one may be a little long…. bear with me….
Say I got engaged on New Years eve (yeah, Big Daddy finally proposed… OK, he didn’t, and if he had, my wife would have beaten him up!) and I want a cool wedding, not in the US, but some wonderful beach affair on distant shores…
I head off to Google to start my research… keep it simple, I think, I’ll search for “beach wedding” (without the quotes of course, I’m not a search marketer or anything….
Result #1: A wedding Favour store. Hmm… I haven’t planned my wedding yet, why is this relevant? We’ll give it a relevancy score of 4/10 (it at least targets favours with a beach theme)
Result #2: OK, an article on beach weddings - cool. Oh, there’s nothing else on the entire site about beach weddings. Score: Page: 5/10 (not a whole lot of use), site in general: 1/10
Result 3: A wedding planner in Hawaii, this is good, though we’ve decided against Hawaii, 10/10 for relevance though!
Result 4: Another Hawaii wedding planner, OK, relevant, so 10/10, but surely there must be some other places out there… lets move on…
Result 5: A possible… another article on beach weddings… but only one, again… out of the entire site, so back to 5/10 for that one (1/10 for the site as a whole)
Result #6: Beach wedding dress page on a pay-for-page site. OK, I’ll be needing one of those, although there’s nothing else here to help me with my plans. 5/10
Result 7: Another beach wedding article. This one part of an article farm generating adsense revenue. There are also articles on monkeys, blankets, bluetooth and Croatian Music, though the site is a children’s portal. A children’s portal for children in India. Article relavancy: 2/10 (it has absolutely no substance) Site relavancy: 0/10
Result 8: At last. A private island in Fijii, offering weddings. If only I had the money! relevance: 10/10
Result 9: An e-store selling Hawaaiaiaian wedding clothes - yup, that’s good, not brilliant, but good. We’ll give it a 6/10 relating to the search term.
Result 9: A page in a pay-for-listing site that is simply a list of links to hundreds of wedding related things in California. Not beach wedding ‘things’, though a tiny percentage are, but just ‘things’. Google’s making me work hard here, searching a page of links for something relevant, so only 4/10 here.
So in the top 10 results. the ones Google thinks are the best there are for that search, the average visitor would find 4 that are of any use.
4/10? Is this the result of months of tweaking, tuning, honing?
Oh dear.
Peter (Brane) Said,
January 4, 2006 @ 4:46 pm
Matt,
Some sites have a hard time getting indexed but on the test center they´re indexed just fine. Is there a slow down on indexing on the “old” datacenters or is this just a coincedence?
I like the results on the biddaddy center. Seems to me that page content and link quantity use to determine rankings is more balanced now (meaning before it was a bit too much links and not enough page content).
Peter
Michael Briggs Said,
January 4, 2006 @ 5:06 pm
TY for the info and happy new year. From the way you are talking about this update it sounds as if rather than having an ‘update’ Google is moving to a system of continuous updating, from the 1 to 2 month update period mentioned. So that a server comes into play when updated and out of play when updating I guess this is so that the results are consistent as possible over the Google network. Sounds Good
sid Said,
January 4, 2006 @ 5:07 pm
hi matt,
thank you for the info! one question: what would be the reason that one would not rank for its own UNIQUE domain name? the index page of this site is PR6 and still does not rank like it used to before Sep 22. the top results are the sites that mention this site. any ideas?
thank you, sid
Adam Senour Said,
January 4, 2006 @ 5:08 pm
Sid,
What’s the site?
Matt Said,
January 4, 2006 @ 5:12 pm
sid, how are your backlinks? Are they strong (i.e. editorially chosen, given for merit)? If you backlinks are less strong (link exchanges, paid links), that can be a factor.
Peter, the results on the Bigdaddy data center seem a little more fresh to me too. I don’t think it’s because the old infrastructure has had a slow-down.
T.J. Said,
January 4, 2006 @ 5:29 pm
Matt,
You say the datacenters are
66.249.93.104
64.233.179.104
I noticed the changes on January 2nd, but the 2 datacenters that
appeared to be sowing the results then were
64.233.179.104
64.233.179.99
Was 64.233.179.99 anything to do with it?
Happy with Big Daddy Said,
January 4, 2006 @ 5:36 pm
This is the best change I have ever seen from google. Canonical issues and duplicate issues have been completely and totally fixed.
sid Said,
January 4, 2006 @ 6:04 pm
hi matt,
thank you for your reply. I hardly look at my backlinks, but there seems to be quite many. lots of scrapers take my content and some links come from there as well.
coluld this be due scrapers taking my entire pages and Google can not tell who the owner is? this seems to be the case as the scrapers rank higher than I do on my content and so do proxy sites that Google has been indexing.
any comments would be of help.
thank you, sid
Byron Said,
January 4, 2006 @ 6:33 pm
“Big Daddy”, of course, is a famous character out of Tenessee Williams’ “Cat on a Hot Tin Roof”. I feel like having a “Bouron” right now.
Big Daddy Said,
January 4, 2006 @ 8:20 pm
Hi Matt,
Allot of great information here.
Thanks again for sharing and being so patient at Pubcom!! I know all about patience raising 7 children.
Have a great 2006!!
aloha,
Big Daddy
Matt Said,
January 4, 2006 @ 8:54 pm
T.J., I’m not aware of anything special going on at those data centers. I’m pretty sure it would be unrelated to Bigdaddy, at least.
sid, I’d look less for scrapers and more for any other types of links gathered by trading, selling, automatic means–stuff like that. That’s just my guess.
Jeff/Big Daddy! Great to have the original Big Daddy in the house!
Tell your kids that you have a data center named after you.
Adam Senour Said,
January 4, 2006 @ 8:54 pm
I think the next update should be named “WTF”.
Why?
Because every time there’s an update, everyone complains about WTF is going on with Google.
(I’ve got nothin’.)
Ledfish Said,
January 4, 2006 @ 10:11 pm
Matt
I’m not seeing a good handling of internal duplicate content on the bigdaddy servers. What I mean is if a site has an old page that has been replaced by a new one almost a year ago, and the old url has been giving a 404. The old page is still in the index(albeit supplemental) with a cache from almost a year ago when it was a current page. In other word, the bigdaddy servers have some cached pages that are as old a a year ago, pages that were not even in the regular serps as recent as two weeks ago.
I know this because we have had a problem for almost 10 months with our internal category pages not ranking like they use to…..we have been suspecting that we are having a duplicate content issue so we have been chasing accidently duplicate content for the last 6 months (spending almost 15 hours per week on it). So we know what is in the index and know we are finding pages on the bigdaddy servers that have been 404′d for almost a year.
Arggg, now I got about 30 more pages I need to try and kill from the index. I feel like a hamster on the treadmill.
Ledfish Said,
January 4, 2006 @ 10:21 pm
PAT fron greennature.com
Wish I had a way to contact you, we both seem to be trying to over come the same internal duplicate content problem or so we assume.
Matt, could internal duplicate content be causing a ranking loss on interior pages. I have internal pages that have good PR, good quality links, but it seems like whatever is done to help them improve for relevant searches, nothing happens. BTW, the keyword are not all that competitve, many less than 500K
Jan Said,
January 4, 2006 @ 10:32 pm
Matt,
Thanks for posting that picture! I could see myself and a friend, Lane, over in the left hand corner, just as plain as seeing an ant on the ground from a moving car…haha.
We sure did enjoy that whole seminar…but the private time with you was worth the whole thing! Thanks to Brett Tabke for such an outstanding job, and you for your patience.
I told everyone it looked like Jesus being followed around by the disciples…:-) No comments from the bible thumpers, please…it’s just a joke!
Thanks again, Matt
Jan
Myrtle Beach
Lars Said,
January 5, 2006 @ 2:56 am
Sid, I have the exact same problem. I cannot believe why backlinks would cause something like that. I cannot control who links to my site or should I start emailing webmasters and asking them to remove links? I’ve never been hunting for links, just focusing on on-site factors.
I’d also like a quick comment on the December 27th change. The effects are similar to September 22nd - suddenly a well ranking site is nowhere.
DaveN Said,
January 5, 2006 @ 3:41 am
Hmmmm
so is bigdaddy following them ??
DaveN Said,
January 5, 2006 @ 3:46 am
LOL you stripped out the NO follow tag
dont’ the question still stands did bigdaddy follow some nofollows
DaveN
David Said,
January 5, 2006 @ 3:59 am
@BigDaddy (the original one)
you’re 5 five ahead of me - are you getting paid for this? you either got nerves of steel or you must be deaf
the other big-daddy did not bring much changes in my sectors - which is got with me
Broker Boy Said,
January 5, 2006 @ 4:25 am
Matt,
Regarding my site -
I see pages that have been incorrectly marked as supplementary coming back as fully indexed pages. This situation was caused by a hijacking and various other problems including unintentional duplicate content caused by poor programing of a session id based quote system.
The strange thing is - for my site at least - odd pages have been picked as the ranking pages by the algorithm.
My site operates in uk financial services and for phrases such as life insurance uk our page on home insurance is being displayed rather than the home page (primarily optomised for that product area).
I suspect this may be the lingering effects of the problems the site previously had many of which have been ironed out.
I also had a canolonical problem with my main site this has been fixed on this data center as well.
In terms of the data as a whole -
It is more difficult to comment on if you are using a regional google for your market. Very few people in the uk use the .com Vs the .co.uk these days and the rankings are very different if you have to use a uk at the front or end vs a straight keyword search using the regional google to filter the results for you.
That being said looking through the results I can,t find a fault in my keyword area some very good sites ( not owned or operated by me) have been brought back into the serps ( although perhaps not where they deserve to be on the value of the site to a propective client) after they were tanked. Generally a better choice of sites than with the current data.
So from my angle job well done (RIDER - for most in the uk this is irrelevant till we see the same characteristics in the regional version as exibited by this data center and also how it handles the regional filtering)
Stephen Said,
January 5, 2006 @ 4:49 am
Matt
With regards to feedback from Big Daddy DC - I had a Canonical problem on the Homepage and Big Daddy seems to be dealing with that correctly now. However the site still has crawling and ranking issues.
You are talking about infastructure at this stage rather than ranking changes - so are you requiring feedback from sites that seem to have the Canonical problem fixed but still dont rank - or is better to hold off on this feedback until the infastructure leads to the next rank change - make sense ?
EG no point some of us reporting to your engineers along the lines of - It had Canonical probs which are fixed but the site still doesnt rank - if this is not to be expected at this stage.
Obviously if the rank is to be expected then some of us will have to look at other reasons for the sites maybe having problems - would be useful for you to clarify.
Cheers
Stephen
Eric G. Myers Said,
January 5, 2006 @ 6:42 am
This is feedback on the bigdaddy datacenter. I would have left it in the “Dissatisfied” box as suggested, but the 1000 character limit wouldn’t allow me to fully explain the issue. I hope it’s OK to post it here.
I have gotten a weird and replicable result I wanted to share.
I did a search for inurl:microsoft.com -site:microsoft.com
It works like a charm…until you get to the 11th page of the results (or beyond).
I then get an error message that says that automated requests are being sent from my network or computer.
I investigated whether something had gone awry with one of the tools I use that uses my Google API key. Found nothing. I also did a virus scan and spyware scan as suggested by the error message. Nothing again.
I have replicated this result from 3 different networks and computers. All generate the same result. At this point, I’m pretty sure it is an error on the Google side of the fence and I thought you might want to know about it.
What is interesting is that my access doesn’t really seem to be cut off (as the error message implies). I can immediately do another query and have it run fine. It just looks like I get this screen when I try to the 11th page of results or beyond. Normal queries run fine beyond 11 SERP’s (example: search for Microsoft by itself).
Just seems weird to me and I thought you might want to know.
Thanks for your time.
Eric G. Myers
Director, Search Marketing
Quest Software
Davywavy Said,
January 5, 2006 @ 6:57 am
Hi Matt
Thanks for the informative blog which i found today - I’ll be checking back.
1) I like Bigdaddy - it seems to ahve solved a lot of little niggles (googles doens’ ahve big niggles IMHO). What is the projected date for full rollout? Any ideas?
2) What was the data update on teh 27th december you alluse to? I think I see a lot less from the blogs, but I’m not sure - is that what happened?
Davy
Brian Turner Said,
January 5, 2006 @ 8:07 am
I’d hate to sound grateful for the BigDaddy info - but are there any regional searches that we can test results on for feedback?
It would be great if some of the bigger Google children - .co.uk, .ca, .etc - were able to provide feedback on BigDaddy results coming to national search only, especially as quality control issues are quite possibly going to be more marked in these niche areas.
2c.
Adam Senour Said,
January 5, 2006 @ 8:26 am
Wouldn’t you rather hate to sound ungrateful?
Johny S Said,
January 5, 2006 @ 9:00 am
Matt, can recip links to any harm to a website’s rankings? Or are they just given lower value, and do not result in any algorithmic penalty?
PK Said,
January 5, 2006 @ 10:48 am
So why exactly is the “Dissatisfied? Help us improve” link only on the first page. Don’t you think it would be more beneficial if a user can report bad SERPs from the page they see it on instead of having to backtrack to the first page??? I thought the link was disabled when I tried to find it while surfing until I stumbled on it about 30 minutes later by accident.
Just my 2 cents.
-PK
Adam Senour Said,
January 5, 2006 @ 11:17 am
I have an idea for an improvement that is probably too late for this update, but would probably serve future updates well and save a whole bunch of people a lot of grief (including you, Matt.)
And here it is:
penalty:domain.com or penalty: domain.com/subpage
Instead of having people guess at why their sites are being penalized or banned, why not just tell them? For example, a SERP for this could appear something like this:
Hyperlink to site’s URL with title tag.
If site is guilty of a crime, replace description with *** banned/penalized for the following reason(s) ***
list reason(s) here
Otherwise, simply list *** This site conforms to Google webmaster guidelines ***
page here - page size here - Cached (don’t really need the similar pages, unless you’re planning on showing other people who are guilty of the same algorithmic offense)
Here’s why I think it would be a good idea:
1) Sites that were banned/penalized would know why and wouldn’t be asking you, the other Google engineers, or every SEO/web discussion board out there anywhere near as much. Think of the man-hours that would save!
2) Most webmasters would fix their problems if they knew that such problems existed, thus cleaning up a lot of inadvertent spam and blackhat from the index.
Obviously there are some people who will continue to manipulate as opposed to fixing the problems that exist, and this would provide them a clue on how to do so. But, since the vast majority will have cleaned their acts up (and likely asked for a reinclusion requests), these attempts will usually become more obvious and therefore more likely to be reported and algorithmically/manually eliminated.
3) Pursuant to 2), you guys would have more time to devote to improving the algo, providing more relevancy, expanding your AdSense reach, gaining market share (less spam = more regular users), and making more money.
And, since you’d be the engineer that implemented my idea, you’d be a conquering hero and make celebrity tours and Google would give you a nice fat healthy bonus (okay, maybe I’m stretching here.)
The point is: rather than make one or two examples public, make them public on a wide-scale and allow webmasters at least the partial opportunity to clean up their acts and conform, should they choose to do so. I know I would if I were guilty of something I didn’t know about, and I’m sure I’m far from the only one.
Big Daddy Said,
January 5, 2006 @ 11:52 am
David,
Actually they pay for themselves and then some. 7 times as many other parents to network with and sell them a home!!
Life is great!!
Aloha
Big Daddy!
Brandon Said,
January 5, 2006 @ 2:08 pm
>> Q: What else can you tell me about Bigdaddy?
>> A: In my opinion, this data center improves in several of the ways that you’d measure a search engine…
TEASE! So tell me, how would *you* measure a search engine?
>> penalty:domain.com or penalty: domain.com/subpage
>> Hyperlink to site’s URL with title tag.
>> *** banned/penalized for the following reason(s) ***
Great idea! Then a site can know if it’s been penalized, or just doesn’t rank well. I’d say this goes along with the idea of G contacting webmasters whom it thinks can improve their sites when penalized.
Con: I can go to a competitor’s site, do a penalty:domain.com query, and see what they’ve done wrong at the moment (and vice versa). Then again, maybe that wouldn’t be quite so bad …
Abhilash Said,
January 5, 2006 @ 5:02 pm
I just wrote a huge response that got knocked off by the security code. Perhaps the massive response wasn’t necessary after all.
1. Adam, i used to believe that the penalty visibility would be important. Especially when Jagger3 knocked a client’s site on it’s Back Daddy. But now I don’t believe it would be a good idea at all. The only thing that would happen is that Grey-hatters would continue to push the envelope and tweek strategies until they knew how to optimize for every little allowance without getting a penalty. this isn’t helping webmasters, it’s helping SEOs who want to concentrate on the algos rather than their own sites, and more importantly–the users.
2. Matt, I’ve definitely seen some great improvements in the new BigDaddy searches. Congrats on that. I have one very important question that I can only hope you try to answer:
I definitely want to hear about webspam that you see in Google.
Ok–I’ve done the spamreports, done the “dissatisfied” submissions (yes both using the keywords–first jagger then jagger3 then BigDaddy) for months. If there is no responses in sight, what is a website owner supposed to do when spammers still get to rank at the top–BigDaddy or not??
Right now, a site ranks #1 for “Alcohol Rehab” by participating in a link scheme…well that is if you consider 100 unrelated sites using the same link-script-page a “link scheme”. Here is a rehab, a Singapore travel site, & a Maine Insurance site all using the same page AND RANKING:
The same tactics are working across several other keyphrase queries.
When SpamReports & “Dissatisfied” submissions don’t work, and updates don’t seem to help, what’s a site owner supposed to do? Either beat them or join them. Well I’ve been able to succeed in Yahoo & MSN with content… but not even BigDaddy caught this??
There are also 3-4 different networks of about 30-40 duplicate-content-driven satellite sites used to inflate the link pop/PR of other sites ranking in the top 10 for these keyphrases. Ultimately, these sites account for 6/10 of the top 10 and perhaps 12/20 of the top 20.
Matt, if you’re so pro-white-hat, then please give me a reason NOT to use these ridiculous strategies. I don’t want a network of 40 crappy websites nor do I want to join one of these stupid link farms.
No offense to anyone, but this isn’t “sexy lingerie” or “gardening supplies”, it’s a very serious industry space where people really need help and it can be life-or-death at times. Ethics matter. Any advice??
Thanks…
Adam Senour Said,
January 5, 2006 @ 5:27 pm
Brandon: I had the same thought, and I don’t really see it as a positive or a negative.
It allows for the potential to see who could quickly get back into the race for a given keyword or phrase by fixing things, and it might force webmasters to think proactively instead of reactively in terms of maintaining position.
It would also lead to two competitors, presumably with white-hat intentions, going after a word or phrase, as opposed to a black hat vs. a grey hat or a black hat vs. a white hat or a grey hat vs. a white hat.
Support Said,
January 5, 2006 @ 6:18 pm
Matt:
I would like to see an answer to Pat’s question.
Note: Please, an answer from Matt, not from random-know-it-all.
David Said,
January 5, 2006 @ 6:36 pm
When you do a site: query, do the results (ordering) have any significance?
Also, if you have a site with more than 3-5000 pages and the results show 29,000 is there a way to see which results G is showing beyond the 1000?
SurfBlog Said,
January 6, 2006 @ 3:32 am
An update on Dec 27th?
Now I understand why traffic doubled on my site. That’s cool
Abuse Said,
January 6, 2006 @ 3:40 am
I wonder if the duplicate-content spammers at Answers.com will finally be penalized by the BigDaddy update?
They seem to be immune to all penalties. It makes me want to become a black-hat!
Dave Said,
January 6, 2006 @ 7:38 am
Hey Matt, Was wondering if it’s ok with you if I quote in two of my relevant websites what you said here about both ‘canonicalization’ and ‘reinclusion requests’ (with credit to you of course)? Thanks.
Brian Turner Said,
January 6, 2006 @ 7:42 am
“Wouldn’t you rather hate to sound ungrateful?”
Quite right - my bad - otherwise my original sentence suggests a level of dry humour I just don’t have.
Pat Said,
January 6, 2006 @ 10:01 am
Ledfish Said
“PAT fron greennature.com
“Wish I had a way to contact you, we both seem to be trying to over come the same internal duplicate content problem or so we assume.”
Ledfish,
Contacting me is hidden away as a comment form on my privacy policy page
at article1029
I won’t put the rest of the url so as to not mussy up poor Matt’s comments with what may come across as spam links.
Let’s compare strategies.
Luis de la Orden Morais (Brazil/UK) Said,
January 6, 2006 @ 10:26 am
Hi Matt,
I couldn’t avoid noticing that the search interface powered by the Bigdaddy centre bears the name of the language (English) instead of the name of the country. Is this how Google in the States looks like? Or is it a global Google roll-out more linguistically targeted?
Talking about language, I would like to share a couple of things about the linguistic relevance of search results in Google outside English-speaking countries, something that has been a bit of a thorn on the side for a majority of ordinary users who do not speak or understand languages other than their own. Just to clarify what I mean by language and countries please bear in mind, that as a Brazilian, I am talking about Portuguese and Spanish in Latin-America.
In order to make it clearer for everyone to visualise the issues, I would like to share a few statistical data collected by appointment of the Brazilian Government last year on Internet usage and penetration in Brazil (). I believe we can assume the situation in other Spanish-speaking countries in the South-American subcontinent are similar.
As expected, the number of users in Brazil is small, counting with approximately 12 million people connected to the Internet out of a population of 185 million. According to the Brazilian Internet census, from this total just 20,81%, or 2.4 million people, use the Internet to search for information and online services. The most interesting fact about these numbers is that the total number of users connected to the Internet is in their majority from classes A and B, which are the most proficient and resourceful in the use of Internet.
The Language Issue
=================
I believe one of the reasons for such a small adherence to pivotal services such as search engines might be rooted on the fact that those services are still to offer the same ease of use in UI and quality in search results without much linguistic interference from other languages.
Our search settings are set by default to serve results from the web. This option yields results in any language.
Although, terms such as ‘acarajé’ (an Afro-Brazilian bean fritter) are easier to find in pure Portuguese, results get more confusing when one is researching for scientific terms; terms that are orthographically similar in several Latin languages such as ‘politica’; or, international names of places and celebrities, just to mention a few.
Even when our users select “results in Portuguese” for a term such as ‘florida’ (full of flowers, in Portuguese and Spanish) in google.com.br, that does not guarantee they will get results in the language they had to make the extra effort to select: their own.
We feel that not only there is a lack of linguistic consistency in the results served but also what seems to be a not very well contextualised or culturally usable approach of search services inside the Portuguese and Spanish-speaking world at least.
The Florida example
===================
A search for ‘florida’ in Google.com.br with ‘results in Portuguese’ enabled made on 05 January 2006 yielded the following in the first page:
- third result, vernacular Latin;
- fourth result, vernacular Latin with a few English words at the bottom of a document from the Netherlands.
Just a couple of weeks before, the same search with the same settings brought a couple of English results just after the ones in Latin.
If you make the same search you will notice that there are a few other results with descriptions in English. In fact, those pages are in Portuguese and despite the bad linguistic accessibility they were not taken into account as foreign results in a Portuguese-only search in my personal research.
As known, from a SEO point of view, description meta-tags have little or no influence on the major SE’s. However, they are the first point of information for users whenever search engines such as Google decide not to display excerpts of the text surrounding the keywords requested.
From a human point of view, despite the fact most of the blame goes to the web content producer who wrote the meta-description and the content itself, search engines could do better in not letting a whole meta-description in a language other than the one selected by the user slip or be displayed in the SERP’s. As you know and might have said before, the description might not be important for the SE robot but it is for the user.
The language changes, the principle stays
====================================
Living in the UK and being able to communicate fairly well in English, I find it admirable to live immersed in a culture where all the information is readily available in the local language: from the technical books that help you as a professional, to the gadgets and their manuals to even salsa classes: everything is linguistically ready for consumption. You guys got it right: serve it in simple and clear English and you make it psychologically accessible for the consumer’s desire.
My suggestion is that Google’s default language results in country pages should be in that country’s language(s). It is not only usable and accessible (both socially, culturally and interface-wise) but in a context such as the Brazilian, would give a hand to local developers trying to show the other 80% non-searching users in Brazil that searching for information in a ‘national’ SE brings the results they are expecting without any hiccups and hindrances. Most of all, it would help to uphold the Internet as a democratic resource that caters for all equally.
In a sense, the way it is now is like watching a subtitled film, either you concentrate on the dialogue or watch the action. Even those commanding the art of reading and watching a film at the same time do not deny it is much better to watch motion pictures in their own language.
The “Pages from Brazil option” issue
===============================
Unlike the UK and other countries that liberated the purchase of national domains to anyone, since the beginning the Brazilian government decided to reserve the .com.br and .net.br domains strictly to companies with a registered office in Brazil. Contrary to the disputable gain in creating a market free of speculation, this has created a trend amongst Brazilian web developers and designers to open their websites with .com or .net domains instead.
On top of that, a considerable number of the most affordable hosting companies in Brazil are actually merchant customers of hosting companies in the US. The same happens in other countries as well, even in the UK where thousands of .co.uk are believed to be hosted in much more affordable American hosting companies.
I believe the way Search Engines, including Google, have been positioning content as pertaining to a certain country according to the domain and where it is hosted is missing a trend that is going completely to the other direction.
Yes, it is not Google’s fault that the academics at Fapesp (the institution that used to take care of the .br domains) have dictated that, if one is not an institution or a liberal professional registered in an official professional association, all that is left is the dubious .nom.br domain.
SEs could improve their localised SERPs tenfold if they considered that certain national domains are hard to acquire and that a significant amount of sites in the western world are hosted in the US either in paid host companies or in free host services such as blogger and geocities.
Possible workarounds for the ‘pages from…’ problem:
—————————————————————–
a. Extend the algorithm to check the content of the page (keywords, addresses, language, etc…) and interpret what country that page belongs to. It can be a bit complicated for multi-national sites hosting pages in several languages side by side, but if big multinational sites can, then the solution might already been in place somewhere just waiting to be rolled out across the globe.
b. Language differentiator chart (stemming). When I was a kid, my father, a Spanish immigrant, used to write down how to say certain words in several languages spoken in the Iberian Peninsula (Portugal and Spain). He would start with a word like ‘action’ then by using stemming he would progress from ação to acción then, acció, açon, etc…
Every Latin language has a set of characteristics that differentiate them from each other. I believe Google is already doing something in that sense as we can not see as many Spanish results in Portuguese-only searches as it used to be before.
c. Inbound and outbound links from a certain country. It could give a clue to bots of which country the .com or .net site belongs to.
d. Country opt-in via Google Sitemaps or other XML resources. Extending Google Sitemaps functionality to accommodate XML language/country declarations would be great and also help the algorithm to judge where the page is from.
e. XML namespaces in the HTML tag of the document.
f. Target country meta-tag. HP uses it already:
g. Country hint in the URL. In the same way SE algorithms read keywords in the URL, it could be helpful to extend the algorithm capability to analyse a .net or .com as pertaining to a country via the countries XML abbreviation in the URL. Example:
http:/ / www .foreignsite. net/br/index.html
h. DMOZ indication. Use of DMOZ’s country categorisation as a validator of a site’s origin.
None of the workarounds suggested above would in fact work alone (after all, we don’t live in an ideal world where everyone says the truth in their meta-tags) but the group of them used together in different priorities and weights against indexed pages could help to decipher whether a .com or a .net is an American site, a site from any other country in Latin-America or a mail order company based in Jersey trying to expand its business to other countries by faking its origin.
In any case, what I would like to ask Google and other Search Engines is that a new way of looking into the linguistic challenges mentioned above be studied with sincerity and that you help us develop our small market by offering search results and search interfaces with language options that, by default, are relevant to our audiences in both sides of the digital divide.
We’ll be looking forward to ‘Bigdaddy’ but we’ll be more joyous when ‘El Gran Papá’ and ‘O Paizão’ come home.
Many thanks for your attention and looking forward to hearing more about what is shared above from you and your company.
Luis de la Orden Morais
Editor
Luis de la Orden Morais (Brazil/UK) Said,
January 6, 2006 @ 10:42 am
Hey Adam,
Long time no see, eh?
Excellent idea indeed! But instead of displaying that info in the SERP’s what about having these reports vinculated to the Google Sitemaps account? That would guarantee just the owner knew what is going on with his own site and would save users the trouble of knowing their favourite website has been naughty.
Cheers,
Luis
Sarah Said,
January 6, 2006 @ 12:43 pm
Hi Matt,
And on top of all the other thank-you(s) – please add one from us
Question: Our 301 issue is with a supplemental listing. Is BigDaddy going to address those?
Thanks!
Sarah
Matt Said,
January 6, 2006 @ 1:04 pm
Pat, you definitely have no manual spam penalties. Think of the Supplement Results as an index with its own Supplemental Googlebot, or (S.G.). S.G. doesn’t come around very often (sometimes not for months), but when it does, it goes much deeper.
When the Supplemental Googlebot last visited your site, you had the www pages. Now you’ve gotten rid of those, but S.G. hasn’t been back around to see that. The normal Googlebot with the main index has been around plenty, and knows all about your change to go non-www, but normal Googlebot doesn’t have the ability to go into the supplemental results and change the urls.
My advice would be to develop your site normally and not to worry much about the supplemental results. I’ll be happy to pass on the feedback that people want the S.G. to visit often enough to see changes in the site like this.
Matt Said,
January 6, 2006 @ 1:41 pm
Sarah, I wouldn’t expect BigDaddy to address 301s in the supplemental listing. The supplemental listings are really independent of BigDaddy and just sort over overlay on top of BigDaddy.
Peach Said,
January 6, 2006 @ 1:58 pm
I can’t see why you are always advertising for WMW, it’s really a terrible site (GUI,policies,overall quality of threads,search functionality)
There are webmaster forums that are so much better in my opinion.
(sitepoint,SEwatch and probably more)
Matt Said,
January 6, 2006 @ 2:40 pm
Dave, I wouldn’t mind if you a paragraph here or there, but instead of quoting an entry verbatim, I would prefer for you to summarize. That is, fair use quoting is fine with me, but I’d rather you didn’t copy the whole post.
Hope that makes sense,
Matt
Father Murphy Said,
January 6, 2006 @ 6:08 pm
Amen to that Peach!
GoogleGuy is the only attraction keeping WMW alive.
If GoogleGuy left, almost no one would put up with the crap at WMW any longer.
Pat Said,
January 6, 2006 @ 7:03 pm
Hi Matt,
Thanks very much for the look see at my site and explanation of the S.G. That makes sense.
I do believe that sometime during the summer as I was working on my .htaccess (I have 5 different ones on my site dealing with specific sections and DBs) that I inadvertantly transferred the wrong one to the root. So, it was my bad in the first place.
I think I was too excited about my newest article at the time, “The Amazing Seahorse”
I was totally surprised to hear that it’s the male seahore who gets pregnant and delivers the little ones.
Moral of the story, don’t think about the sexual habits of marine life when you are working on your site
amanda Said,
January 6, 2006 @ 9:46 pm
Is there a way to KNOW when you look at 66.249.93.104 if you are seeing BIGDADDY serps or not?? When i search for [sf giants]i NEVER get giants.mlb.com at #1 — was that a thing of the past or has bigdaddy been off a few days now??
Carol Said,
January 7, 2006 @ 1:44 am
www vs. non-www issues are almost resolved on the new data center.
I see movement up on serps and hope with BigDaddy that I will mostly move back to where I was. You will see me jumping for joy if that happens and I get Google traffic back again. :-0
Carol
Armi Said,
January 7, 2006 @ 7:12 am
Hi Matt,
what is the new task of the Mozilla Bot
Mozilla/5.0 (compatible; Googlebot/2.1; +)
?
Sarah Said,
January 7, 2006 @ 7:59 am
Hi Matt,
This is really devastating news for us as the supplemental page is (our real URL is in my email address) with a cache of January 23, 2005 (no kidding
And although last summer we put a 301 on to, which regular GoogleBot routinely finds and follows perfectly, we’re still clearly being hit with a duplicate penalty for this supplemental.
Actually, during Jagger the cache for updated to November, 2005, so we thought that there was still hope. However in 66.249.93.104, the cache for has reverted to January 23, 2005. So it looks like we’ll need to switch to a new URL entirely to finally rid ourselves of the issue.
Do you have any idea when the supplemental index may be refreshed?
Thanks!
Sarah
Sarah Said,
January 7, 2006 @ 8:02 am
Sorry — dropped a couple .com(s) by mistake. The supplemental is –
Adam Senour Said,
January 7, 2006 @ 12:18 pm
I would agree with that in the very short-term. Keep in mind four things, though:
1. What you’re suggesting is the classic criminal behaviour pattern.
For those unfamiliar with this (and as a fan of the A&E crime drama shows, I’m quite familiar), it’s a pretty simple concept. Most criminals tend to repeat or increase the severity of their crimes until such a point as they get caught in the act. How many times have you not sped down a new stretch of road until you realize that there are never any cops on it, and then get the lead foot out and go faster and faster until you do get nailed? I’ll admit it; I do this all the time, and sooner or later, I’ll probably get nailed by a cop for it.
Now…how does this relate to spammers and grey-hatters?
Spammers won’t stop at keyword stuffing or doorway pages or IBL spam or Google bombing or any one of the 5,000,000 techniques out there. They’ll keep going. They’ll keep pushing the envelope. And the longer they do it, the more people like Matt will become aware of it.
2. Competitors will either rat out the SEO types for their own gain, or attempt to compete on the same level. In the case of the former, the SEO stops (assuming Google agrees and reacts accordingly). In the case of the latter, the game enters continual escalation until such time as one or the other goes too far.
3. If Google openly declares the reasons for getting blacklisted, they won’t have to answer millions of questions about it. This will allow them more time and resource to devote to further tweaking and improving of the algorithm as well as manual removal of those who choose to try and manipulate unethically. In other words, they’ll have more time to solve more grey-hat issues and in turn, shrink the grey area.
4. I hope this isn’t taboo (watch Matt ban me from his blog now j/k
) but you do realize that there are *GASP* other engines out there, and too much ######## around can lead to a blacklisting from those as well. So someone’s attempts to toe the line with Google could in turn get them burned on another level on another engine (and if the other two adopt the same policy, then the same types of things occur).
So yeah, people probably will try to screw with the SERPs. I don’t doubt that. But the more Google stands up and says “hey, we’re nailing this site for this reason”, the more they say “hey, you can get burned for this reason too” and that will prove to be a deterrent in at least some cases.
Good Sam Said,
January 7, 2006 @ 9:58 pm
Sarah:
Matt can correct me if I am wrong, but I believe that the duplicate content filter (not penalty) would effect only the 2nd, 3rd, 4th, etc… “most relevant” ummm… “copies” of each instance of one of your web pages.
In other words, the duplicate content filter would *not* lower the SERPS for _at least one copy_ of each of your pages.
How Google determines which duplicate is primary… that is a complete mystery to me. All I know is that they are frequently wrong.
Peter Said,
January 8, 2006 @ 4:07 pm
I´m also interested about the Mozilla Bot.
Is it correct, that the new important Googlebot would be the Mozilla Bot? Is Bigdaddy the Mozilla-Bot index?
What´s the diffrent between the Mozilla Bot and the Googlebot?
Robin Kay Said,
January 8, 2006 @ 7:23 pm
Matt,
Where did big daddy go?
Sarah Said,
January 9, 2006 @ 8:02 am
Hi Good Sam, is an exact duplicate of our home page that’s located at. And we’ve definitely incurred a penalty in the SERPS as a result. Further, as it’s the text that sells, it isn’t about to be changed.
And in thinking of changing URLS, another problem appears: we have great in-bound links and no out-going links so we’d want to 301 our old site to our new site in order to save the links. However, that would doubtless bring the problem right along – and we’d still be having to deal with the penalty.
Sarah
Adrian Cristian Said,
January 9, 2006 @ 10:33 pm
I have a strange problem.
Google indexed my site I think on 5th January. I have in Google 20.600 pages. After two or there days..when it was Week End..I have only pages that was indexed before 1 January 2006, only 78 pages.
After this..monday 9th January 2006, after 1pm it works fine..having all of my 20.600 pages.
In the evening, 8 pm I have that problem..only 78 pages.
After a short while, after 5 minutes I have all of my pages.
Before I go to sleep I’d check to see how many pages do I have, and there was that only 78 pages.
I’d spoke to people and they said me that I have an error..the shopping cart it’s written in Perl..so I need a redirect to /cgi-bin/index.cgi. I was doing this redirect with a Java Script, but I heard that can cause problems, now I’m doing with this:
Can you please take a little time to answer to this please.
Thank you in advance,
Adrian Cristian.
Adrian Cristian Said,
January 9, 2006 @ 10:33 pm
I forgot to say: those hours that I mentioned was GMT time.
Adrian Cristian Said,
January 10, 2006 @ 5:24 am
No, 14:24 it’s working well
TearingHairOut Said,
January 10, 2006 @ 12:49 pm
Hmm, looking at BigDaddy earlier today on 64.249.93.104, (I did do the sf giants check to make sure the BigDaddy results were up), I see that, for my main keyphrase, the first page showing from my site is in the mid-sixties on SERP’s, and it is the links page.
Now I’m not going to moan about rankings, because I’d largely expect a result in the mid-sixties, but it just seems really wierd that internal pages with no external BL’s are still showing up where the site homepage is not.
This has been a recurring theme on forum discussions, so if there is any likely theoretical explanation that you can give, I’m sure it will get lots of attention.
SeoDude Said,
January 10, 2006 @ 12:57 pm
Guy !!! You at Google never reply to contacts . I used the form to inquery about a ban and got no reply for over 1.5 months .
Thanks .
TearingHairOut Said,
January 10, 2006 @ 1:01 pm
Update to my previous comment:
I just checked again and my homepage is now the first page from my site to appear in the SERPs for my main keyphrase. However, it’s down in position 126.
So I’m not sure whether to cheer or groan…
Obviously things are still in flux a bit.
Lost Puppy Said,
January 10, 2006 @ 9:35 pm
Ha! 1.5 months is nothing! I’ve been more than twice that long.
Google seems to have no effective methodology for communications. Matt, charming as he may be, is not scalable.
It appears that 95% of those e-mails get thrown into the bit bucket because Google just doesn’t care enough about producting quality search engine results to look into problems with their system.
Mike Said,
January 13, 2006 @ 5:43 am
Hi Matt,
just doing my weekly serps spreadsheet and noticed that they’ve all improved, dramatically. Looks like Big Daddy has been included into the index as of this morning, UK Time.
TY
Mike
Wuzhong Said,
January 13, 2006 @ 7:54 am
Matts,
Thanks for your useful information.
My question is:why that 2 IPs you provided show different SERP?
vikasamrohi Said,
January 13, 2006 @ 9:33 am
hi Matt,
Thanks for highlighting this, well i have seen my future results on both of the DC’s and didn’t get any fluctuations in the ranking. But the major thing i have noticed is related to the GEO targetting. I am using GEO targetting in one of my site
if anyone open the site from US then opens and if any one open the site from UK the opens. My site is still on top but the now is coming on the top. My site is in bigdaddy’s mouth???
Keen to hear your comments
thanks
Vikas
Val Said,
January 18, 2006 @ 10:44 am
Thanks Matt and Google developers for a new set of obvious improvements!
How will Bigdaddy treat 301 redirects from an internal page to a root page of another domain?
How high are the chances of passing the rankings that this landing page had onto this new domain?
Val Said,
January 18, 2006 @ 10:57 am
One more if possible - this I believe interests pretty much everyone here - do you have any news on how much more the transition will take?
Colin_h Said,
January 23, 2006 @ 4:33 am
Hi Matt,
We’ve been thinking about the onset of Big Daddy and wonder whether February 2nd is a good day for the event … Groundhog Day. Let’s hope we don’t have to do 2005 all over again
R. Said,
January 24, 2006 @ 5:09 am
Hi Matt,
Unfortunately for some reason you do not show my comments.
Is this because you’re not comftrable with them for some reason?
Are there different guidelines and SPAM laws for some wellborn websites, and other rules to the rest of us?
How come that companies like weblogsinc.com that uses massive substantialy double content on their websites to increase search engine visibility don’t get a penalty for breaking this basic guideline. Here are some real world examples from their flagship website - engadget.com.
exactly same content on 2 different sub domains. and I could fill this email with such examples.
You can see Google bold preference is also for about.com. For example take a look at their sitemap, with thousands of links only, it was built for just for search engines. show me one human being that can get benefit from this sitemap… If I was building such sitemap like this on my websites I would have been banned in a snap.
You may also find TONS of non useful links and ads only pages on about.com, what you call if I’m not mistaken as “pages desined for search engines”
Are these companies bulletproof?
Sincerely,
Roy
Nick Said,
January 29, 2006 @ 2:20 am
Hi Matt,
I came across to a website and seen this website have Google PR 7. When I checkd link: I found 2,300 link back information according to google.com search. But when I have open the link back pages I haven’t found any of the link back information on the pages.
I will await for your answer.
DouG Said,
January 30, 2006 @ 12:08 am
Hi Matt,
Jan 30 still saw a lot of “Big Daddy” results shuffled into standard results over the past few days. I have also noticed that there seems to be quite a few splogs hitting top 10 results. Sending spam reports as requested but they seem to still dont seem to get banned (Im sure google get’s spammed with spam reports, and are working on automating the process somewhat.).
Overall the results of this new data center look very positive, more subtle than “Jagger” but certianly more geared for the user.
Keeping my eyes peeled for SERPS to come.
Doug
P.S
I agree with “Colin_h” vote “Ground Hog Day” for launch!.
Richard Said,
January 30, 2006 @ 6:22 am
What the hell is Big Daddy.
hasit Said,
January 31, 2006 @ 3:40 am
hi Matts,
i am very happy to find your website, i have a quick question for you. i was just searching around the website and found to be different than
you mentioned in one of your answer about that site: is changed in all the datacenters, than why this difference? Please advice.
James Said,
January 31, 2006 @ 7:01 pm
Matt
Nice to see you greeting some of us more ordinary folks and providing a glimmer of hope in our search for better ranking and thus a better life!
I have to say that on first glance at the picture above, i mistook the set up and wondered why some poor paralegic in a blue shirt had his legs on the table for everyone to watch !… it took me about 1-2 mins to work out that they werent actually legs but a rucksack instead !!.
Keep the posts coming and dont forget the humour.
James
markkk Said,
January 31, 2006 @ 11:12 pm
How are you doin Matt,
I just wana ask about the Big Daddy DC.. is the update on the algorithm still in progress?
im pretty confused with its SERPS..
Like example… When I searched for the keyword “psychic reading” , it seems the top result is about “tarot cards”…
Thank you and Goodluck!
-Mark
RobMarketshare Said,
February 1, 2006 @ 4:03 am
PR7 and 2300 backlinks, Thats curious, because I came across a Dutch (.nl) website with an undeserved PR7 too. And guess what I has exactly the same backlinks as in the PR7 site metioned above.(29th)
Matt, what’s going on here?
Search Student Said,
February 1, 2006 @ 5:13 am
The results from BigDaddy seem to have an opposite effect in some situations. The BigDaddy results show a notorious cloaker, page jacker, redirect artist at #5 for a very competitive term, where this site was #9 previously. The site is part of a big link network, and was bombed to the top within a few weeks… it is a one page micro site, on an advertorial, on a small newspaper’s domain.
Isn’t this the kind of stuff G is trying to weed out? Seems the new datacenter favors this type of behavior.
Chung Said,
February 1, 2006 @ 7:52 am
I hope with this new BigDaddy my rankings improve.
Marzan Said,
February 1, 2006 @ 8:02 am
Hi Matt,
I’d really appriciate to read a response for the issues that Roy (R) has wrote.
There’s also a very interesting article with facts on SEOChat:
Regards,
M.
BradD Said,
February 1, 2006 @ 11:23 am
The results are improved in a big way. I am very happy.
ashmita_mosaic Said,
February 2, 2006 @ 4:23 am
Hi
Sometimes different browsers show different Google/Yahoo/MSN rankings for the same page and same keyword……please explain why this happens..
Also, it was really strange when we found that a particular site showed PR 5 in the same browser of 1 computor and showed a 0 PR in 2 others!?!!
Karl H. Knop Said,
February 2, 2006 @ 11:38 pm
Hi Matt!
nice 2 hear about Googles intentions,
but why can Google not handle site with different language start sites correct?
it lasted month to find the English version and my Russian version seems never to be on the list. I also think Google should count multilingual Sites better than Sites in only one language.
Roxana Said,
February 3, 2006 @ 7:02 am
Hello Matt,
I don’t know what to make of all this dancing that’s been around with Big Daddy. On one hand, I personally like what is displaying because most sites that I monitor are indexed properly and the position is great. But the problem is that it only last for a few minutes, because when I check the same website five minutes later, its indexed pages have dropped more than 70 % and the text of each link is no longer the right one. Is this normal because of all the trials Google is making? Not to mention the chaos displayed sometimes on the actual Google. There, the dancing is even more frenetically and that means losing a lot of traffic, thus a lot of customers or visitors in the case of web editors and of course Google also must be losing a lot. Let’s hope that when Big Daddy finally enters the stage, things will cool down a little bit. Thank-you and good luck with the trials.
Lee Said,
February 3, 2006 @ 10:49 pm
Yah! you are correct Ms.Roxana.
Most of the sites are updated often. Yesterday I saw a site for a specific keyword at 100th position and after 5 minutes it has moved out from 100 to 300. How is it possible? If Bigdaddy is making a trial, then there will not be any static results for atleast 5 minutes. I am wondering what are the changes going to happen in Bigdaddy’s update and what are the ways to improve my site rankings. I think I have to update myself every 10 minutes.
Ash Said,
February 4, 2006 @ 12:44 am
Hi
I have been having a chat on digital point ( ) about one of my web sites that was doing rather well in google, but just recantly seems to have been de-indexed for no apperant reason and the pr set to 0.
The web site is an affiliate site from pooldawg using their csv file to create and display their products. It would appear that my site has suffered due to this, as it may appear to be a scraper site pulling their content to my site. But surly this is what affiliate websites do that use csv files and such like. So now that the digdaddy update is “underway” will all affiliate web site now be penalized for using their affiliates csv files becuase if this is so, then affiliate web sites everywhere are going to suffer as the new update rolles out. These sites are not spam or scraper sites but affiliate sites and google must see this and not penalize us for creating them surley.
Karl Said,
February 5, 2006 @ 1:26 am
If I am an unknown artist on my way to become famous, deciding the internet is the right place to tell the people in the world about me, I had to thing about google and their system.
Google demands me to get good theme related incoming links.
But therefore I had to ask or pay my competitors.
My work is new and different but anyhow people all over the world from several cultures will love it (if they would know it). If I ask competitors for backlinks, nearly no one will answer because
their art will look very old fashioned against mine.
So this backlink-system works like the communism hadn’t work.
To all this comes that google don’t trust our metatags and so we all had to pick
with a bar in the (google made) fog (german adage).
It all would very much easier if google began to trust us.
Therfore I would be feel up to add some tools to my Site.
For example a programm which manage my Linksystem so that
every searchbot can see to whom I linked but also who had ask me for a link.
The webmaster can decide to take or not to take this link, and the bots can
read his decision in my tool and can think about both. So a decision to take or not to take this special link can be good or bad for my site (your decision), and afterwards everyone will handle the link-system much better.
I think this could be easy and the bots become more and corrector information’s.
And at last I have to say, that the Internet is showing the whole world, not only this what US-Americans held for it. I have a multilingual Site and it seems to me, that google
penalties me for it (as mirror content) instead giving me some advantage for this.
I think most of the spam problems google have are house made.
I think you (google) earn money with our problems you have caused be your own strategy.
And therefore you make a great ballyhoo like this here, that no one understands it.
I know that’s not a real cannonical theme but this idea could very helpful to us all.
I know also that such bot an my side of the web (for better understanding: the other side is
the of search engines), bring new problems. But specialists can work on there, and they can know what’s needed.
I, and most other webmasters, never would really able to know what’s
needed in all this terms.
Radovan Dzurcanin Said,
February 5, 2006 @ 4:15 pm
Sorry, can I ask you what do you call a spam feedback? I mean, what is the definition of SPAM… thanks.
Cherryl Said,
February 6, 2006 @ 4:09 am
Nice to see you greeting some of us more ordinary folks and providing a glimmer of hope in our search for better ranking and thus a better life!
Vikas Amrohi Said,
February 8, 2006 @ 11:24 pm
Hi Ashmita,
Please find my response blelow your question
Q: Sometimes different browsers show different Google/Yahoo/MSNrankings for the same page and same keyword……please explain why this happens…
A:This is because the different browsers pick the data from different ips of the search engines. all the search engines uses the geo mapping thats why you get the different results.
Q: Also, it was really strange when we found that a particular site showed PR 5 in the same browser of 1 computer and showed a 0 PR in 2 others!?!!
Ans: It might be the problem of the google toolbar, or u have to check the IPs of the google on both of the computers if the ip are different then it means google is ranking you differently on its different IPs.
Cheers
VikasAmrohi
KrzysztofM Said,
February 10, 2006 @ 7:46 am
With what happened with BMW - nice to see that google re-inserted them back in the index. My question is this - If it was an average joe that did this I don’t believe that it would have been as easy to get re-inserted for joe. Either we all get treated equally or google is clearly showing favourism here.
Search Commando Said,
February 14, 2006 @ 1:18 am
So it looks like after a couple of weeks the “big daddy” was taken back offline last night. Have we any ideas as to when this data center will settle down to business? Overall I think that the new results were very positive and look forward to a permananet deployment.
Tosin Adesanya Said,
February 15, 2006 @ 9:05 am
Old database: about 9,680,000,000 pages
New database: about 25,270,000,000 pages indexed indexed
Now how can these numbers be correct. i thought Google was trying to cut down and filter random and uneeded pages, so i would expect the numbers to fall. However, according to your #’s you have went up. How?????
Nitin Said,
February 17, 2006 @ 12:17 am
Can anybody explain me please when google is going to update its pagerank and serps.Because this Bigdaddy update is going from the last one month but still no stability in results, OR google will increase its time from 3 month to 6 month for an update.
vary Said,
February 17, 2006 @ 2:03 am
I noticed the bigdaddy data center update the sites slowly, but the current other google data center update the sites quickly. Dose the bigdaddy data center use different googlebot?
Serkant Karaca Said,
February 17, 2006 @ 3:12 pm
How long will it take to complete BigDaddy DC? Because serps are still fluctuating and this is annoying for webmasters.
Mark B Said,
February 21, 2006 @ 1:53 pm
What’s the differance. The black hatters will buy new urls and have a new site up in 1 hour. While some of us get caught up in the wave
Jason Said,
March 2, 2006 @ 12:46 pm
Interesting information and discussion, but the Big Daddy DC’s leave me a little concerned.
We’re seeing subdomains of our site completely removed. Is this because you’re unable to determine their position vs www-mysite.com as opposed to subdomain-mysite.com?
If I search for subdomain-mysite the result pulls up www-mysite which in part is ok, but not an accurate reflection of the content.
Should we be thinking in making all pages www-mysite.com/subdomain again or are subdomains still a valid option for siteowners?
Jason
Monika Said,
March 8, 2006 @ 11:21 pm
When is Bigdaddy update is going to get end.
& when will be the next update.
How can I come to know whats the next update
Mary Said,
March 10, 2006 @ 8:09 am
I see you were talking about duplicate content. What does this mean for me when I submit my articles to directories? Will this effect me or someone else that uses my articles? Or does it just have to do with content on my website?
marlies Said,
March 22, 2006 @ 5:44 pm | http://www.mattcutts.com/blog/bigdaddy/ | crawl-001 | refinedweb | 14,140 | 69.92 |
I need help figuring this out. What I need is this:
- The section number, as a string
- The instructor's name, also as a string
- The number of students in this section, as an integer.
- The student's scores for the test, as an array of integers. Declare this array to be of size 30. Do Not use a vector in this exercise!
provide the following member functions in your class:
- A constructor that takes the section and instructor's name. It should set the number of students to zero and initialize all of the array elements to zero.
- A readData( )function to read in student scores from a file. This function should verify that the file opened correctly, and that each piece of data was successfully read. As you read in each score, store it in the array, and increment the variable that holds the number of students in the class. Read until you encounter an end of file condition.
- a function that returns the number of scores stored in the array,
- a function that takes in integer value as a parameter, and returns the score at that position in the array of scores.
- a function that returns the highest score on the test,
- a function that returns the lowest score on the test,
- a function that calculates the average score on the test, and
- optionally a function that sorts the array (extra credit).
Your main( ) routine should work as follows:
- Display your student information.
- Creates an object of the Section class.
- Prompt the user to enter in a file name
- Read in all of the scores from the file, using the readData( ) function described above. The object should now contain the number of scores read, and the scores should be stored in the array.
- Optionally sort the array (extra credit).
- Call the function that returns the number of scores stored in the array.
- Using this value in a loop, display all of the scores in the array.
- Call the function that returns the maximum score, and display it.
- Call the function that returns the minimum score, and display it
- Call the function that returns the average score, and display it.
What I have so far is:
section.cpp
#include <iostream> #include <fstream> #include "section.h" using namespace std; int main() { Section object; Section::readData(); system("PAUSE"); cin.get(); return 0; }
section.h
using namespace std; class Section { private: string section; string instName; int students; const int SIZE = 30; int array[SIZE]; public: //Section[array]; readData(); num_scores(); /* high_score(); low_score(); avg_score();*/ }; void Section::readData() { std::string filename; cout << "Please enter in the path to the student score file: " << endl; getline(cin, filename); ifstream theFile(filename.c_str()); if (theFile.good( ) ) { cout << "Test Scores are: " << endl; int number = 0; double average = 0; int score = 0; int count = 0; int max = 0; int min = 0; while (theFile >> number ) { if ( count == 0) { max = number; min = number; } else { if (number > max) max = number; if (number < min) min = number; } score += number; count++; cout << "\n" << number; } average = score / count; cout << "\nLow score " << min << endl; cout << "\nHigh score " << max << endl; cout << "\nAverage score = " << average << endl; } else { cout << "\nCould not open the file..."; } theFile.close(); }
Not sure where to go from here... :( | https://www.daniweb.com/programming/software-development/threads/61755/need-some-help-with-student-grade-program | CC-MAIN-2018-43 | refinedweb | 533 | 70.94 |
IntelEdisonarunquest Nov 4, 2015 9:30 PM
What are the advantages of inteledison over other widely availa boards in the market?
1. Re: IntelEdisonarunquest Nov 4, 2015 9:40 PM (in response to arunquest)
Hi,
My intention is to send some data to cloud and retrieve data from cloud using inteledison board??
Please help me ... What all things i need to do??
2. Re: IntelEdisonarunquest Nov 4, 2015 10:28 PM (in response to arunquest)
Hi,
Can anyone give me the answer. I am new with this Iot ?? Please
3. Re: IntelEdisonmhahn Nov 5, 2015 12:37 AM (in response to arunquest)
I'd recommend starting with e.g.
4. Re: IntelEdisonarunquest Nov 5, 2015 1:48 AM (in response to mhahn)
Hi,
Thank you for the reply.
I have gone through the links.
I would like to use Arduino IDE and an Intel-Edison board. How can i program it to send data (lets say a character) to the intel cloud??
Does it use TCP/IP or any other protocol to send the data???
Looking forward for your reply.
5. Re: IntelEdisonmhahn Nov 5, 2015 4:22 AM (in response to arunquest)
well, there are also tutorials and docs, e.g.:
6. Re: IntelEdisonarunquest Nov 5, 2015 4:38 AM (in response to mhahn)
Thanks.
I got sample codes while i installed arduino ide for inteledison board.
In sample code for sending and receiving data to the cloud, we need to specify server name, ip address..
How can i get an account on Intel cloud so i can specify those address in program??
Do you have any code for reference??
Looking forward for your reply.
7. Re: IntelEdisonIntel_Alvarado Nov 5, 2015 8:48 AM (in response to arunquest)
Take a look at Intel® IoT Platforms: Getting Started: Cloud Analytics | Intel® Developer Zone . Section 1 describes how to set your account.
Sergio
8. Re: IntelEdisonarunquest Nov 5, 2015 9:22 PM (in response to Intel_Alvarado)
Thank you.
The sample code to send data through Wi-Fi need to enter following details:
1. Network SSID (name).
2. Secret Password
How can i get all these details??
Before running this code,whether i need to setup something on this board to get those details?? The code is as follows :
/**********************************************************************Sample code***********************************************************************************************/
#include <SPI.h>
#include <WiFi.h>
#include <WiFiUdp.h>
int status = WL_IDLE_STATUS;
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "secretPassword"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
unsigned int localPort = 2390; // local port to listen on
char packetBuffer[255]; //buffer to hold incoming packet
char ReplyBuffer[] = "acknowledged"; // a string to send back
WiFiUDP Udp;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo
int len = Udp.read(packetBuffer,255);
if (len >0) packetBuffer[len]=0;
Serial.println("Contents:");
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
Udp");
}
9. Re: IntelEdisonmhahn Nov 5, 2015 11:04 PM (in response to arunquest)
did you read through Sergio's link? Everything's described there.
10. Re: IntelEdisonarunquest Nov 5, 2015 11:25 PM (in response to mhahn)
Yes I read it.
I have some theoretical doubts:
1. I think there are different cloud services such as google drive etc.Can we send data to any cloud service with this Intel Edison Board??? Do we need to specify anything to find our cloud??
2. What is the format to send data to cloud?? How to specify the data i send is of the particular category??
May be these are foolish questions. I am a beginner in this. it would be grateful if you help me with these doubts.
11. Re: IntelEdisonIntel_Alvarado Nov 10, 2015 10:04 AM (in response to arunquest)
- You should be able to use another cloud service, however this means you’d probably have to do additional work. In the Intel Cloud you already have the functionality of the IoT agent. Look at enableiot/iotkit-samples · GitHub .
- The protocols supported for communication are UPD and TCP. You can send data through Java Script. Through JavaScript you can reach the cloud and configure the settings. In other cloud services, you may not have all the functionality you need ready to go, you’d probably need to install packages or libraries to fully interact with your board.
Sergio | https://communities.intel.com/thread/90472 | CC-MAIN-2018-13 | refinedweb | 749 | 66.64 |
If you are familiar with the concept of pointers, then you probably won’t have any problems understanding the principles by which linked lists work.
Basically, a linked list is an array of objects that however, is quite different from a simple array. A regular array allocates a specific part of the memory automatically. Let’s look at an example:
string[] dataSet = new string[100];for (int i = 0; i < 99; i++){ dataSet[i] = string.Format("Sample Data {0}", i.ToString());}
This code allocates space for 100 string items and fills each one of them with a string. However, there are a few drawbacks in the regular array. What if there are more than 100 items used later on? The array needs to be extended, and if it was hardcoded to a hundred values, there could be some problems with overflowing data. Another problem is the inefficient memory usage when there are less than a hundred elements. In that case, a lot of memory is kept unused.
Linked lists tend to solve the two of the above problems. First of all, a linked list doesn’t have a single field for a value, but rather two – one with the stored data and one referencing the next value. These two fields together build a node, that is – a unit inside the linked list.
Values aren’t stored in any particular order, however the reference to the next value helps finding and inserting the needed values much easier.
In C#, linked lists are handled via the LinkedList<T> class, that contains multiple LinkedListNode<T> instances. After disassembling the LinkedListNode<T>, there is an interesting thing seen:
Take a look at the highlighted fields - in .NET, a linked list node not only keeps a reference to the next node, but also to the previous node. In this case, the linked list scheme shown above would look like this:
Since values 1 and 6 are the limits of the list, for the first element the previous node is equal to NULL, and for the last element the next node is equal to NULL.
To instantiate a linked list, you can use the following code:
LinkedList<string> list = new LinkedList<string>();
The LinkedList<T> class represents a generic collection (member of the System.Collections.Generic namespace), therefore it is safely typed – when used, the developer is aware of the type of the elements inside it.
Since elements are added without an order, every node needs a reference. Initially, you can add nodes via the AddFirst and AddLast methods. For example:
list.AddFirst("Data Value 1");list.AddLast("Data Value 6");
Even if there is already a first and last element, the new node will replace the existing one and the list will adjust accordingly. To prove this, try this code:
list.AddFirst("Data Value 1");list.AddFirst("Data Value 2");LinkedListNode<string> node = list.Find("Data Value 1");Debug.Print(node.Previous.Value.ToString());
Since the node containing “Data Value 2” is placed first, the node containing “Data Value 1” is moved to the second spot. Therefore, the Previous property is automatically set to the new node that was inserted.
Same applies to the AddLast method, although the Next property will be the one modified.
When you want to add nodes between the first and last, you can use the AddBefore and AddAfter methods. AddBefore will add a node before the LinkedListNode instance that you are going to pass and AddAfter will add a node after it.
A way to specify the initial node, that will be considered for the Previous property assignment, the Find and FindLast methods can be used. Find finds the first occurring instance of the node and FindLast finds the last instance of the occurring node, since nodes can have the same value.
Here is a sample on how to use the methods mentioned above:
list.AddAfter(list.Find("Data Value 1"), "Data Value 2");
You have to be very careful when you are looking for a node since if you don’t specify the correct searched value, a null value will be returned and this will cause an exception, since the value cannot be null.
Since the list is not sorted and the values are added dynamically, there is no way to get them by the index, since no actual index value exists for nodes. The only way to find a value is by using the linear search, and that is provided by the Find and FindLast methods.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/introduction-linked-lists-c | CC-MAIN-2018-09 | refinedweb | 760 | 62.38 |
CodePlexProject Hosting for Open Source Software
(Sorry I couldn't find a better title.)
My project has the following structure:
I'd like to the following to happen:
So basically I'd like to change which BaseDependency gets injected into HomeController based on whether TopModuleA or TopModuleB is "active". I thought the above would simply work but it doesn't and I'm quite clueless how it could. Anybody has an idea?
Maybe the problem is that the order in which dependencies are resolved is depending on in which order they're registered (after figuring out module dependencies). Since registration happens on shell start, TopModuleB's TopDependencyB will get registered
last, so it "wins" every time.
Thank you for everyone who makes time to read my question.
Yup, dependencies are shell-wide and which injections you get is irrespective of which module is getting routed.
I'm creating this crazy little module called "Alchemy" which will be perfect for creating flexible, pluggable routes like this ... but it's not exactly production code yet.
The best thing you can do here is have a single controller which accepts a string parameter, and pass that parameter in your route. Then look up in a list of dependencies for anything matching that string key to find the correct dependency for that route.
(This is essentially what Alchemy is doing, but in a vastly generalised form, with a ridiculous amount of pluggability).
Thanks, that's what I feared. The solution I came up with is the following:
Pass a parameter in the Route's dataTokens indicating upon which module the controller is executing (fortunately there was already a RoutesBase to handle the common tasks), then...
and then load the appropriate BaseDependency depending on the content of the dataToken (fortunately a locator to do this was also already written). It gets a bit more complex as the BaseDependency instance should be injected into a number of other services
as well that are required by HomeController, so either...
I'm still wondering what the best approach would be, but I think the nicest way would be to change the registered implementation in Autofac before HomeController gets instantiated, but I haven't found a way to do it and I begin to doubt whether there's any
way to do this in ASP.NET MVC without a custom controller factory (or modifying Global.asax, which is not really an option here).
P.S.: Your modules' names are cool :-).
I think trying to coax Autofac into giving you the right dependency at the right time might be a convoluted and problematic way to implement what you're after, and to me it sounds like it could be slightly contrary to the principles of dependency injection
(of course, I don't know exactly what you're trying to achieve).
Let's start with the facts: you have an identifier key, which is a simple string. This is available in your controller action (you don't need a filter or anything special, it can just be an ordinary parameter of your action method).
You then require various behaviours to change depending on the value of this key. Instead of trying to "cheat" dependency injection to get the different behaviours, why not just have your various dependencies expose a GetIdentifier() method. Then any time
you need one, you can just enumerate an IEnumerable<IMyDependency> to check for the one that matches the identifier on the current request. Obviously the methods on any services or whatever you might have will also need a parameter to pass in this identifier,
so they themselves can look up the correct dependency.
It might be a little more work doing things this way, but you won't have to do any custom manipulation of Autofac, and it'll leave you the most flexibility in how you (or others) reused those services or dependencies in other places.
A lot of existing modules do very much the same thing, off the top of my head the Forms module uses a string key for the form name. In fact, each form handler runs, and it's up to that handler to decide whether or not to participate, based on the current
form key. This is really the principle of dependency injection when you're dealing with multiple behaviours (rather than single services); you shouldn't be telling the system
which one to run, just let them all run and they can choose whether or not to modify a context object that you pass in.
Hope that makes sense; I can elaborate with further examples if needed!
Piedone wrote:
P.S.: Your modules' names are cool :-).
Thanks - some people just find them confusing ;) I spend probably too much time figuring them out. Actually, "Alchemy" is one I wanted to have for quite a while, but I only just worked out the functionality to go in it. Almost a case of the name driving
the feature ... But there's an underlying pattern. These are all "Science Project" modules, so each module is named after some distinct branch of scientific or at least academic thinking; Mechanics, Cartography, Origami (the science of shape folding...)
Very valid points, thanks again for you insightful help! I think what I'm trying to achieve does make sense here:
Imagine the HomeController here as something that outputs information about a BaseDependency instance. Now it can output this about any registered instance, but only about one at a time. That means, there can be an arbitrary number of BaseDependencies floating
around in Autofac and I'd like to choose one and use it in the controller. So I think the principles of DI are not violated here; this use case here is like a plugin system were plugins are auto-discovered but you have to choose one to use at a time (but there
is no assumption made about the plugins, i.e. there is no hard-coded plugin list, really there could be arbitrary plugins).
The way I'm trying to achieve the above goal might be awkward, but the principle is much like the one with IHtmlFilters (I haven't looked into Forms, but from your description filters work quite the same). (This is going a bit away from the original question
and will be a bit philosophical :-); it also adds information about the objects I use here, that are superfluous to the question.) The difference is, that not all registered BaseDependencies are run and they decide whether they should run or not but rather
all BaseDependencies expose information what they're capable of doing and the consuming part decides which one to run. This is really what you described in the paragraph "You then require various behaviours...": to be honest, the registered objects have an
identifier (used by the specific case described in the question) and also "capabilities" for the previously mentioned scenario.
Actually after re-reading your post I see that not this was what bothered you with my proposed solution (so just treat the previous paragraphs as general ideas) but the way I wanted to trick Autofac. Yeah, it's not a nice approach; the thing is, if I'd like
to create a kind of scope for the controller (I know scopes are possible with Autofac but I really can't apply them to this scenario as I don't know how I could let some code run just before controller instantiation), so all the action happening in it doesn't
have to think about choosing the right dependency corresponding to the identifier. So the purpose of having the "choosing algorithm" at the point happening the earliest in the page life cycle possible is to keep all the underlying services or even the used
constructor as simple as possible. Just as a side note, but these services can be used independently too with arbitrary BaseDependency implementations, that are changeable also between two method calls.
Hope that makes sense...
I've taken a look at Alchemy, still trying to understand it :-).
This really does sound like exactly the set of problems I've tried to generalise with Alchemy. If you haven't seen it I wrote an overview and some basic examples here:
In a nutshell it's an idea I'm calling "Factory Injection". It has a specific concept of "Scope" (otherwise called "Context", or "Input") which consists of any number of types or string/object pairs you like. Alchemy factories can be described with statements
of the following form:
"Given [scope] the method to produce [type] is [func]"
A process is broken down into a chain of object factories. Any of those factories can then be swapped out for different implementations, based on the scope. The idea is to break the process into as small individual factory units as possible, so later on
you can swap out any piece of the chain you like. So it's like injecting individual statements into a method, rather than injecting or overriding entire classes as with normal dependency injection.
Regarding your original problem:
Yes it's a bit like IHtmlFilter, and some other dependencies in Orchard. I'll just quote the method signature of IHtmlFilter:
public interface IHtmlFilter : IDependency {
string ProcessContent(string text, string flavor);
}
And here's some code that uses it:
var bodyText = _htmlFilters.Aggregate(part.Text, (text, filter) => filter.ProcessContent(text, GetFlavor(part)));
And here's an example IHtmlFilter implementation:
public class MarkdownFilter : IHtmlFilter {
public string ProcessContent(string text, string flavor) {
return flavor.Equals("markdown", StringComparison.OrdinalIgnoreCase) ? MarkdownReplace(text) : text;
}
private static string MarkdownReplace(string text) {
if (string.IsNullOrEmpty(text))
return string.Empty;
var markdown = new MarkdownSharp.Markdown();
return markdown.Transform(text);
}
}
(I realise you've probably seen all this, but I'm just quoting for clarity).
Now there's nothing especially complex here, the underlying services and constructors are very simple. All that happens is a string comparison to see if the flavor is correct before the IHtmlFilter runs. The BodyPart runs
all IHtmlFilters but any that don't apply will just return the unmodified text, however multiple IHtmlFilters are still allowed to participate.
Let me just reiterate what DI is about: the caller should know nothing about the implementations that it's calling. The trick is to expose interfaces in such a way that you can blindly call whatever implementations are available; and it's up
to those implementations to do the right thing with the data you make available to them (or other data they may acquire themselves through other dependencies, which again you can make no assumptions about). By pre-selecting a particular dependency you are
already assuming some knowledge about which of those dependencies might apply.
Quick example: what if someone wanted to implement a BaseDependency to handle
multiple routes? With the IHtmlFilter it's easy, you can check for multiple flavors, or even catch all of them (which the BBCodeFilter actually does).
Of course this is all pretty much abstract and philosophical because I still know nothing about the specific problem you're trying to solve, but by trying to inject in a different way for what seems to be a very small saving in code you could well be boxing
yourself into a corner ;) (And yes, reading that statement back it sounds somewhat hypocritical, because I've already been discussing my own way of reinventing injection!)
Thanks again for the well thought-through input!
To concretize a bit (I'm not pretending the software I'm developing is a secret - although it's not ready for publishing yet -, but it's fairly complex and I try to omit details not needed),). So basically what happens here is just that I'd like to set the current context for the controller.
Now this indeed sounds much like part of what Alchemy does, as far as I know.
Thinking further a bit now I think what I really need is to be able to choose the interface of the IBaseDependency (edited the original question a bit) derivatives to inject into the controller (or any other services). This would of course narrow down injectable
dependencies (meaning, now HomeController would request e.g. an ITopDependencyA in the constructor), but these would still be changeable by registering another ITopDependencyA implementation. Just thinking aloud...
I've also seen that the controller in Alchemy (more precisely, DisplayController's Index() method) acts like a kind of dispatcher if I understand correctly. This is what I tried to achieve in a different was previously (meaning there's a dispatcher controller
that gets called to set the context for HomeController, than hands the control over to HomeController), but it was awkward, a bit slow and I couldn't get theming work properly. Maybe I should look into dynamic proxies used also in Orchard.
You could definitely use Alchemy for this, although I still maintain as far as the information you've given here goes you can achieve all of this with straight dependencies, nothing special. It's no different to how loads of Orchard's modules already work;
especially some of the newer bits like Projections, Rules, Tokens, and Forms (and I've based my newer modules - mainly Autoroute and Alchemy, but also some other currently secret things - on very similar principles).
How these modules all work is that a Describe context is initially generated by the service, and all the available dependencies populate the describe object with their supported behaviours and other parameters. Note that at this point no "input"
or "scope" is available; the handlers are just describing what they are capable of (and what scope(s) they support). Also note that no DB access is performed during description, in fact very little work is performed at all, so this stage is very quick, they
are just populating some lists and dictionaries with strings, delegates, etc.
Now the service wants to perform a task. So it looks through the description context it has built, finds any items matching the scope which is now available, and executes the delegates or performs other operations as appropriate.
To my mind this exactly matches what you require: )."
All you need is a central service to function as the switch box (dispatcher), which your controller or any of your other services can call into to get the correct behaviour.
In the cases of all the modules I just mentioned, the service is acting as a dispatcher. Even in Alchemy; the dispatching isn't performed from the controller, it's performed by the IAlchemyService. The controller is simply invoking a call to
the service, providing inputs, and handling the output.
You might want to look in detail through the code and interfaces for Rules and Tokens, they're in my opinion the cleanest and simplest examples of this kind of describe / dispatch behaviour, all using perfectly normal dependencies (usually an IEventHandler
because this means you can often utilise the message bus instead of having a hard project reference).
Thanks for all your help!
The solution I ended up after iterating over two other is pretty much the one you advised in your first answer. (The description following is again abstracted and simplified, but I hope it shows the point).
So the configuration/provider/descriptor objects, auto-discovered as dependencies (IBaseDependency implementations, from the original question) have public properties, storing among others the meta data that describes which HomeController they support (as
they can also be more HomeControllers):
Downside is that if there's a need for a new config value the interface has to change.
There's a service that gets the lastly registered provider for a controller with something along the lines of ProviderService.FindProvider(string controller).
I evaluated also two other approaches:
A simplified version of e.g. how Tokens work:
The provider only has a Describe(ProviderDescriptor descriptor) method. The ProviderDescriptor object is a blank object that the code inside Describe can fill up with the values mentioned above. Now this approach is nice, simple and flexible but I really
disliked the idea that the ProviderDescriptor object's properties all should have public setters or a method that lets you overwrite its content. I wanted these descriptors to be practically immutable once set up.
The approach of Tokens:
It has all the flexibility of the previous but I felt that in my case the result became bloated.
Also there's a problem with the last two approaches: there's also a need for custom config values for the different controllers, e.g. one controller would need a long ConfigValue4 too (these values are arbitrary so there's no possibility to store them in
a common datatype without constantly casting to and from object). The most straightforward way of achieving that the controllers can fetch a provider with their own custom type (which is a derivation of the common one) from the same service (so without a need
to write too much custom code for every controller) was with the first solution. This way a generic service method cuts it:
ProviderService.FindProvider<TProvider>(string controller)
This returns the lastly registered provider that's assignable to TProvider.
I hope the above compilation will also help someone decide which is the best approach for them when in a similar situation.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | https://orchard.codeplex.com/discussions/286288 | CC-MAIN-2016-50 | refinedweb | 2,908 | 57.71 |
Smart Appliance Switch
Introduction: Smart Appliance Switch
Easy to use device that turns on appliance when it is dark and movement is detected. I use it to turn on light when I go at night from one room to another.
We will define "device" as this Arduino-based project (Smart Appliance Switch - SAS) you are about to create and "appliance" as everything that you want to turn on/off (for example, a lamp).
SAS features 3 different modes:
- default mode - turns on after you power up device. Light threshold is hard coded, you may need to change it;
- permanent mode - appliance is permanently turned on;
- manual mode - you set light threshold by pressing a button and fine tuning it with potentiometer. Current level of light will be threshold.
It has 1 switch that turns device on/off, 2 buttons that change mode, 1 knob to fine-tune light threshold.
Word of caution: this device operates with high voltage which may be deadly for humans. Unless you are a certified electrician (I am not), test circuit and relay using 5 - 9 V electric current. Only after you have clear understanding of what you are doing and your small voltage test circuit works, you may carry on. Don't forget to insulate all connections.
Step 1: What You Need
In brackets I indicate parts that I have used in my device, if there was a name or a value.
- Arduino board (UNO, although on my photos you may see Leonardo)
- Arduino power adapter
- Relay (SONGLE SRD-05-VDC-SL-C)
- Potentiometer (250 kOm)
- 2 buttons
- 1 switch
- Plastic case (85x85x55 mm)
- Wires (22 AWG for all parts that are connected to Arduino. Wires that conduct high voltage must have bigger diameter and depend on appliance you are going to control. If you are not sure, use the same wires as in your home sockets).
- Plug that you are able to take apart and make two parts from it or two independent plugs.
- Resistors (3 pcs - 1 kOm, 1 pc - 1MOm)
- Passive infrared sensor PIR (HC-SR501)
- Photocell
- LED
- Protoshield (optional but very convenient)
- 4 and 2 - way stereo speaker terminal plate (optional)
- Screws (better plastic)
Step 2: Wiring Up
You may see how to connect everything together on diagram.
All the necessary information I got from Adafruit:
About relays you may read here
Some notes:
- LED turns on when permanent mode is on.
- Relay has jumper - put it in LOW position.
- I use 1 MOm resistor with photocell, because this way it's possible to distinguish better between "it's dark but I see where I am going" and "I can't see a thing". Read more about it on Adafruit via the link above.
- 250 kOm potentiometer gives quite wide range by which you may increase or decrease threshold during twilight.
- PIR has 2 adjustable knobs: delay time and sensitivity. I turned it all the way down counter clockwise.
At this stage I strongly suggest you assemble only parts which are connected to breadboard on the picture. Make another simple circuit with battery and LED and connect it to the relay.
Step 3: Coding
At first logic seemed straightforward: if it's dark and there is movement - turn on the appliance (lamp in my case), otherwise turn it off. Wait n seconds and check again.
But as I was testing and adding new modes to my device, none of above mentioned worked that simple.
You can't use if (dark == true && movement == true) then {turn on} else {turn off}; delay (n);
because you will get nasty feedback effect: dark? - yes, movement? - yes then turn it on; wait; dark? - no (because we have just turned on the lights), movement? - yes then turn it off; dark? - yes ... So with this logic you will get constant blinking.
That's why in procedure light_on() first we check if it is dark and then go into loop, switching on light and constantly checking if motion is present. We don't check these two conditions simultaneously.
As for command delay (n), which pauses execution for n milliseconds, we can't use it because during delay, if you press permanent or manual mode buttons, Arduino will not notice it, because it sleeps. That is why we use in the same loop, which checks for motion in light_on () procedure, function millis() and assign it's value to variable "now". Millis() returns number of milliseconds that passed since Arduino was turned on. This way we are able to get out of loop when now + delay_time > millis().
So, all conditions to get out of loop in light_on() procedure:
- there is no movement;
- delay_time has passed since last time movement was detected;
- device mode was changed by pressing one of the buttons.
Other comments I included in code itself.
I made two classes: photocell and pir.
For button debouncing I use Bounce2 library that you can download from here. Download library and unpack its contents into ~/Documents/Arduino/libraries (on a Mac) or My Documents\Arduino\libraries (on a Windows machine).
<p>//#define __DEBUG__ // uncomment this define for debugging information in serial monitor<br>#include "Bounce2.h" #include "photocell.h" #include "pir.h"</p><p>//SETUP const unsigned int PHOTOCELL_PIN = A0; const unsigned int RELAY_PIN = 10; const unsigned int PERMANENT_LED_PIN = 13; const unsigned int PERMANENT_MODE_PIN = 12; const unsigned int MANUAL_MODE_PIN = 11; const unsigned int PIR_INPUT_PIN = 2; const unsigned int BAUD_RATE = 9600; const unsigned int LIGHT_DELAY = 5000; const unsigned int DEBOUNCE_DELAY = 20; const int DEFAULT_THRESHOLD = 130; //SETUP</p><p>int threshold = 0; Bounce permanent_mode_button, manual_mode_button; boolean button_state = false; photocell p_cell(PHOTOCELL_PIN); PIR ir_sensor(PIR_INPUT_PIN); enum modes {default_, permanent, manual, threshold_changed}; // we also need to be able to determine, when during manual mode, manual mode button was pressed again int prev_mode = default_; int mode = default_;</p><p>//check state of button boolean button_pressed(Bounce& button, boolean& state) { if (button.update() && button.read() == 1) { state = !state; } return state; }</p><p>//determine current mode int check_mode() { if (button_pressed(permanent_mode_button, button_state)) mode = permanent; // permanent mode button pressed</p><p> else if (manual_mode_button.update() && manual_mode_button.read() == 1) { threshold = p_cell.value();</p><p>#ifdef __DEBUG__ Serial.println("threshold: " + String(threshold)); #endif</p><p> mode = threshold_changed; // threshold was changed }</p><p> else if (threshold > 0) { mode = manual; // manual mode }</p><p> else mode = default_; // default mode</p><p> return mode; }</p><p>//check, wheter mode was changed bool mode_changed() { if (prev_mode != check_mode()) { prev_mode = check_mode();</p><p>#ifdef __DEBUG__ Serial.println("true, previous mode: " + String(prev_mode)); #endif return true; } else { #ifdef __DEBUG__ Serial.println("false, previous mode: " + String(prev_mode)); #endif return false; } }</p><p>//turn on the light void light_on (int threshold, const unsigned int& pin, const unsigned int& delay_time) { digitalWrite (PERMANENT_LED_PIN, 0); if (p_cell.value() <= threshold) {</p><p> unsigned long now = 0; boolean mode_change = mode_changed();</p><p> for (; ((ir_sensor.motion_detected() && !mode_change) && (now = millis())) || ((millis() < (now + delay_time)) && !mode_change); mode_change = mode_changed()) { digitalWrite(pin, 1); // we get out of this loop when there is no movement or device mode was changed or delay time has passed #ifdef __DEBUG__ Serial.println("inside loop, motion: " + String(ir_sensor.motion_detected())); Serial.println("now: " + String(now)); #endif } digitalWrite(pin, 0); } digitalWrite(pin, 0); }</p><p>void setup() { #ifdef __DEBUG__ Serial.begin(BAUD_RATE); #endif permanent_mode_button.attach(PERMANENT_MODE_PIN); permanent_mode_button.interval(DEBOUNCE_DELAY); pinMode(PERMANENT_MODE_PIN, INPUT); manual_mode_button.attach(MANUAL_MODE_PIN); manual_mode_button.interval(DEBOUNCE_DELAY); pinMode(MANUAL_MODE_PIN, INPUT); pinMode(RELAY_PIN, OUTPUT); pinMode(PERMANENT_LED_PIN, OUTPUT); }</p><p>void loop() { if (mode == permanent) { digitalWrite(RELAY_PIN, 1); digitalWrite(PERMANENT_LED_PIN, 1); #ifdef __DEBUG__ Serial.println("permanent mode on"); #endif }</p><p> else if (mode == manual) { #ifdef __DEBUG__ Serial.println("manual mode on"); #endif light_on (threshold, RELAY_PIN, LIGHT_DELAY); }</p><p> else if (mode == default_) { #ifdef __DEBUG__ //Serial.println("default mode on"); Serial.println("value: " + String(p_cell.value())); #endif light_on (DEFAULT_THRESHOLD, RELAY_PIN, LIGHT_DELAY); } check_mode(); }</p>
photocell.h
<p>#include "arduino.h"</p><p>class photocell { private: unsigned int _pin; int buffer_size;</p><p> public: photocell(const unsigned int pin) { _pin = pin; buffer_size = 10; }</p><p> int value () { float sum = 0; for (int i = 1; i <= buffer_size; i++) { //we use buffer to get nice average value sum += analogRead(_pin); } return round(sum / buffer_size); } };</p>
pir.h
<p>#ifndef __PIR__<br>#define __PIR__ #include "arduino.h"</p><p>class PIR { int _input_pin;</p><p> public: PIR(const unsigned int input_pin) { _input_pin = input_pin; pinMode(_input_pin, INPUT); }</p><p> bool motion_detected() { return digitalRead(_input_pin) == HIGH; } }; #endif</p>
That's all the code you need. Now you may upload it to your Arduino and test, whether everything works as it should, before dealing with high voltage and assembling case for your device.
Also I attached files with codes. On my machine everything compiles without problems.
Step 4: Assembling Case
Everything is pretty straightforward. If necessary, make adjustments for your convenience, for example, if you are left-handed.
It's good idea to use protoshield, where you can nicely solder resistors and wires.
On the bottom of the device I use 4 and 2-way stereo speaker terminal plate, with it you can easily attach and remove photocell and PIR.
On the sides I made some holes for the air to flow, because power adapter heats when in use.
Don't forget that you need wire with bigger diameter to connect all parts through which high voltage will flow. If you are not sure, take wires that are normally used to connect your home sockets.
Don't forget to insulate all contacts inside the device. Also I strongly recommend to solder everything.
There are some metal parts that you may still touch when the case is closed (for example, screws with which I attached Arduino and relay to the lid). It is really a good idea to use plastic screws. In my case when everything was finished, I insulated them too.
Finally, there must be no metal parts that you can touch with your body. This device is not grounded, so better not to risk.
Step 5: Afterword
This is my first device which I use every day and I got really a lot of fun assembling it. Please, do not spoil my fun by hurting yourself. If you don't know something or aren't sure, please, stop at once and ask somebody for help. You still can test and experiment using only Arduino and breadboard.
Although my device works well for quite some time now and behaves exactly as I intended, I am no electrician nor programmer. I would be really grateful, if you could share with me some of your thoughts on my device. Thank you.
Great home automation project! Thank's !
Сразу слышен жестокий Русский акцент!!!)) теперь все тоже самое но на русском))
Thank's guys! I have added video.
very good
Great home automation project! Another use of the arduino microcontroller.
Smart
Great Arduino controller. These are perfect for making ordinary appliances smart. | http://www.instructables.com/id/Smart-Appliance-Switch/ | CC-MAIN-2018-05 | refinedweb | 1,791 | 55.54 |
Suppose we have an array nums with positive values, we have to find a pattern of length m that is repeated k or more than k times. Here a pattern is a non-overlapping subarray (consecutive) that consists of one or more values and are repeated multiple times. A pattern is defined by its length and number of repetitions. We have to check whether there exists a pattern of length m that is repeated k or more times or not.
So, if the input is like nums = [3,5,1,4,3,1,4,3,1,4,3,9,6,1], m = 3, k = 2, then the output will be True because there is a pattern [1,4,3] which is present 3 times.
To solve this, we will follow these steps −
for i in range 0 to size of nums - 1, do
sub1 := sub array of nums from index i to (i+m*k) - 1
sub2 := k consecutive sub array of nums from index i to (i+m-1)
if sub1 is same as sub2, then
return True
return False
Let us see the following implementation to get better understanding −
def solve(nums, m, k): for i in range(len(nums)): sub1 = nums[i:i+m*k] sub2 = nums[i:i+m]*k if sub1 == sub2: return True return False nums = [3,5,1,4,3,1,4,3,1,4,3,9,6,1] m = 3 k = 2 print(solve(nums, m, k))
[3,5,1,4,3,1,4,3,1,4,3,9,6,1], 3, 2
True | https://www.tutorialspoint.com/program-to-check-pattern-of-length-m-repeated-k-or-more-times-exists-or-not-in-python | CC-MAIN-2021-39 | refinedweb | 262 | 62.55 |
check_jmx4perl - Nagios plugin using jmx4perl for accessing JMX data remotely
# Check for used heap memory (absolute values) check_jmx4perl --url \ --name memory_used \ --mbean java.lang:type=Memory \ --attribute HeapMemoryUsage \ --path used \ --critical 10000000 \ --warning 5000000 # Check that used heap memory is less than 80% of the available memory check_jmx4perl --url \ --alias MEMORY_HEAP_USED \ --base MEMORY_HEAP_MAX \ --critical :80 # Use predefined checks in a configuration file with a server alias # Server alias is 'webshop', check is about requests per minute for the # servlet 'socks_shop' check_jmx4perl --config /etc/nagios/check_jmx4perl/tomcat.cfg --server webshop \ --check tc_servlet_requests \ --critical 1000 \ socks_shop # Check for string values by comparing them literally check_jmx4perl --url \ --mbean myDomain:name=myMBean \ --attribute stringAttribute \ --string \ --critical 'Stopped' \ --warning '!Started' # Check that no more than 5 threads are started in a minute check_jmx4perl --url \ --alias THREAD_COUNT_STARTED \ --delta 60 \ --critical 5 # Execute a JMX operation on an MBean and use the return value for threshold # Here a thread-deadlock is detected. check_jmx4perl --url \ --mbean java.lang:type=Threading \ --operation findDeadlockedThreads \ --null no-deadlock \ --string \ --critical '!no-deadlock' \ --critical 10 # Use check_jmx4perl in proxy mode check_jmx4perl --url \ --alias MEMORY_HEAP_USED \ --critical 10000000 \ --target service:jmx:rmi:///jndi/rmi://bhut:9999/jmxrmi application server this is a simple webapplication packaged as a
war archive. For other platforms, other agents are available, too. Please refer to the
README for installation instructions and the supported platforms.
check_jmx4perls can also be used in an agentless mode (i.e. no agent needs to be installed on the target platform). See "Proxy mode" for details.
This plugin can be configured in two ways: Either, all required parameters for identifying the JMX information can be given via the command line. Or, a configuration file can be used to define one or more Nagios checks. This is the recommended way, since it allows for more advanced features not available when using the command line alone. Each command line argument has an equivalent option in the configuration files, though.
This documentation contains four parts. First, a tutorial gives a 5 minute quickstart for installing and using
check_jmx4perl. The middle part offers some technical background information on JMX itself, the features provided by this plugin and finally the command line arguments and the configuration file directives are described.
Before we dive into the more nifty details, this 5 minutes quickstart gives a simple cooking recipe for configuration and setup of
check_jmx4perl.
$ tar zxvf apache-tomcat-*.tar.gz $ # We need this variable later on: $ TC=`pwd`/apache-tomcat*
$ tar zxvf jmx4perl-*.tar.gz $ cd jmx4perl* $ # Store current directory for later reference: $ J4P=`pwd` $ perl Build.PL $ sudo ./Build install
This is installs the Perl modules around
JMX::Jmx4Perl which can be used for programmatic JMX access. There are some CPAN dependencies for jmx4perl, the build will fail if there are missing modules. Please install the missing modules via cpan (
cpan module). The Nagios plugin
check_jmx4perl is installed in a standard location (/usr/bin, /usr/local/bin or whatever your Perl installation thinks is appropriate) as well as the other scripts
jmx4perl (a generic tool for accessing JMX) and
j4psh (an interactive JMX shell).
$ cd $TC/webapps $ jolokia
$ $TC/bin/startup.sh
$ jmx4perl
This prints out a summary about your application server. is the URL under which the agent is reachable. Tomcat itself listens on port 8080 by default, and any autodeployed war archive can be reached under its filename without the .war suffix (jolokia in this case).
$ check_jmx4perl --url \ --mbean java.lang:type=Memory \ --attribute HeapMemoryUsage \ --path used \ --base java.lang:type=Memory/HeapMemoryUsage/max \ --warning 80 \ --critical 90 OK - [java.lang:type=Memory,HeapMemoryUsage,used] : In range 9.83% (12778136 / 129957888) | '[java.lang:type#Memory,HeapMemoryUsage,used]'=12778136;103966310.4;116962099.2;0;129957888
where
is the agent URL
is the MBean name
is the attribute to monitor
is an inner path (see "Paths"), which specifies an inner value within a more complex structure. The value
HeapMemoryUsage is a composed value (Jav type: CompositeData) which combines multiple memory related data. The complete value can be viewed with jmx4perl:
$ jmx4perl read java.lang:type=Memory HeapMemoryUsage { committed => 85000192, init => 0 max => 129957888, used => 15106608, }
is the base value for which a relative threshold should be applied. This is a shortcut notation in the format mbean
/attribute
/path.
is the warning threshold in percent. I.e. a
WARNING will be raised by this plugin when the heap memory usage is larger than 80% of the maximal available heap memory for the application server (which is smaller than the available memory of the operating system)
is the critical threshold in percent. If the available heap memory reaches 90% of the available heap, a
CRITICAL alert will be returned.
All available command line options are described in "COMMAND LINE".
$ check_jmx4perl --url \ --config $J4P/config/tomcat.cfg \ --critical 100 \ --check tc_servlet_requests \ jolokia-agent OK - 15.00 requests/minute | 'Requests jolokia-agent'=15;5000;100
where
is the path to configuration file. There a several predefined checks coming with this distribution, which are documented inline. Look there for some inspiration for what to check.
A threshold von 100, i.e. the checked value must be 100 or less, otherwise a critical alert is raised.
is the name of the check to perform which must be defined in the configuration file
is an extra argument used by the predefined check. It is the name of the servlet for which the number of requests should be monitored. To get the name of all registered servlets use
jmx4perl list:
$ jmx4perl list | grep j2eeType=Servlet
The servlet name is the value of the
name property of the listed MBeans.
Configuration files are very powerful and are the recommended way for configuring
check_jmx4perl for any larger installation. Features like multi checks are even only available when using a configuration file. The syntax for configuration files are explained in depth in "CONFIGURATION".
define command { command_name check_jmx4perl_relative command_line $USER3$/check_jmx4perl \ --url $ARG1$ \ --mbean $ARG2$ \ --attribute $ARG3$ \ --path $ARG4$ \ --base $ARG5$ \ $ARG6$ }
Put this into place where you normally define commands (either in the global Nagios commands.cfg or in a specific commands configuration file in the commands directory).
$USER3 is a custom variable and should point to the directory where
check_jmx4perl is installed (e.g. /usr/local/bin).
The service definition itself then looks like:
define service { service_description j4p_localhost_memory host_name localhost check_command check_jmx4perl_relative \ ! \ !java.lang:type=Memory \ !HeapMemoryUsage \ !used \ !java.lang:type=Memory/HeapMemoryUsage/max \ !--warning 80 --critical 90 }
Add this section to your service definitions (depending on your Nagios installation). This example adds a service to host
localhost for checking the heap memory, raising a
WARNING if 80% of the available heap is used and a
CRITICAL if more than 90% of the heap memory is occupied.
Installing and using jmx4perl is really that easy. The Nagios configuration in this example is rather simplistic, of course a more flexible Nagios setup is possible. The blog post (written by Gerhard Lausser) shows some advanced configuration setup. (It is in german, but the automatic translation from seems to be quite usable).
This section explains the JMX basics necessary to better understand the usage of
check_jmx4perl. It tries to be as brief as possible, but some theory is required to get the link to the Java world.
JMX's central entity is an
MBean. An MBean exposes management information in a well defined way. Each MBean has a unique name called Object Name with the following structure:
domain:attribute1=value1,attribute2=value2, .....
E.g.
java.lang:type=Memory
points to the MBean which lets you access the memory information of the target server.
Unfortunately, except for so called MXBeans () there is no standard naming for MBeans. Each platform uses its own. There used to be a naming standard defined in JSR77 (), unfortunately it was never widely adopted.
There are various ways for identifying MBeans on a server:
jmx4perl --listto list all registered MBeans. In addition
jmx4perl --attributesdumps out all known MBean attributes along with their values. (Be careful, the output can be quite large)
j4pshfor interactively exploring the JMX namespace.
jmx4perl aliases. Since each platform can have slightly different MBean names for the same information, this extra level of indirection might help in identifying MBeans. See "Aliases" for more about aliases.
check_jmx4perlcomes with quite some checks predefined in various configuration files. These are ready for use out of the box. "Predefined checks" are described in an extra section.
check_jmx4perl can obtain the information to monitor from two sources: Either as MBean attributes or as a return value from JMX operations. Since JMX values can be any Java object, it is important to understand, how
check_jmx4perl (or jmx4perl in general) handles this situation.
Simple data types can be used directly in threshold checking. I.e. the following data types can be used directly
String and
Boolean can be used in string checks only, whereas the others can be used in both, numeric and string checks (see "String checks").
For numeric checks, the threhsholds has to be specified according to the format defined in
For more complex types,
check_jmx4perl provides the concept of so called paths for specifying an inner attribute of a more complex value. A path contains parts separated by slashes (/). It is similar to an XPath expression for accessing parts of an XML document. Each part points to an inner level of a complex object.
For example, the MBean
java.lang:type=Memory exposes an attribute called
HeapMemoryUsage. This attribute is a compound data type which contains multiple entries. Looking with
jmx4perl at this attribute
$ jmx4perl read java.lang:type=Memory HeapMemoryUsage { committed => 85000192, init => 0 max => 129957888, used => 15106608, }
it can be seen, that there are 4 values coming with the reponse. With a path
used one can directly pick the used heap memory usage (8135440 bytes in this case) which then can be used for a threshold check.
$ check_jmx4perl --url \ --mbean java.lang:type=Memory \ --attribute HeapMemoryUsage \ --path used \ --critical 100000000 OK - [java.lang:type=Memory,HeapMemoryUsage,used] : Value 10136056 in range | ...
Attributes are values obtained from MBean properties. Complex values are translated into a JSON structure on the agent side, which works for most types. To access a single value from a complex value, the path mechanism described above can be used. Thresholds can be applied to simple data types only, so for complex attributes a path is required.
The return values of operations can be used for threshold checking, too. Since a JMX exposed operation can take arguments, these has to be provided as extra arguments on the command line or in the configuration via the
Args configuration directive. Due to the agent's nature and the protocol used (JSON), only simple typed arguments like strings, numbers or booleans ("true"/"false") can be used.
Example:
$ check_jmx4perl --url \ --mbean jolokia:type=Runtime \ --operation getNrQueriesFor \ --critical 10 \ "operation" \ "java.lang:type=Memory" \ "gc"
This example contacts a MBean
jolokia:type=Runtime registered by the jolokia agent in order to check for the number of queries for a certain MBean via this agent. For this purpose an JMX operation
getNrQueriesFor is exposed which takes three arguments: The type ("operation"/"attribute"), the MBean's ObjectName and the operation/attribute name which was called.
If the operation to be called is an overloaded operation (i.e. an operation whose name exists multiple times on the same MBean but with different parameter types), the argument types must be given within parentheses:
--operation checkUserCount(java.lang.String,java.lang.String)
Aliases are shortcut for common MBean names and attributes. E.g. the alias
MEMORY_HEAP_MAX specifies the MBean
java.lang:type=Memory, the attribute
HeapMemoryUsage and the path
max. Aliases can be specified with the
--alias option or with the configuration directive
Alias. Aliases can be translated to different MBean names on different application server. For this
check_jmx4perl uses an autodetection mechanism to determine the target platform. Currently this mechanism uses one or more extra server round-trips. To avoid this overhead, the
--product option (configuration:
Product) can be used to specify the target platform explicitely. This is highly recommended in case you are using the aliasing feature.
Aliases are not extensible and can not take any parameters. All availables aliases can be viewed with
jmx4perl aliases
A much more flexible alternative to aliases are parameterized checks, which are defined in a configuration file. See "CONFIGURATION" for more details about parameterized checks.
Relative values are often more interesting than absolute numbers. E.g. the knowledge that 140 MBytes heap memory is used is not as important as the knowledge, that 56% of the available memory is used. Relative checks calculate the ratio of a value to a base value. (Another advantage is that Nagios service definitions for relative checks are generic as they can be applied for target servers with different memory footprints).
The base value has to be given with
--base (configuration:
Base). The argument provided here is first tried as an alias name or checked as an absolute, numeric value. Alternatively, you can use a full MBean/attribute/path specification by using a
/ as separator, e.g.
... --base java.lang:type=Memory/HeapMemoryUsage/max ...
If one of these parts (the path is optional) contains a slash within its name, the slash must be escaped with a backslash (\/). Backslashes in MBean names are escaped with a double backslash (\\).
Alternatively
--base-mbean,
--base-attribute and
--base-path can be used to specify the parts of the base value separately.
Example:
check_jmx4perl --url \ --value java.lang:type=Memory/HeapMemoryUsage/used \ --base java.lang:type=Memory/HeapMemoryUsage/max \ --critical 90 check_jmx4perl --url \ --value java.lang:type=Memory/HeapMemoryUsage/used \ --base-mbean java.lang:type=Memory \ --base-attribute HeapMemoryUsage \ --base-path max \ --critical 90
This check will trigger a state change to CRITICAL if the used heap memory will exceed 90% of the available heap memory.
For some values it is worth monitoring the increase rate (velocity). E.g. for threads it can be important to know how fast threads are created.
Incremental checks are switched on with the
--delta option (configuration:
Delta). This option takes an optional argument which is interpreted as seconds for normalization.
Example:
check_jmx4perl --url \ --mbean java.lang:type=Threading \ --attribute TotalStartedThreadCount \ --delta 60 \ --critical 5
This will fail as CRITICAL if more than 5 threads are created per minute (60 seconds). Technically
check_jmx4perl uses the history feature of the jolokia agent deployed on the target server. This will always store the result and the timestamp of the last check on the server side and returns these historical values on the next check so that the velocity can be calculated. If no value is given for
--delta, no normalization is used. In the example above, without a normalization value of 60, a CRITICAL is returned if the number of threads created increased more than 5 between two checks.
--delta doesn't work yet with
--base (e.g. incremental mode for relative checks is not available).
In addition to standard numerical checks, direct string comparison can be used. This mode is switched on either explicitely via
--string (configuration:
String) or by default implicitely if a heuristics determines that a value is non-numeric. Numeric checking can be enforced with the option
--numeric (configuration: Numeric).
For string checks,
--critical and
--warning are not treated as numerical values but as string types. They are compared literally against the value retrieved and yield the corresponding Nagios status if matched. If the threshold is given with a leading
!, the condition is negated. E.g. a
--critical '!Running' returns
CRITICAL if the value not equals to
Running. Alternatively you can also use a regular expression by using
qr/.../ as threshold value (substitute
... with the pattern to used for comparison). Boolean values are returned as
true or
false strings from the agent, so you can check for them as well with this kind of string comparison.
No performance data will be generated for string checks by default. This can be switched on by providing
--perfdata on (or "
PerfData on" in the configuration). However, this probably doesn't make much sense, though.
The output of
check_jmx4perl can be highly customized. A unit-of-measurement can be provided with the option
--unit (configuration:
Unit) which specifies how the the attribute or an operation's return value should be interpreted. The units available are
B - Byte KB - Kilo Byte MB - Mega Byte GB - Giga Byte TB - Terra Byte us - Microseconds ms - Milliseconds s - Seconds m - Minutes h - Hours d - Days
The unit will be used for performance data as well as for the plugin's output. Large numbers are converted to larger units automatically (and reverse for small number that are smaller than 1). E.g.
2048 KB is converted to
2 MB. Beautifying by conversion is only performed for the plugin output, not for the performance data for which no conversions happens at all.
Beside unit handling, you can provide your own label for the Nagios output via
--label. The provided option is interpreted as a pattern with the following placeholders:
%v the absolute value %f the absolute value as floating point number %r the relative value as percentage (--base) %q the relative value as ratio of value to base (--base) %u the value's unit for the output when --unit is used (after shortening) %w the base value's unit for the output when --unit is used (after shortening) %b the absolut base value as it is used with --base %c the Nagios exit code in the Form "OK", "WARNING", "CRITICAL" or "UNKNOWN" %t Threshold value which failed ("" when the check doesn't fail) %n name, either calulated automatically or given with --name %d the delta value used for normalization when using incremental mode %y WARNING threshold as configured %z CRITICAL threshold as configured
Note that
%u and
%w are typically not the same as the
--unit option. They specify the unit after the conversion for the plugin output as described above. You can use the same length modifiers as for
sprintf to fine tune the output.
Example:
check_jmx4perl --url \ --alias MEMORY_HEAP_USED \ --base MEMORY_HEAP_MAX \ --critical :80 \ --label "Heap-Memory: %.2r% used (%.2v %u / %.2b %w)" \ --unit B
will result in an output like
OK - Heap-Memory: 3.48% used (17.68 MB / 508.06 MB) | '[MEMORY_HEAP_USED]'=3.48%;;:80
Since the jolokia-agent is usually a simple war-file, it can be secured as any other Java Webapplication. Since setting up authentication is JEE Server specific, a detailed instruction is beyond the scope of this document. Please refer to your appserver documentation, how to do this. At the moment,
check_jmx4perl can use Basic-Authentication for authentication purposes only.
In addition to this user/password authentication, the jolokia-agent uses a policy file for fine granular access control. The policy is defined with an XML file packaged within the agent. In order to adapt this to your needs, you need to extract the war file, edit it, and repackage the agent with a policy file. A future version of jmx4perl might provide a more flexible way for changing the policy.
In detail, the following steps are required:
$ jolokia $ jolokia --policy
$ vi jolokia-access.xml
$ jolokia repack --policy jolokia.war
The downloaded sample policy file jolokia-access.xml contains inline documentation and examples, so you can easily adapt it to your environment.
Restrictions can be set to on various parameters :
Access to the jolokia-agent can be restricted based on the client IP accessing the agent. A single host, either with hostname or IP address can be set or even a complete subnet.
Example:
<remote> <host>127.0.0.1</host> <host>10.0.0.0/16</host> </remote>
Only the localhost or any host in the subnet 10.0 is allowed to access the agent. If the
<remote> section is missing, access from all hosts is allowed.
The access can be restricted to certain commands.
Example:
<commands> <command>read</command> </commands>
This will only allow reading of attributes, but no other operation like execution of operations. If the
<commands> section is missing, any command is allowed. The commands known are
Read an attribute
Write an attribute (used by
check_jmx4perl only when using incremental checks)
Execution of an operation
List all MBeans (not used by
check_jmx4perl)
Version command (not used by
check_jmx4perl)
check_jmx4perl)
The most specific policy can be put on the MBeans themselves. For this, two sections can be defined, depending on whether a command is globaly enabled or denied.
The
<allow> section is used to switch on access for operations and attributes in case
read,
write or
exec are globally disabled (see above). Wildcards can be used for MBean names and attributes/and operations.
Example:
<allow> <mbean> <name>jolokia:*</name> <operation>*</operation> <attribute>*</attribute> </mbean> <mbean> <name>java.lang:type=Threading</name> <operation>findDeadlockedThreads</operation> </mbean> <mbean> <name>java.lang:type=Memory</name> <attribute mode="read">Verbose</attribute> </mbean> </allow>
This will allow access to all operation and attributes of all MBeans in the
jolokia: domain and to the operation
findDeadlockedThreads on the MBean
java.lang:type=Threading regardless whether the
read or
exec command is enabled globally. The attribute
Verbose on
java.lang:type=Memory is allowed to be read, but cannot be written (if the
mode attribute is not given, both read and write is allowed by default).
The
<deny> section forbids access to certain MBean's operation and/or attributes, even when the command is allowed globally.
Example:
<deny> <mbean> <!-- Exposes user/password of data source, so we forbid this one --> <name>com.mchange.v2.c3p0:type=PooledDataSource*</name> <attribute>properties</attribute> </mbean> </deny>
This will forbid the access to the specified attribute, even if
read is allowed globally. If there is an overlap between <allow> and <deny>, <allow> takes precedence.
check_jmx4perl can be used in an agentless mode as well, i.e. no jolokia-agent needs to deployed on the target server. The setup for the agentless mode is a bit more complicated, though:
check_jmx4perlthe target JMX URL for accessing the target server is required. This URL typically looks like
service:jmx:rmi:///jndi/rmi://host:9999/jmxrmi
but this depends on the server to monitor. Please refer to your JEE server's documentation for how the export JMX URL looks like.
check_jmx4perluses the proxy mody if the option
--target(configuration: <Target>) is provided. In this case, this Nagios plugin contacts the proxy server specified as usual with
--url(config: Url in Server section) and put the URL specified with
--targetin the request. The agent in the proxy then dispatches this request to the real target and uses the JMX procotol specified with in the target URL. The answer received is then translated into a JSON response which is returned to
check_jmx4perl.
Example:
check_jmx4perl --url \ --target service:jmx:rmi:///jndi/rmi://jeeserver:9999/jmxrmi --alias MEMORY_HEAP_USED --base MEMORY_HEAP_MAX --critical 90
Here the host proxy is listening on port 8080 for jolokia requests and host jeeserver exports its JMX data via JSR-160 over port 9999. (BTW, proxy can be monitored itself as usual).
So, what mode is more appropriate ? Both, the agent mode and the proxy mode have advantages and disadvantages.
The agent protocol is more flexible since it translates the data into a JSON structure before putting it on the wire.
To summarize, I would always recommend the agent mode over the proxy mode except when an agentless operation is required (e.g. for policy reasons).
The pure command line interface (without a configuration file) is mostly suited for simple checks where the predefined defaults are suitable. For all other use cases, a configuration file fits better.
check_jmx4perl knows about the following command line options:
The URL for accessing the target server (or the jolokia-proxy server, see "Proxy Mode" for details about the JMX proxy mode)
Example:
--url
Object name of MBean to access
Example:
--mbean java.lang:type=Runtime
A MBean's attribute name. The value of this attribute is used for threshold checking.
Example:
--attribute Uptime
A MBean's operation name. The operation gets executed on the server side and the return value is used for threshold checking. Any arguments required for this operation has to be given as additional arguments to
check_jmx4perl. See "Attributes and Operations" for details.
Example:
check_jmx4perl ... --mbean java.lang:type=Threading \ --operation getThreadUserTime 1
Operation
getThreadUserTime takes a single argument the thread id (a long) which is given as extra argument.
Path for extracting an inner element from an attribute or operation return value. See "Paths" for details about paths.
Example:
--path used
Shortcut for giving
--mbean,
--attribute and
--path at once.
Example:
--value java.lang:type=Memory/HeapMemoryUsage/used
Any slash (/) in the MBean name must be escaped with a backslash (\/). Backslashes in names has to be escaped as \\.
Switches on relative checking. The value given points to an attribute which should be used as base value and has to be given in the shortcut notation described above. Alternatively, the value can be an absolute number or an alias name ("Aliases") The threshold are the interpreted as relative values in the range [0,100]. See "Relative Checks" for details.
Example:
--base 100000 --base java.lang:type=Memory/HeapMemoryUsage/max --base MEMORY_HEAP_MAX
Switches on incremental checking, i.e. the increase rate (or velocity) of an attribute or operation return value is measured. The value given here is used for normalization (in seconds). E.g.
--delta 60 normalizes the velocity to 'growth per minute'. See "Incremental Checks" for details.
Forces string checking, in which case the threshold values are compared as strings against the measured values. See "String checks" for more details. By default, a heuristic based on the measured value is applied to determine, whether numerical or string checking should be use
Example:
--string --critical '!Running'
Forces numeric checking, in which case the measured valued are compared against the given thresholds according to the Nagios developer guideline specification ()
Example:
--numeric --critical ~:80
The value to be used in case the attribute or the operation's return value is
null. This is useful when doing string checks. By default, this value is "
null".
Example:
--null "no deadlock" --string --critical "!no deadlock"
Name to be used for the performance data. By default a name is calculated based on the MBean's name and the attribute/operation to monitor.
Example:
--name "HeapMemoryUsage"
Label for using in the plugin output which can be a format specifier as described in "Output Tuning".
Example:
--label "%.2r% used (%.2v %u / %.2b %w)"
Switch off ("off") or on ("on") performance data generation. Performance data is generated by default for numerical checks and omitted for string based checks. For relative checks, if the value is '%' then performance data is appended as relative values instead of absolute values.
Natural unit of the value measured. E.g. when measuring memory, then the memory MXBean exports this number as bytes. The value given here is used for shortening the value's output by converting to the largest possible unit. See "Output Tuning" for details.
Example:
--alias MEMORY_HEAP_USED --unit B
Critical threshold. For string checks, see "String checks" for how the critical value is interpreted. For other checks, the value given here should conform to the specification defined in.
Example:
--critical :90
Warning threshold, which is interpreted the same way as the
--critical threshold (see above). At least a warning or critical threshold must be given.
An alias is a shortcut for an MBean attribute or operation. See "Aliases" for details.
Example:
--alias RUNTIME_UPTIME
When aliasing is used,
check_jmx4perl needs to known about the target server type for resolving the alias. By default it used an autodetection facility, which at least required an additional request. To avoid this, the product can be explicitely specified here
Example:
--product jboss
User and password needed when the agent is secured with Basic Authentication. By default, no authentication is used.
How long to wait for an answer from the agent at most (in seconds). By default, the timeout is 180s.
The HTTP metod to use for sending the jmx4perl request. This can be either
get or
post. By default, an method is determined automatically.
get for simple, single requests,
post for bulk request or requests using a JMX proxy.
A HTTP proxy server to use for accessing the jolokia-agent.
Example:
--proxy
When the deployed Jolokia agent's version is less than 1.0, then this option should be used since the escape scheme as changed since version 1.0. This option is only important for MBeans whose names contain slashes. It is recommended to upgrade the agent to a post 1.0 version, though.
Switches on jolokia-proxy mode and specifies the URL for accessing the target platform. Optionally, user and password for accessing the target can be given, too. See "Proxy Mode" for details.
Example:
--target service:jmx:rmi:///jndi/rmi://bhut:9999/jmxrmi
Specifies a configuration file from where server and check definitions can be obtained. See "CONFIGURATION" for details about the configuration file's format.
Example:
--config /etc/jmx4perl/tomcat.cfg
Specify a symbolic name for a server connection. This name is used to lookup a server in the configuration file specified with
--config
Example:
servers.cfg: <Server tomcat> Url User roland Password fcn </Server> --config /etc/jmx4perl/servers.cfg --server tomcat
See "CONFIGURATION" for more about server definitions.
The name of the check to use as defined in the configuration file. See "CONFIGURATION" about the syntax for defining checks and multi checks. Additional arguments for parameterized checks should be given as additional arguments on the command line. Please note, that checks specified with
--check have precedence before checks defined explicitely on the command line.
Example:
--config /etc/jmx4perl/tomcat.cfg --check tc_servlet_requests jolokia-agent
Prints out the version of this plugin
Enables verbose output during the check, which is useful for debugging. Don't use it in production, it will confuse Nagios.
--usage give a short synopsis,
--help prints out a bit longe usage information.
--doc prints out this man page. If an argument is given, it will only print out the relevant sections. The following sections are recognized:
A 5 minute quickstart
Reference manual explaining the various operational modes.
Command line options available for
check_jmx4perl
Documentation for the configuration syntax
Using
check_jmx4perl with a configuration file is the most powerful way for defining Nagios checks. A simple configuration file looks like
# Define server connection parameters <Server tomcat> Url = </Server> # A simple heap memory check with a critical threshold of # 90% of the maximal heap memory. <Check memory_heap> Value = java.lang:type=Memory/HeapMemoryUsage/used Base = java.lang:type=Memory/HeapMemoryUsage/max Unit = B Label = Heap-Memory: %.2r% used (%.2v %u / %.2b %u) Name = Heap Critical = 90 </Check>
A configuration file is provided on the command line with the option
--config. It can be divided into two parts: A section defining server connection parameters and a section defining the checks themselves.
With
<Server name> the connection parameters for a specific server is defined. In order to select a server the
--server name command line option has to be used. Within a
<Server> configuration element, the following keys can be used:
The URL under which the jolokia agent can be reached.
If authentication is switched on, the user and the credentials can be provided with the User and Password directive, respectively. Currently only Basic Authentication is supported.
The type of application server to monitor. This configuration can speed up checks significantly, but only when aliases are used. By default when using aliases,
check_jmx4perl uses autodetection for determine the target's platform. This results in at least one additional HTTP-Request. This configuration does not has any effect when MBeans are always used with their full name.
A HTTP Proxy URL and credentials can be given with the
<Proxy> sub-section. Example:
<Server> .... <Proxy> Url = User = woody Password = buzz </Proxy> </Server>
The proxy URL
Optional user and credentials for accessing the proxy
With this directive, the JMX-Proxy mode can be switched on. As described in section "Proxy mode",
check_jmx4perl can operate in an agentless mode, where the agent servlet is deployed only on an intermediated, so called JMX-Proxy server, whereas the target platform only needs to export JMX information in the traditional way (e.g. via JSR-160 export). This mode is especially useful if the agent is not allowed to be installed on the target platform. However, this approach has some drawbacks and some functionality is missing there, so the agent-mode is the recommended way. A sample JMX-Proxy configuration looks like:
<Target> Url = service:jmx:rmi:///jndi/rmi://tessin:6666/jmxrmi User = max Password = frisch </Target>
For a discussion about the advantages and disadvantages of the JMX-Proxy mode, please have a look at which contains some evaluations of this mode for various application servers (e.g. JBoss and Weblogic).
The JMX-RMI Url to access the target platform.
User and password for authentication against the target server.
With
<Check> a single check can be defined. It takes any option available also available via the command line. Each check has a name, which can be referenced from the commandline with the option
--check name.
Example:
<Check memory_heap> Value = java.lang:type=Memory/HeapMemoryUsage/used Base = java.lang:type=Memory/HeapMemoryUsage/max Label = Heap-Memory: Name = Heap Critical = 90 </Check>
The
<Check> section knows about the following directives:
The
ObjectName of the MBean to monitor.
Attribute to monitor.
Operation, whose return value should be monitored. Either
Attribute or
Operation should be given, but not both. If the operation takes arguments, these need to be given as additional arguments to the
check_jmx4perl command line call. In the rare case, you need to call an overloaded operation (i.e. an operation whose name exists multiple times on the same MBean but with different parameter types), the argument types can be given within parentheses:
<Check> .... Operation = checkUserCount(java.lang.String,java.lang.String) ... </Check>
Used for specifying arguments to operation. This directive can be given multiple times for multiple arguments. The order of the directive determine the order of the arguments.
<Check> .... Operation checkUserCount(java.lang.String,java.lang.String) Argument Max Argument Morlock </Check>
Alias, which must be known to
check_jmx4perl. Use
jmx4perl aliases to get a list of all known aliases. If
Alias is given as configuration directive,
Operation and/or
Attribute is ignored. Please note, that using
Alias without
Product in the server section leads to at least one additional HTTP request.
Path to apply to the attribute or operation return value. See "Paths" for more information about paths.
Value is a shortcut for specifying
MBean,
Attribute and
Path at once. Simply concatenate all three parts via
/ (the
Path part is optional). Slashes within MBean names needs to be escaped with a
\ (backslash). Example:
Value = java.lang:type=Memory/HeapMemoryUsage/used
is equivalent to
MBean = java.lang:type=Memory Attribute = HeapMemoryUsage Path = used
Switches on relative checks. See "Relative Checks" for more information about relative checks. The value specified with this directive defines the base value against which the relative value should be calculated. The format is the same as for
Value:
Base = java.lang:type=Memory/HeapMemoryUsage/max
For relative checks, the
Critical and
Warning Threshold are interpreted as a value between 0% and 100%.
As an alternative to specifying a base value in a combined fashion the different parts can be given separately.
BaseMBean and
BaseAttribute switches on relative checks and specifies the base value. An optional
BasePath can be used to provide the path within this base value.
The example above can be also written as
BaseMBean = java.lang:type=Memory BaseAttribute = HeapMemoryUsage BasePath = max
Switches on incremental mode as described in section "Incremental Checks". The value given is used for normalization the increase rate. E.g.
Delta = 60
measures the growth rate per minute (60 seconds). If no value is given, the absolute increase between two checks is used.
This directive switches on numeric mode, i.e. the given threshold values are compared numerically against the returned JMX value. By default, the check mode is determined by a heuristic algorithm.
String checks, which are switched on with this directive, are useful for non-numeric thresholds. See "String checks" for more details.
The name to be used in the performance data. By default, a name is calculated based on the MBean and attribute/operation name.
If this check is used within a multi check, this prefix is used to identify this particular check in the output of a multicheck. It can be set to an empty string if no prefix is required. By default the name as configured with
Name is used.
Format for setting the plugin output (not the performance data, use
Name for this). It takes a printf like format string which is described in detail in "Output Tuning".
By default, performance data is appended for numeric checks. This can be tuned by setting this directive to "false" (or "0", "no", "off") in which case performance data is omitted. If using this in a base check, an inherited check can switch performance data generation back on with "true" (or "1", "yes", "on")
For relative checks, the value can be set to '%'. In this case, performance data is added as relative values instead of the absolute value measured.
This specifies how the return value should be interpreted. This value, if given, must conform to the unit returned by the JMX attribute/operation. E.g. for
java.lang:type=Memory/HeapMemoryUsage/used unit, if set, must be
B since this JMX call returns the used memory measured in bytes. The value given here is only used for shortening the plugin's output automatically. For more details and for what units are available refer to section "Output Tuning".
Specifies the critical threshold. If
String is set (or the heuristics determines a string check), this should be a string value as described in "String checks". For relative checks, this should be a relative value in ther range [0,100]. Otherwise, it is a simple numeric value which is used as threshold. For numeric checks, the threshhold can be given in the format defined at.
Defines the warning threshold the same way as described for the
Critical threshold.
Replacement value when an attribute is null or an operation returns a null value. This value then can be used in string checks in order to check against null values. By default, this value is "
null".
HTTP Method to use for the check. Available values are
GET or
POST for GET or POST HTTP-Requests, respectively. By default a method is determined automatically. The value can be given case insensitively.
In order to use parent checks, this directive specifies the parent along with any parameters passed through. For example,
Use = memory_relative_base(80,90),base_label
uses a parent check named
memory_relative_base, which must be a check defined in the same configuration file (or an imported on). Additionally, the parameters
80 and
90 are passed to this check (which can be accessed there via the argument placeholders
$0 and
$1). See "Parent checks" and "Parameterized checks" for more information about check inheritance.
Multiple parents can be given by providing them in a comma separated list.
For complex checks which can not be realized with the configurations described until yet, it is possible to use a Perl script snippet to perfrom arbitrary logic. The content of this script is typically provided as an HERE-document (see example below). It comes with a predefined variable
$j4p which is an instance of JMX::Jmx4Perl so that it can be used for a flexible access to the server. Note that this scriptlet is executed separately and doesn't not benefit from the optimization done for bulk or relative checks. Check parameters can be accessed as ${0}, ${1}, .. but since these are also valid Perl variables (and hence can be overwritten accidentially), it is recommended to assign them to local variable before using them. In summary, script based checks are powerful but might be expensive.
Example:
Script <<EOT my $pools = $j4p->search("java.lang:type=MemoryPool,*"); my @matched_pools; my $pattern = "${0}"; for my $pool (@$pools) { push @matched_pools,$pool if $pool =~ /$pattern/; } return $j4p->get_attribute($matched_pools[0],"Usage","used"); EOT
Checks can be organized in multiple configuration files. To include another configuration file, the
include directive can be used:
include tomcat.cfg include threads.cfg include memory.cfg
If given as relative path, the configuration files are looked up in the same directory as the current configuration file. Absolute paths can be given, too.
With
check_jmx4perl parent checks it is possible to define common base checks, which are usable in various sub-checks. Any
<Check> can be a parent check as soon as it is referenced via a
Use directive from within another check's definition. When a check with a parent check is used, its configuration is merged with this from the parent check with own directives having a higher priority. Parent checks can have parent checks as well (and so on).
For example, consider the following configuration:
<Check grand_parent> Name grand_parent Label GrandPa Critical 10 </Check> <Check parent_1> Use grand_parent Name parent_1 Critical 20 </Check> <Check parent_2> Name parent_2 Warning 20 </Check> <Check check> Use parent_1,parent_2 Warning 40 </Check>
In this scenario, when check
check is used, it has a
Name "
parent_2" (last parent check in
Use), a
Label "GrandPa" (inherited from
grand_parent via
parent_1), a
Critical 20 (inherited from
parent_1) and a
Warning 40 (directly give in the check definition).
A parent value of a configuration directive can be refered to with the placeholder
$BASE. For example:
<Check parent> Name Parent </Check> <Check check> Use parent Name Child: $BASE </Check>
This will lead to a
Name "
Child: Parent" since
$BASE is resolved to the parent checks valus of
Name,
"Parent" in this case. The base value is searched upwards in the inheritance hierarchy (parent, grand parent, ...) until a value is found. If nonen is found, an empty string is used for
$BASE.
Checks can be parameterized, i.e. they can take arguments which are replaced in the configuration during runtime. Arguments are used in check definition via the positional format
$0,
$1, .... (e.g.
$0 is the first argument given). Arguments can either be given on the command line as extra arguments to
check_jmx4perl or within the
Use directive to provide arguments to parent checks.
Example:
<Check parent> Name $0 Label $1 </Check> <Check child_check> Use parent($0,"Check-Label") .... </Check> $ check_jmx4perl --check child_check .... "Argument-Name" OK - Check-Label | 'Argument-Name'= ....
As it can be seen in this example, arguments can be propagated to a parent check. In this case,
$0 from the command line (
Argument-Name) is passed through to the parent check which uses it in the
Name directive.
$1 from the parent check is replaced with the value "
Check-Label" given in the
Use directive of the child check.
Parameters can have default values. These default values are taken in case an argument is missing (either when declaring the parent check or missing from the command line). Default values are specified with
${arg-nr
:default
}. For example,
<Check relative_base> Label = %.2r% used (%.2v %u / %.2b %w) Critical = ${0:90} Warning = ${1:80} </Check>
defines a default value of 90% for the critical threshold and 80% for the warning threshold. If a child check uses this parent definition and only wants to ommit the first parameter (but explicitely specifying the second parameter) it can do so by leaving the first parameter empty:
<Check child> Use relative_base(,70) </Check>
Multiple checks can be combined to a single MultiCheck. The advantage of a multi check is, that multiple values can be retrieved from the server side with a single HTTP request. The output is conformant to Nagios 3 multiline format. It will lead to a
CRITICAL value as soon as one check is critical, same for
WARNING. If both,
CRITICAL and
WARNING is triggered by two or more checks, then
CRITICAL take precedence.
If a single check within a multi check fails with an exception (e.g. because an MBean is missing), its state becomes
UNKNOWN.
UNKNOWN is the highest state in so far that it shadows even
CRITICAL (i.e. if a single check is
UNKNOWN the whole multi check is
UNKNOWN, too). This can be changed by providing the command line option
--unknown-is-critical in which case all
UNKNOWN errors are mapped to
CRITICAL.
A multi-check can be defined with the directive
<MultiCheck>, which contain various references to other
<Check> definitions or other multi check definitions.
Example:
<MultiCheck all> MultiCheck memory MultiCheck threads </MultiCheck> <MultiCheck memory> Check memory_heap($0,80) Check memory_pool_base("CMS Perm Gen",90,80) </MultiCheck> <MultiCheck threads> Check thread_inc Check thread_deadlock </MultiCheck>
Here a multi check group memory has been defined with reference to two checks, which must exist somewhere else in the configuration file. As it can be seen, parameters can be given through to the check in the usual way (literally or with references to command line arguments). The group all combines the two groups memory and thread, containing effectively four checks.
A multi-check is referenced from the command line like any other check:
$ check_jmx4perl .... --check all 90
(90 is the argument which replaces
$0 in the definition above).
The summary label in a multi check can be configured, too.
Example:
<MultiCheck memory> SummaryOk All %n checks are OK SummaryFailure %e of %n checks failed [%d] ... </MultiCheck>
These format specifiers can be used:
%n Number of all checks executed %e Number of failed checks %d Details which checks failed
check_jmx4perl comes with a collection of predefined configuration for various application servers. The configurations can be found in the directory config within the toplevel distribution directory. The configurations are fairly well documented inline.
Common check definitions, which can be used as parents for own checks. E.g. a check
relative_base can be used as parent for getting a nicely formatted output message.
Memory checks for heap and non-heap memoy as well as for various memory pools. Particularly interesting here is the so called Perm Gen pool as it holds the java type information which can overflow e.g after multiple redeployments when the old classloader of the webapp can't be cleared up by the garbage collector (someone might still hold a reference to it).
Checks for threads, i.e. checking for the tread count increase rate. A check for finding out deadlocks (on a JDK 6 VM) is provided, too.
Various checks for jetty like checking for running servlets, thread count within the app server, sessions (number and lifing time) or requests per minute.
Mostly the same checks as for jetty, but for tomcat as application server.
WebSphere specific checks, which uses the configuration files below the `websphere/` directory. For this checks to work, a customized Jolokia agent with JSR-77 extensions is required. The GitHub project for this enhanced agents can be found at and downloaded at Maven Central () <>.
roland@cpan.org | http://search.cpan.org/~roland/jmx4perl-1.12/scripts/check_jmx4perl | CC-MAIN-2017-30 | refinedweb | 7,808 | 56.66 |
This post is by Grammarly software engineers Anton Pets and Yaroslav Voloshchuk. See part 1 here.
In our last post, we examined some of Grammarly engineering’s process-based methods of reducing complexity, derived from research, experience, and classic computer science guidelines. In this post, we’ll look at how we reduce complexity in the code itself, starting with our complexity pyramid, which informs our choices throughout the front-end development process and helps ensure that engineering hours are invested well. We hope to provide you with ideas for designing your code, educating yourself, and leveraging classic ideas of computer science to reduce complexity—from the start of project planning all the way to the final PR merge.
Complexity can creep in from anywhere: from new challenges or familiar problems. The latter can be especially insidious because we’re likely to be less suspicious of common issues. Consider email validation, a commonly encountered task. Shouldn’t it be a straightforward matter of working out the correct regex, validating it, and calling it done?
Alas, regex for email validation isn’t simple. And once you finally nail down a long string of regex pattern, you still need to send an email with a validation link that the user has to click. This creates obstacles: An extra step means a drop in conversions. Users sometimes can’t find the emails, or maybe just won’t take that extra step of opening to click.
We might address this problem by starting to send email addresses to the server—to check the MX records for the domains—while the user fills out the form. It’s not a bad fix, but it brings the inherent complexity of MX record validation into play.
Because that’s how complexity grows: By solving one issue you might add several new ones. Figuring out how to avoid doing so is difficult—but we’ve worked through a few processes that can help.
The structure of code complexity
There are two types of complexity in software: structural and behavioral. Structural complexity represents the built connection between your application’s components. Behavioral complexity comes into play when these components interact: when they start sending messages to one another at runtime. Behavioral complexity is strongly connected to how a user interacts with the system, whereas structural complexity is more about how engineers build the system. In this article, we will mostly focus on structural complexity.
In code, complexity occurs at increasing levels of abstraction. The complexity pyramid shown above is one way to think about how an engineer will encounter them. Let’s climb the pyramid to see what might help us at each level. We’ll need to reconsider basic code blocks that we might take for granted as having mastered: statements, functions and methods, and modules and classes. We’ll even need to reconsider how we think about applications themselves.
But first, we need to discuss some of the major tools in our arsenal for minimizing complexity up the pyramid.
Allies against complexity
Functional programming: Almost a silver bullet
In the previous post, we agreed that there is no silver bullet to fight software complexity. But a central part of overcoming complexity is ensuring that your code works predictably. One way we do this at Grammarly is by using statically typed functional programming.
Consider this level of excitement about FP:
We introduced static typing at Grammarly, which had helped us vastly improve our code quality but left us still struggling with unpredictability and complexity. That’s when functional programming entered our toolkit.
One particularly challenging task we encountered was synchronizing a user’s text between front-end and back-end. If a user clicks on the Correct Mistake button, for example, the error correction event should first go to the server. Only then should we correct the text in the browser and send the updated document to the server. If done in the wrong order, our back-end tries to handle the correction event on the already corrected text—and consequently produces an incorrect state. The two events—correcting a mistake and updating text—are examples of side effects. Coordinating multiple asynchronous side effects in a complex UI system is difficult and can be a limitless source of bugs.
We were able to address some of these side-effect issues once we began using functional programming, which was introduced to our team by colleagues that had backgrounds in F#. The first FP citizen in our repository was
Option (aka
Maybe) type, which is now used all over our codebase. Later, we discovered existing FP libraries that provide nuanced ready-to-use tools for controlling side effects elegantly. Because FP abstractions are universal (they operate like extremely forceful design patterns), the FP-powered solutions are easier to understand and reuse. We diminished our side-effect problems by using this functional approach, and now we always prefer declarative FP solutions to imperative or class-based code.
Types: An underrated (and critical) ally
Another major ally to consider in the fight against complexity: the use of types.
Though we know it can seem to add complexity when you adapt an existing codebase to have types, our own experience is that incorporating types merely surfaces unavoidable complexity already in the code.
So if your code is clumsy: Yes, adding types will result in clumsy types. Though this can itself be a step toward conquering complexity. Having a combination of different function calls with complex parameters can make it hard to understand the underlying logic. But when types are used, it becomes obvious what are the inputs and outputs of functions—and, consequently, it becomes easier to understand the behavior.
Without types, there is no verification before code execution (except code linters, which are more of a crutch used in the absence of types). There are no very compelling reasons not to use types, as static typing doesn’t add overhead at runtime in almost any available languages compiled in JavaScript. Some examples: TypeScript, Elm, PureScript, Reason, and OCaml.
Grammarly’s Editor was originally written in JavaScript because there were no popular statically typed languages that could compile into JavaScript at the time. Later, as the complexity of the app grew, the Editor became harder to support, and it was not easy to improve a big codebase without compile-time verification. So we started to research options for compiled-to-JavaScript languages that could meet our needs. We analyzed many options, including TypeScript, PureScript, and Scala.js. In the end, we chose TypeScript because it has a robust ecosystem and community of support. Even more, TypeScript is a superset of JavaScript, and so it was easy to adopt.
We completely rewrote our Editor in TypeScript so we could make a fair comparison with JavaScript. Long before the last commit was made, we knew we preferred TypeScript, so we used it to develop Denali, the latest generation of the Grammarly Editor.
How does this language switch relate to functional programming and our journey to limit complexity? JavaScript has all the necessary attributes to be an effective functional language: first-class functions, lambda functions, and closures. But functions in JavaScript are not pure, and data is not immutable. Furthermore, the lack of static typing makes it harder to compose neat functions because composition requires some contracts to be respected, and there are some other advantages of types in FP. For this reason, TypeScript is a better option for FP—especially now that we have such FP libraries as FP-TS and Funfix—and thereby a better ally for limiting complexity.
So even though there is no one fix to eliminate complexity entirely, we agree with Mark Seeman’s points in “Yes Silver Bullet”: Statically typed functional programming is as close to a silver bullet as we’ve found.
Structural Complexity
Now that we’ve discussed functional programming and the benefit of using types, we can return to our pyramid fully outfitted for success. Let’s address complexity from the bottom up, starting at the level of statements.
Statements: Unchanging variables and handling predictable exceptions
Some of functional programming’s most helpful characteristics come from some pretty elemental guidelines. To start: When possible, we use
readonly variables, which keep the changes created by our functions compact and predictable, and our parameters unchanged.
We also try to contain unexpected effects by using
for/while loops only in performance-sensitive places.
for/while loops are powerful tools but are notorious for creating problems (there’s a reason Apple headquarters’ original address was 1 Infinite Loop). We use them judiciously and only when we know they’re the best option.
Finally, we try to perform idiomatic handling for empty values and errors with
Try and
Option.
Option is an object type that may or may not have a value; this type is used to prevent undefined and null objects and their resulting errors.
Try is an object that can be completed either successfully or unsuccessfully, without the need to catch exceptions in your application. By using these, you can be less defensive in your programming.
In the code above, we get an
Option—that is, an optional parameter—and try to parse it with
Try. First, we do it in one way, and if that doesn’t work, we try to recover in another way, which can enable your code to support two different formats of stored app configuration (in the case of json.parse, a JSON string). Then we try to validate it; if the validation worked, we merge it with our basic config and return it. If at some point the values we needed to proceed through the entire function are not there, we return the default value. And as we discussed with
readonly variables the original variables supplied as parameters are unchanged and still available to other functions as needed.
Functions: Clear, pure, and SOLID
When possible, we prefer pure functions, and we try to avoid conditional
if statements for switching behavior.
For instance, we have a function that writes logs, and when we run it in the local environment, it writes to the console. Instead of making one function with conditional checks, we make it polymorphic with two different implementations. The correct one will be used depending on the parameters supplied. Here’s an example:
For polymorphism, it is important to respect two important principles from SOLID—a classic set of computer science principles that we keep in mind throughout our work. First, the single responsibility principle states that each function or method should be responsible for just one thing. This makes our code more deliberate, clear, and predictable. Second, the Liskov substitution principle states that we should be able to easily switch from one function implementation to another.
Another way of ensuring clarity is to avoid class methods that can leave the class in a disassembled state. For example, when we create an alert in the user’s text (an object that stores information about a specific error or an issue, including its position in text and possible ways to fix the error or issue), we must register this alert with the
positionManager, which is an entity that controls the absolute position of the alert in text.
If we haven’t registered the alert, we can’t do anything with it, so if an operation happens without registering the alert, we’ll get an exception. To avoid this, we should design our system so the object is provided what it needs from the start.
The composition is critical, and we use it frequently with functions, classes, and objects. When used with functions, it opens up a whole stream of possibilities in the form of memoization, piping, and other useful perks. We can also use composition to divide function logic from error recovery—e.g., to isolate handling JSON parsing errors from the actual usage of the parsing result. This then empowers us to use and combine different error-handling strategies inside a function without rewriting its logic.
Finally, it’s essential to write functions with a clear and easy-to-use interface. In the example below, the parse function takes a data parameter, and what it does internally may not be immediately evident in its twenty lines of code (to say nothing of much longer functions). If you specify that the function returns Try, engineers using your function later will be grateful, and future engineers will find it much easier to maintain the codebase.
Modules and classes
Although types bring considerable benefits at each level of the complexity pyramid, their utility becomes most evident at the class and module level. At this level, engineers start to think in terms of software architecture. We think through the design of our modules, how they interact, and their APIs, using types to describe these aspects. Then we implement our architecture, integrating work from other Grammarly engineers that might use different libraries or frameworks. Having clear types in place ensures that we can manage these different sources of complexity for this commit—and future ones too.
Invariance in types
In general, when constructing types, it’s best to ensure that they cannot express an incorrect or somehow contradictory state. Let’s imagine, for instance, that we are implementing an interface for a bulb switcher. We might inadvertently create an unpredictable state, like trying to switch off a bulb that’s not on. The solution would be creating a specialized bulb interface that does not allow such behavior. Consider the code sample below.
In some languages, such a design can be achieved with the help of algebraic data types.
Algebraic data types
This principle dictates that we cannot read data from a state that is incorrect according to the type system. By avoiding contradictory states, we can avoid complexity.
Correct data structures for better performance
Strong types help ensure that you’re using the right data structures and not defaulting to simple arrays and objects, which can be suboptimal. A few examples:
- Set vs. Array: If you need only unique values, use set instead of array, as it provides a quick uniqueness check.
- Prefix tree vs. Hash table: This is an important distinction for search functionality. For instance, if you needed to create an English-language dictionary that will be frequently searched but rarely modified, then you might use a prefix tree. Looking up data will be faster, even in a worst-case scenario, compared to an imperfect hash table that contains many key collisions. Moreover, using a hash table for this would require a huge amount of allocated memory, which is especially important to consider for front-end apps.
Data heading/encapsulation
This classic software engineering principle dictates that our variables, functions, and classes should have the smallest possible scope. Avoid exporting or importing unnecessary artifacts. Hide nonessential variables inside closures instead of storing them inside a class. Try not to clutter your namespaces.
Separation of concerns
This principle dictates that responsibilities are distinctly separated. For example, imagine that you need to implement functionality for bank-transaction processing. In addition to the core business logic, this task also requires authorization, logging, tracking, and other functions. You will want to isolate all these concerns into separate modules. Mixing them all into a single function or class risks turning into unsupportable spaghetti code.
Composition over inheritance
Inheritance is one of the ways to implement polymorphism. When we use it for composition, however, we end up with highly coupled, inflexible, and fragile architectures. Composition is usually preferable.
Applications and subsystems
Before we move on from discussing the structural complexity of building an app, we wanted to talk about complexity at the level of the application itself. This can sit between the code level—which we just discussed—and the behavioral areas. There are some shared principles that can help a project move cleanly from discussion through to implementation.
To start, we try not to reinvent the wheel when writing code, because less new code means less maintenance. If we have a need our current code and libraries don’t address, often there’s an existing library that will cover it—and our job, when we’re planning out a project’s architecture and code, is to find it. Design patterns and frameworks are similar. Many common problems are already well solved and don’t require a new or different solution. Sometimes engineers feel ambitious and are drawn to a challenge, but good planning can mean the difference between a successful project and one that requires a difficult retro.
We also suggest using a trustworthy runtime library—we like FP-TS, Ramda, Immutable.js, and lodash/fp. We keep our list of tools up to date through ongoing team self-education and sharing resources and papers with one another. We like dev.to, The Morning Paper, Dan Abramov’s blog, and this extensive repo of functional programming resources.
Behavioral complexity
Though behavioral complexity is a subject that’s too big for one blog post—much less a section of one—it’s important to examine how it fits into our discussion about structural complexity. If we look back at our complexity pyramid, we’re now going all the way back to the base of product requirements. Behavioral complexity is a concern from that early stage and continues running alongside all the structural concerns we’ve been discussing.
Behavioral complexity in front-end applications at Grammarly is often caused by the asynchronous nature of human-computer interaction. We have struggled with common front-end challenges like callback hell and orchestrating application actions via event emitters. But one thing has made our life noticeably better: functional reactive programming (FRP). We found it especially effective to manage application state. We even created our own state management framework, Focal, which leverages our favorite parts of React and RxJS.
To illustrate how one might deal with this type of complexity, let’s look at an example of functional reactive programming usage. Here we are waiting for the user’s mouse to get into a certain area of Grammarly’s Editor; after that, we will start tracking mouse moves. Our task is to find DOM nodes under the pointer. For performance reasons, we don’t want to immediately notify the system about the mouse leaving the area, so we add a 200-millisecond delay. Finally, we filter duplicates of those states so we don’t overload the system with unnecessary actions.
There are a lot of complicated things going on here—and keep in mind that this code would be much longer if it were written in imperative style. In fact, just to show this complex sample, we had to violate some of the principles discussed above. Namely, the single responsibility principle is not respected, and some functions are not separated into their own modules.
But perhaps this itself is the best illustration of complexity: Even just demonstrating and explaining how to manage, it can be so complicated you might need to question whether you’re taking the right approach. You might even have to go back to the beginning and make sure you planned things out correctly. (But don’t worry—we won’t do that to you in this post.)
Takeaways
Complexity in software engineering is—no surprise—a very complex subject. We can never fully eliminate it, but with the use of long-lived principles (such as SOLID) and the use of recent engineering advances (such as recent functional programming libraries like ft-ts), we can reduce it enough to make reliable software that isn’t a burden to maintain. Even just incorporating one or two of the above ideas might make your team’s work measurably easier. With a strongly typed language here and the adoption of
readonly variables there, adding a new feature becomes that much less burdensome. | https://www.grammarly.com/blog/engineering/part-2-how-grammarly-tackles-hidden-complexity-in-front-end-applications/ | CC-MAIN-2020-16 | refinedweb | 3,304 | 52.8 |
Hi, I did not find any up to date explanation of how ot use Proguad with Ionic 2, so I had to go through several different explanations figuring out what works with latest versions of android, proguard, cordova and ionic 2.
I’m sharing the solution I came up with, which seems to work well with my app, so others can use it and to get feedback if I missed something.
1. The information for proguard contained in the platform project seems to be outdated for latest android versions:
In platforms/android/project.properties you will find this hint:
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
However, I found out we should ignore it since it does not work anymore (has no effect) and the referenced proguard-project.txt seems to be missing anyway.
2. Enable Proguard
You will have to modify platforms/android/build.gradle instead and add some configuration to buildTypes.release section:
buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' ... } }
Hint: I have used proguard-android-optimize.txt as suggested in which seems to enable more shrinking than proguard-android.txt. Did not find any problems with it.
The proguard-rules.pro file is a file with your custom configurations. In old cordova project this is referenced as “proguard-project.txt”, however I used here the name used by Android Studio normally and which is used in android documenations. The file has to be in the same folder as the build.gradle file, or you have to adjust the path to it.
3. Add required proguard rules
You will have to exclude some classes from being stripped away or from being renamed. I assembled several examples I found and came up with following solution (add them in proguard-rules.pro):
# ionic -keep class org.apache.cordova.** { *; } -keep public class * extends org.apache.cordova.CordovaPlugin -keep class com.ionic.keyboard.IonicKeyboard.** { *; } #adm; } -keep public class com.google.cordova.admob.** # Not sure if needed, found it in several document; }
The first block seems to be needed for Ionic & Cordova.
The second one is needed by AdMob plugin (if you use it)
I’m not so sure about the 3rd block. I found it in several documentations and examples, however I’m not sure if you really need it. I just added it to be sure. Feel free to play around with it and give some feedback.
Some other cordova plugins require also special rules, so keep an eye open on their documentations for hints regarding ProGuard.
4. Add your owns project proguard rules
You might need more rules if you have added platform specific code in some cases, however, I don’t need anything else than above since I don’t have this.
5. IMPORTANT: Make sure to re-enable and configure proguard after reinitializing/re-adding android platform!
Probably your config will be lost when re-adding/initializing android platform so you will have to do it again. In my case I checked in build.gradle + proguard-rules.pro into my projects VCS to make sure I see if anything changed there. Maybe adding a hook which ensures that the config is there or even adds it would make sense. (Does somebody want to share some hook here, maybe?)
That’s it! Recompile your project using
ionic build android --release --prod and pray hard while opening the app ;). If it crashes see logcat output to find out what classes its complaining about. You should test the app well before releasing it, especially any interaction with native plugins.
Hint:
This not only obfuscates the apps code but also reduces the size of your app and according to androids documentation it will also speed it up. In my case:
APK without proguard: 7,33 MB
APK with proguard: 7,25 MB
Installed app without proguard: 16,18 MB
Installed app with proguard: 12,98 MB
Any Feedback? Did you come up with more rules needed?
Greetings
Ralf | https://forum.ionicframework.com/t/proguard-and-ionic/84271 | CC-MAIN-2018-51 | refinedweb | 684 | 65.12 |
Next: printf, Up: GNU lightning examples
Let’s see how to create and use the sample
incr function created
in GNU lightning’s instruction set:
#include <stdio.h> #include <lightning.h> static jit_state_t *_jit; typedef int (*pifi)(int); /* Pointer to Int Function of Int */ int main(int argc, char *argv[]) { jit_node_t *in; pifi incr; init_jit(argv[0]); _jit = jit_new_state(); jit_prolog(); /* prolog */ in = jit_arg(); /* in = arg */ jit_getarg(JIT_R0, in); /* getarg R0 */ jit_addi(JIT_R0, JIT_R0, 1); /* addi R0, R0, 1 */ jit_retr(JIT_R0); /* retr R0 */ incr = jit_emit(); jit_clear_state(); /* call the generated code, passing 5 as an argument */ printf("%d + 1 = %d\n", 5, incr(5)); jit_destroy_state(); finish_jit(); return 0; }
Let’s examine the code line by line (well, almost…):
You already know about this. It defines all of GNU lightning’s macros.
You might wonder about what is
jit_state_t. It is a structure
that stores jit code generation information. The name
_jit is
special, because since multiple jit generators can run at the same
time, you must either #define _jit my_jit_state or name it
_jit.
Just a handy typedef for a pointer to a function that takes an
int and returns another.
Declares a variable to hold an identifier for a function argument. It
is an opaque pointer, that will hold the return of a call to
arg
and be used as argument to
getarg.
Declares a function pointer variable to a function that receives an
int and returns an
int.
You must call this function before creating a
jit_state_t
object. This function does global state initialization, and may need
to detect CPU or Operating System features. It receives a string
argument that is later used to read symbols from a shared object using
GNU binutils if disassembly was enabled at configure time. If no
disassembly will be performed a NULL pointer can be used as argument.
This call initializes a GNU lightning jit state.
Ok, so we start generating code for our beloved function…
We retrieve the first (and only) argument, an integer, and store it
into the general-purpose register
R0.
We add one to the content of the register.
This instruction generates a standard function epilog that returns
the contents of the
R0 register.
This instruction is very important. It actually translates the GNU lightning macros used before to machine code, flushes the generated code area out of the processor’s instruction cache and return a pointer to the start of the code.
This call cleanups any data not required for jit execution. Note
that it must be called after any call to
jit_print or
jit_address, as this call destroy the GNU lightning
intermediate representation.
Calling our function is this simple—it is not distinguishable from
a normal C function call, the only difference being that
incr
is a variable.
Releases all memory associated with the jit context. It should be called after known the jit will no longer be called.
This call cleanups any global state hold by GNU lightning, and is advisable to call it once jit code will no longer be generated._64
architecture (on the right is the code that an assembly-language
programmer would write):
save %sp, -112, %sp mov %i0, %g2 retl inc %g2 inc %o0 mov %g2, %i0 restore retl nop
In this case, GNU lightning introduces overhead to create a register
window (not knowing that the procedure is a leaf procedure) and to
move the argument to the general purpose register
R0 (which
maps to
%g2 on the SPARC).
sub $0x30,%rsp mov %rbp,(%rsp) mov %rsp,%rbp sub $0x18,%rsp mov %rdi,%rax mov %rdi, %rax add $0x1,%rax inc %rax mov %rbp,%rsp mov (%rsp),%rbp add $0x30,%rsp retq retq
In this case, the main overhead is due to the function’s prolog and epilog, and stack alignment after reserving stack space for word to/from float conversions or moving data from/to x87 to/from SSE. Note that besides allocating space to save callee saved registers, no registers are saved/restored because GNU lightning notices those registers are not modified. There is currently no logic to detect if it needs to allocate stack space for type conversions neither proper leaf function detection, but these are subject to change (FIXME).
Next: printf, Up: GNU lightning examples | http://www.gnu.org/software/lightning/manual/html_node/incr.html | CC-MAIN-2014-41 | refinedweb | 707 | 58.62 |
#include <LiquidCrystal.h> LiquidCrystal lcd(10, 11, 12, 13, 14, 15, 16); int n = 0; void setup() { lcd.clear();//clears lcd.print("Ozbolt is GAY"); lcd.setCursor(0,1); lcd.print("not really");} void loop() {}
Thanks guys this was much help. It is working now.
the display works according to the program but it is very unclear even after adjusting the 10k pot..im not sure what the problem is please help me out..some extra info:
ive attached the LCD to the breadboard by means of soldering connector pins (not sure if this is the problem?)
Hey..I tried your suggestions@MAS32: I tried changing the speed hopefully that means the baud rate..but didnt help much..
In your last picture only power and contrast are connected.The display doesn't get a reset (because there is no device connected that can send that) so it might act like this (but as you already read somewhere, the boxes are expected in the top row).
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=53952.msg1160165 | CC-MAIN-2015-11 | refinedweb | 200 | 75.2 |
Geb Gems: Handling AJAX requests
One of the biggest struggles while testing web applications that use AJAX is dealing with the timing issues caused by asynchronous nature of the request. A common solution is using timeouts to wait for the AJAX call to be completed. This could cause lots of timing issues. Using Geb there is a better way to determine that the AJAX call and its callback has been completed.
In this blog post we will test the W3Schools website which has a button on it which executes an AJAX request:
First we change our baseUrl in the GebConfig.groovy file to the w3school site:
baseUrl = ""
Second we define the W3schools page with the needed content and the makeRequest method which clicks the button.
import geb.Page class WwwSchoolsAjaxExamplePage extends Page{ private static final DEFAULT_DIV_CONTENT = 'Let AJAX change this text' static url = "ajax/ajax_example.asp" static at = { title=="AJAX Example" } static content = { theButton { $(".example button") } theResultDiv { $("#myDiv") } } def makeRequest() { theButton.click() waitFor { theResultDiv.text()!=DEFAULT_DIV_CONTENT } } }
The key statement here is the
waitFor line. This will wait till the condition in the closure returns true. The
waitFor uses the default timeout configuration which is for Geb 5 seconds.
Next we're going to make our test which verifies our content has been updated.
import geb.spock.GebReportingSpec class AjaxRequestSpec extends GebReportingSpec{ def "Validate if content gets updated after button click"() { given: to WwwSchoolsAjaxExamplePage when: makeRequest() then: theResultDiv.children()[0].text() == "AJAX is not a new programming language." theResultDiv.children()[1].text() == "AJAX is a technique for creating fast and dynamic web pages." } }
When you run the now run the test, the test will succesfully verify the updated content of the w3schools website.
Done with Groovy 2.4.3 | https://blog.jdriven.com/2015/06/geb-gems-handling-ajax-requests/ | CC-MAIN-2021-43 | refinedweb | 288 | 57.06 |
issues stata12
Hello, has anyone been able to import an online excel file directly
into stata 12 without saving first? I need to write a loop to pull
multiple datasets from online, so I am trying to bypass manually
opening and saving them first. When I try the following code:
import excel,
sheet("UCDP DyadicDataset") firstrow clear
I get this error: file
could not be loaded
r(603);
I have tried many variants of the above syntax. For example, this
also does not work (returns the same error):
import excel using,
sheet("UCDP DyadicDataset") firstrow clear
I am having no issues importing an excel file I've saved first. The
following works perfectly:
import excel "C:\Desktop\Uppsala
Data\UCDP_DyadicDataset_v12011_1946_2010.xls", sheet("UCDP
DyadicDataset") firstrow clear
Thank you very much in advance for any help.
*
* For searches and help try:
*
*
* | http://www.stata.com/statalist/archive/2012-06/msg00269.html | CC-MAIN-2016-07 | refinedweb | 140 | 60.95 |
You.
SOAP 101
SOAP is a protocol for applications and servers to communicate with each other. Its primary use in PHP is exposing Web services and building Web service clients. As a protocol, it can exchange messages over HTTP/HTTPS, which helps it get around firewalls that would block other protocols (eg, Remote Procedure Call). As an application layer protocol, SOAP is also entirely platform independent — your PHP Web application can talk to a Java database server, for example, as long as they both speak SOAP.
SOAP messages are simply XML with some custom namespaces, so they're fully machine-readable. Libraries are available for every major language, and working with SOAP Web services is quick, easy and fast.
SOAP for PHP
Today we're going to take a look at one of these libraries, NuSOAP. PHP has a few options for SOAP, including a PHP 5 extension, a PEAR package, and an independent (but very popular) library called NuSOAP. NuSOAP is the simplest way to get up and running with SOAP, but we could just as well have used PEAR::SOAP or the extension, and all three are interoperable — you can consume PEAR::SOAP exposed services with NuSOAP and vice versa, and scripts using either can happily run alongside each other.
Getting started with NuSOAP
To begin using NuSOAP, first head to the project page and download a copy of libraries — I'm using version 0.7.2. All examples should be forwards-compatible, but API changes happen, so check your library version if you encounter any errors. Drop the contents of the archive into a folder on your Web server — using /soap under my docroot. The latest version is compatible with the SOAP extension, but if you experience "class already declared" errors just disable the SOAP extension or rename the class in nusoap.php.
Your first SOAP request!
We'll start with the SOAP client. SOAP works with servers and clients; servers expose services and clients consume them. We'll start with a demo of a simple Web service that takes an argument and returns an array — but with the power of SOAP, we get that array data locally, almost as if the client was the server, and SOAP takes care of all the information in between.
Fire up your favourite text editor and type out the following:
<?php include("lib/nusoap.php"); $soap = new soapclient(""); $output = $soap->call("hello_world", array("name" => "Josh")); print_r($output);
Save it as hello_world.php in the folder you created earlier. It can be anywhere, as long as the lib/nusoap.php reference still points to your NuSOAP library. Do the same for the server:
<?php include("lib/nusoap.php"); $srv = new soap_server(); $srv->register("hello_world"); function hello_world($name) { return array("data"=>"Hello World, {$name}!"); } $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ""; $srv->service($HTTP_RAW_POST_DATA);
Save this as hello_world_server.php in the same folder. If it can't be accessed at that URL in the client script (localhost/soap/...), change the reference in the client code as needed.
Then load up your Web browser, point it to the SOAP client — eg, — and run the script. You should see the following:
Array ( [data] => Hello World, Josh! )
That's perfectly normal print_r output — precisely what you would expect if you returned the array within the same PHP script. Except that our server script is separate, could be on a different server and could be running on a totally different platform — SOAP helps gets data from the server to the client as smoothly as possible.
The Server
Let's examine the server for a moment. Here's the code we used to build our server:
<?php include("lib/nusoap.php"); $srv = new soap_server(); $srv->register("hello_world"); function hello_world($name) { return array("data"=>"Hello World, {$name}!"); }
In this example, we first load up the NuSOAP library and register the service we want to expose, naming it "hello_world". We then define this service as a standard PHP function. At the moment, it does nothing but return a simple associative array, with the value containing an argument,
$name. The client provides this argument from a totally separate PHP script and SOAP provides the glue to make sure it is passed in when the function is called.
HTTP is stateless, and our PHP script will be executed from the top down whenever a request is made, so each SOAP call (or other script execution) will be a new request. To check if we have a SOAP call (and what the SOAP client wants us to do), we have to scan each request for data. SOAP clients send POST requests, with XML data in the message body of the request, so we can fetch this raw POST data and pass it to the
service() method of the
soap_server class. Raw POST data is available in
$HTTP_RAW_POST_DATA, but PHP won't set this unless it has a value, so we use a small hack to ensure it exists before passing it on to the SOAP server.
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : ''; $srv->service($HTTP_RAW_POST_DATA);
We quickly get together the raw POST data, pass it to the SOAP library, and away we go.
The Client
The client uses the NuSOAP library, but only because we choose to — the server could use the PHP SOAP extension or PEAR::SOAP, and could be hosted anywhere. With the power of SOAP, we're going to take the PHP function on the server and talk to it through SOAP; we're also going to receive the result just like any other variable within our script. Have a look at the code for the client:
<?php include("lib/nusoap.php"); $soap = new soapclient(""); $output = $soap->call("hello_world", array("name" => "Josh")); print_r($output);
The client is very basic — we first load up the library, then establish a connection to the SOAP server at the URL we've provided and call the "hello_world" service. For testing, we'll
print_r the output. The second argument to the
$soap->call() method is an array of parameters to be passed to the service. Notice we specify 'name' as the array key, the same as the $name argument on the server's function — this is not necessary as we aren't working with complex pre-defined services, however, it does hold importance when consuming slightly more elaborate SOAP services.
The service call returns a value which we then put into
$output. If we check that print_r output earlier, it showed we had a perfectly good PHP associative array —
[data] => Hello World, Josh! — just as our server's
hello_world() function should have returned. In just a few lines of code, we've linked together two independent PHP scripts. Now your Web apps are really talking.
Behind the scenes: debugging SOAP
While you make high-level calls to the SOAP libraries, the NuSOAP library is actually busy generating and parsing XML request messages and passing them back and forth between server and client. You can easily examine the message body of your request and the server's response on the client side, using the
request and
response properties of the SOAP client class. These are invaluable in debugging, and will help you get a better understanding of SOAP internals, although you may never need it...
<?php include("lib/nusoap.php"); $soap = new soapclient(""); $output = $soap->call("hello_world", array("name" => "Josh")); print_r($output); echo '<pre>'.htmlspecialchars($soap->request).'</pre>'; echo '<pre>'.htmlspecialchars($soap->response).'</pre>';
This request will output something like the following:
POST /soap/hello_world_server.php HTTP/1.0 Host: 127.0.0.1 User-Agent: NuSOAP/0.7.2 (1.94) Content-Type: text/xml; charset=ISO-8859-1 SOAPAction: "" Content-Length: 511 <?xml version="1.0" encoding="ISO-8859-1"?><SOAP-ENV:Envelope ...
Notice we're making a direct POST request and passing all the XML through. In a HTML form request, that XML would be replaced with key=value&key=value pairs, which are then translated into elements of $_POST — this is why we have to request the raw POST data to check for a SOAP request. The actual XML schema for SOAP messages isn't important, as the libraries take care of it for us, but read up on the SOAP specifications if you want to take a closer look.
Further SOAP
Now that you've built your first SOAP client, experiment with more complex APIs, or try consuming one of the many SOAP-based APIs available. If your applications already receive data from other sources, check if they offer SOAP — its use is very prevalent in enterprise situations, especially where SOA is encouraged. Finally, if you want to learn more about NuSOAP, one of the authors provides some handy resources.
1
Insane - 03/05/08
Excellent, nice post.
» Report offensive content
2
Pritam - 08/05/08
Hi.
Your post on web services using NuSOAP Utility is very nice one.
I tried out @my end but giving the problem as:
Warning: SoapClient::SoapClient() [function.SoapClient-SoapClient]: failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error in C:\wamp\www\soap\hello_world.php on line 3
Warning: SoapClient::SoapClient() [function.SoapClient-SoapClient]: I/O warning : failed to load external entity "" in C:\wamp\www\soap\hello_world.php on line 3
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from '' in C:\wamp\www\soap\hello_world.php:3 Stack trace: #0 C:\wamp\www\soap\hello_world.php(3): SoapClient->SoapClient('....') #1 {main} thrown in C:\wamp\www\soap\hello_world.php on line 3
Could you please tell me why this is happening?
I am using WAMP server. Also my host port is 81(localhost:81) b'se I am using IIS on port 80. I have done all changes which are required as per your post. But still I am facing the problem.
Regards,
Pritam
» Report offensive content
3
Bakhtiyor - 20/05/08
Excellent explanation of the subject. Well done. Thnx a lot.
» Report offensive content
4
Umesh Kumar Sharma - 22/05/08
Hi pritam,
i was also stuck with this kind of problem.
Please replace SoapClient with Soap_Client it will help you sure.
do like this-
» Report offensive content
5
Brendan - 05/06/08
Thanks for this.
It helped me a lot.
An FYI for anyone using IIS and SSL, you need cURL enables in your php.ini. I ran into this problem.
» Report offensive content
6
T.Aravindhan - 28/06/08
To Powerfull PHP Editor
» Report offensive content
7
cornice london - 26/08/08
vwery interestuing site ! really good article
» Report offensive content
8
mike - 07/10/08
Hi, i test and run to my local server and it returns nothing...anyone can help me?? anyways, nice post.
» Report offensive content
9
Nadeera - 03/11/08
i found the issue use the following code
» Report offensive content
10
asdasda - 18/11/08
asda
» Report offensive content
11
asdf - 18/11/08
asdfs
» Report offensive content
12
Nichi - 04/02/09
I figured out why I was getting the "[function.SoapClient-SoapClient]: failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error" message.
I'm using XAMPP on Windows and I needed to disable "extension=php_soap.dll" in the php.ini file for nusoap to work. I'd be curious to know as to why that would fix it though.
» Report offensive content
13
Mayuresh - 17/04/09
It is ok to disable "extension=php_soap.dll" if i a am working with local server, but what if i am working with sharing host? how can i disable this exttension using .htaccess or using php code(ini_set)?
» Report offensive content
14
markus - 11/05/09
it's a name conflict with the soap extension, just rename the class soapclient to something else
» Report offensive content | http://www.builderau.com.au/program/php/soa/Powerful-Web-Services-with-PHP-and-SOAP/0,339028448,339288552,00.htm | crawl-002 | refinedweb | 1,961 | 64 |
A VICTORIAN WRITER S WORLD. Who was Samuel Butler?
- William Shields
- 1 years ago
- Views:
Transcription
1 A VICTORIAN WRITER S WORLD Who was Samuel Butler? In the exhibition cases around the Library are lots of artefacts relating to Samuel Butler. We will be using these historical artefacts to help us build up a picture of a Victorian writer s world. We will try to find out: what Samuel Butler did during his lifetime, and when; what else was happening at the same time; what Samuel Butler was like as a person. We cannot ask Samuel Butler about his life and the world he lived in, because he died more than 100 years ago. If we want to find out about people from the past we have to look for evidence, then use the evidence to form our own impression of what life was like for them. You will need to look very carefully at the artefacts on display, and think of them as clues that will help you solve the mystery of who Samuel Butler was. Turn over the page to begin your trail around the exhibition! NOTE: The exhibition cases are numbered from 1 to 10, but the order is not important you can start anywhere.
2 Case 1 The Origin of Species is one of the most important books ever published. It is all about the scientific theory of evolution, and it offers an explanation of how life on earth has come to be the way it is. In which year was this book first published? Who wrote it? Next to it is another copy of the Origin of Species, which Samuel Butler bought in 1876 (almost 20 years after it was first published). The notes scribbled in the book are by Samuel Butler. Do you think Samuel Butler agreed with Charles Darwin s explanation? Give a reason for your answer. Samuel Butler wrote his own books on the subject of evolution. Two of these are on display elsewhere in the exhibition. When you find them, write down their titles and the years in which they were first published: Did Samuel Butler write about evolution before or after Charles Darwin?
3 Case 2 Here is one of Samuel Butler s account books, where he kept a record of the money he spent on one of his main hobbies. What was this hobby? Look closely and you will see he has listed his expenses in chronological order, year by year. In which year did he purchase a Detective camera? What evidence can you find elsewhere in the exhibition to prove that Samuel Butler used the photographic equipment he bought? Case 3 Samuel Butler painted this picture in 1856, while he was at university in the town depicted. Where did he go to university? In this case there are also some notes written out by Samuel Butler. What kind of lessons do these notes record? When did Samuel Butler write these notes?
4 Case 4 Here is a reproduction of an oil painting by Samuel Butler, which was exhibited at the Royal Academy in London in The title of the painting is Mr Heatherley s Holiday: An Incident in Studio Life. Mr Heatherley was the manager of an art school. Which skills do you think Samuel Butler practised in Mr Heatherley s studio? Samuel Butler has written his address at the top of this map. Where did he live? Which shop does this map come from? (You might recognise the name!) Lots of red lines have been drawn onto the map with a pen. What do you think these lines represent? Which modes of transport do you think Samuel Butler used to travel so many miles around the south of England?
5 Case 5 In which country is Canterbury Settlement? When was Samuel Butler s account of life in Canterbury published? This object is a sheep-brand. It was registered in the Brand Book for Canterbury, under Samuel Butler s name, on 26th November What job do you think Samuel Butler was doing at this time? Case 6 Here is a family photograph, taken when Samuel Butler was about 30. Write down three words to describe the atmosphere or people in this photograph: Samuel Butler s most famous painting is Family Prayers, dated Do you think Butler enjoyed his religious upbringing? Give a reason for your answer. Butler also wrote a novel, The Way of All Flesh, based on his family experiences, but he said it must not be published until after his death. Why do you think Butler was worried about publishing this book?
6 Case 7 Here are two books written by Samuel Butler. Based on their titles, do you think these are works of fiction (stories) or non-fiction (factual)? Which other writer is mentioned in the title of both of these books? Case 8 Look closely at this humorous sketch of Samuel Butler and the book of music that belonged to him. Which musical instrument did Samuel Butler play? Which classical composer did Samuel Butler most admire? (The composer s name is included in the drawing and on the music.) Case 9 Here is one of Samuel Butler s photograph albums, containing pictures taken in and around London. In which year were these pictures taken? Write down two things you can see in these photographs that would be different today:
7 Case 10 Match these portraits of Samuel Butler to the correct descriptions: Samuel Butler with his friends at university (about 1856) Samuel Butler a few months before his death (1901) Samuel Butler in his room at Clifford s Inn, London (about 1892) Samuel Butler in New Zealand, or shortly after his return (about 1863)
Model answer: Timeline
Teaching package: answer sheet Vincent van Gogh. An artist s struggle This graphic novel about the life of Vincent van Gogh can be used in lessons in a variety of ways and is an ideal introduction to a
YEAR 1: Kings, Queens and Leaders (6 lessons)
YEAR 1: Kings, Queens and Leaders (6 lessons) Contents Include: The United Kingdom and the Union Jack Kings and Queens The Magna Carta Charles I Parliament The Prime Minister Suggested Teacher Resources:
Victorian Museum trail pack
Victorian Museum trail pack This pack of cards is your museum trail pack covering the Victorian part of the museum. It is designed to help you explore the Victorian area of the museum and learn more about
SALE TODAY All toys half price
Name: Class: Date: KET Practice PET TestPractice Reading Test and Reading Writing KET PET Part 1 Questions 1 5 Which notice (A H) says this (1 5)? For Questions 1 5 mark the correct letter A H on your
Year 3: Famous Artists Turner Lesson 1
Year 3: Famous Artists Turner Lesson 1 Duration 1 hour. Date: Planned by Katrina Gray for Two Temple Place, 2014 Main teaching Activities - Differentiation Plenary LO: To explore Turner s work Cross curricular]
WHERE ARE YOU GOING WHERE HAVE YOU BEEN?
WHERE ARE YOU GOING WHERE HAVE YOU BEEN? LESSON PLAN FOR DAY 1 OF WHERE ARE YOU GOING WHERE HAVE YOU BEEN TITLE: WHERE ARE YOU GOING WHERE HAVE YOU BEEN INTRODUCTION OVERVIEW Students will be introduced
Teaching package EUREDUCATION
Teaching package What else do you need? The comic book, a pen and paper, the photocopy sheet, a pair of scissors, glue, a computer with an internet connection, a printer and an atlas. Have fun! EUREDUCATION,
CIVIL WAR PHOTOGRAPHY
CIVIL WAR PHOTOGRAPHY Grade level: Late elementary through middle school Estimated time: One to two class periods Specific Topic: Civil War photography Subtopic: Photograph analysis and interpretation
Dr. Jekyll and Mr. Hyde
Problematic Situation Purpose Problematic situations allow students to use problem solving skills, decision making skills, and cooperation skills as they address imaginary situations that apply to
Episode 1: Literacy Resource Pack
Episode 1: Literacy Resource Pack These resources have been written to provide teachers with starter activities and ideas relating to Episode One of Inanimate Alice. They do not constitute a complete course,
Level 2 l Intermediate
1 Warmer What do you know about William Shakespeare? Name as many of his plays as you can. 2 Key words Fill the gaps in the sentences with these key words from the text. The paragraph numbers are given
ANALYZING SHORT STORIES/NOVELS
ANALYZING SHORT STORIES/NOVELS When analyzing fiction, you should consider the plot, setting, characters, point of view, imagery, symbolism, tone, irony, and the theme. PLOT Plot refers to what happens
1. Find a partner or a small team of three or four classmates to work on this lesson.
Culture Inspiration for this lesson came from ESL Special Collection found at:. Within that website, there is Building Bridges: A Peace Corps Guide to Cross-Cultural
Religion and Science
Religion and Science Glossary Cosmology the study of the origins of the universe How did the world come into existence? Theory one Aristotle Taught that the universe has always existed and would always
A Student Response Journal for. The Invisible Man. by H. G. Wells
Reflections: A Student Response Journal for The Invisible Man by H. G. Wells Copyright 2001 by Prestwick House, Inc., P.O. Box 658, Clayton, DE 19938. 1-800-932-4593. Permission
Safe Places and Safe People
Safe Places and Safe People Lesson Plan: KS2 Age: 7-9 years Teachers Notes Page 1 Lesson Aim: To develop awareness of safe people and safe places in their life Lesson Objectives: Children can describe
Contents. Contents. Planning and assessment Planning Assessment
Contents Contents Introduction School essentials Writing essentials Essential characteristics of writers Reading essentials Essential characteristics of readers Communication essentials Essential characteristics:
Strategies Unlimited, Inc. 2007.. Activity 1
Activity 1 Postcard Create a postcard with a drawing that shows the setting of your book on one side and write a note to a friend telling them all about the book you have read. For example, Wish you could
Adapted from activities and information found at University of Surrey Website.
12: Finding Fibonacci patterns in nature Adapted from activities and information found at University of Surrey Website Curriculum connections
ebrate Poetry Month with the Poetry Workshop Kit
ebrate Poetry Month with the Poetry Workshop Kit Art from A Light in the Attic 1981 Evil Eye Music, Inc. All rights reserved. Permission to reproduce and distribute this page has been granted by the copyright
Comprehension Questions for Leveled Text
Fiction What words to you expect to come on the next page? What do you think is going to happen next by looking at the pictures? What do you think will happen at the end of the story? What do you think
THE VICTORIANS (1837 1901) - OVERVIEW
THE VICTORIANS (1837 1901) - OVERVIEW The purpose of this topic is to explore the theme of the Victorians through a creative exploration methodology across the entirety of the curriculum subjects.
What are you. worried about? Looking Deeper
What are you worried about? Looking Deeper Looking Deeper What are you worried about? Some of us lie awake at night worrying about family members, health, finances or a thousand other things. Worry do I learn something from the Bible?
Description The Bible can feel intimidating if you haven t spent much time reading it. It was written long ago by many authors in times and places you may not know much about. Learn to read and interpret
Point of View, Perspective, Audience, and Voice
Lesson Da 2 Day 1 Point of View, Perspective, Audience, and Voice A story can be told from more than one point of view. If a story is written by someone who is a character in the story, then it is said
Sunday Lesson: Family History Stories
Sunday Lesson: Family History Stories This outline is for a Sunday lesson to be taught by the bishop in a combined group of Melchizedek Priesthood holders, Relief Society sisters, and youth and singles
Looking for Lincoln Throughout His Life
GRADE LEVEL: 1-3 Looking for Lincoln Throughout His Life TIME ALLOTMENT: Two 45-minute class periods OVERVIEW: In this interdisciplinary lesson, students will gather different facts about Lincoln through
to The Ten Commandments
Introduction to The Ten Commandments This was a collaborative learning experience for our Nursery, led by Sue Thomson, Children s Minister, St Columba s Church and our Primary 7 teacher, Kara McCurrach.
Fry Instant Word List
First 100 Instant Words the had out than of by many first and words then water a but them been to not these called in what so who is all some oil you were her sit that we would now it when make find.
DesignLab: Exploring Skylines
DesignLab: Exploring Skylines through the V&A+RIBA Architecture collections Teachers Presentation Notes Teachers notes to accompany the Exploring Skylines introductory Presentation as part of At School
The War of the Worlds
Reflections: A Student Response Journal for The War of the Worlds by H. G. Wells Copyright 2002 by Prestwick House, Inc., P.O. Box 658, Clayton, DE 19938. 1-800-932-4593. Permission
Self Portrait Lesson Plans
Self Portrait Lesson Plans This lesson on self-portrait is prepared for 4 age groups: ages 5 to 7; 8 to 11; 12 to 14; 15 to 18. You can use any elements from any of the lessons for your group. You do not
First Grade Library Skills and Literature
First Grade Library Skills and Literature Lesson 1: Welcome to the Library, Review Care of Books Preparation: Set books out on back table for checkout as in kindergarten. Story corner. Review: Care;
Short-Term and Long-Term Savings Goals
Grade Five Short-Term and Long-Term Savings Goals Content Standards Overview Students share several chapters from the book The Leaves in October, by Karen Ackerman, to learn about earning an income, saving,
Writing Topics WRITING TOPICS
Writing Topics Topics in the following list may appear in your actual test. You should become familiar with this list before you take the computer-based TOEFL test. Remember that when you take the test
HSC: All My Own Work. Copyright. Introduction. Module Outline
HSC: All My Own Work Copyright Introduction This module explains copyright and its relevance to students. The Board of Studies NSW gratefully acknowledges permission to quote from and paraphrase information
Nebamun goes hunting
Nebamun goes hunting Cross-curricular literacy activities Key Stage 2 classroom resource Nebamun goes hunting Introduction Introduction This resource pack contains instructions and resources for five cross-curricular
Lesson 4 What Is a Plant s Life Cycle? The Seasons of a Tree
Lesson 4 What Is a Plant s Life Cycle? The Seasons of a Tree STUDENT SKILLS: predicting, communicating prior observations and knowledge, listening, cooperating, observing, sequencing, communicating, reasoning,
MYSTERY GENRE BOOK PROJECTS
MYSTERY GENRE BOOK PROJECTS Here is information for two FUN Mystery Genre Projects. Project 1: Reading a Mystery Chapter Book and Writing a Summary 1. Your child will select a mystery chapter book that
ANALYSING THE SHORT STORY CONTENTS
English: The Short story. 1.x/ fall 2002/lm 1/5 ANALYSING THE SHORT STORY CONTENTS THE SHORT STORY GENRE CONVENTIONS: 2 In medias res beginning: 2 A limited number of characters. 2 Limited character description:
Why Do Bad Things Happen?
Why Do Bad Things Happen? Psalm 76:10 Items Needed! Bible with marked scripture! Pencils/Crayons/Markers! Play Doe for each child! Various items you purchased at a store! 1000 piece puzzle! Safety scissors
Trip to the Zoo Performance Task Classroom Interaction
Trip to the Zoo Performance Task Classroom Interaction Resources needed: chalkboard or some manner for recording and displaying student responses projector or some manner to share photographs Setting the
GCSE Information and Communication Technology Assignments Short and Full Course
GCSE Information and Communication Technology Assignments Short and Full Course First Teaching from Autumn 2004 First Examination from Summer 2006 FOREWORD The coursework in this booklet is set).
Activities for Primary Students
This workshop outline was the one used by the Education team at the Australian War Memorial in conjunction with the Captured in colour: rare photographs from the First World War exhibition. The workshop
TEACHER S GUIDE. Teacher s Guides are developed by members of the Nine O Clock Players, an auxiliary of Assistance League of Los Angeles.
TEACHER S GUIDE Teacher s Guides are developed by members of the Nine O Clock Players, an auxiliary of Assistance League of Los Angeles. Committee Chairman: Roxanna Amdur Committee Members: Carolyn Barbian,
Student Reading Survey
Name Teacher Name Class Grade Date 1. From what you can remember, learning how to read was very easy for you easy for you hard for you very hard for you 2. What do you usually do when you read? (Check
Reading at home with your child
Reading at home with your child The Power of Reading! Creating a love of reading in children is potentially one of the most powerful ways of improving academic standards in school. There can be few
PRACTICAL 1. Lab Manual. Practical. Notes
Practical Lab Manual PRACTICAL 1 OBJECTIVE: To understand the concept of a message in communication and to learn how to construct/ write a clear message. INTRODUCTION: You have learnt to define communication
Charles Drew ABC Game
Charles Drew ABC Game Originally developed by Steve Cooke. This information gap has been revised because colleagues have pointed out that the circumstances surrounding Drew s death are not clear. Was he
Spring Term Year 1. Covering activity badges : Communicator Badge
Spring Term Year 1 Covering activity badges : Communicator Badge 1. Get someone to give you directions or instructions to do something. Check that you have understood. Then follow the directions or instructions.
I m Going To College Activity Book
I m Going To College Activity Book This activity book belongs to: Name of student who is going to college NORTHWEST EDUCATION LOAN ASSOCIATION Adapted from the California Association of Student Financial
1 SCIENCE AND NATURAL PHILOSOPHY BEFORE THE 17 TH CENTURY
1 SCIENCE AND NATURAL PHILOSOPHY BEFORE THE 17 TH CENTURY FOR TEACHERS Lesson Title: Science and Natural Philosophy Before the Seventeenth Century Area of Learning: chronology, states of affairs Aims.
Example of Practice I - Secondary School: Jane s Year 10 Science Class
Example of Practice I - Secondary School: Jane s Year 10 Science Class I have been working my way through a unit on Earth Science with my year 10 class. I am keen to get some student voice to assist me
5 DARWIN, EVOLUTION & FAITH 850L
5 DARWIN, EVOLUTION & FAITH 850L DARWIN, EVOLUTION & FAITH By John F. Haught, adapted by Newsela Nothing in modern science is more challenging to religious believers than the theory of evolution. For more | http://docplayer.net/26196208-A-victorian-writer-s-world-who-was-samuel-butler.html | CC-MAIN-2018-30 | refinedweb | 3,100 | 59.13 |
Hopfield Network
Reading time: 30 minutes | Coding time: 10 minutes
Hopfield Network is a recurrent neural network with bipolar threshold neurons. In this article, we will go through in depth along with an implementation. Before going into Hopfield network, we will revise basic ideas like Neural network and perceptron.
A neural network is a mathematical model or computational model inspired by biological neural networks. It consists of an interconnected group of artificial neurons. The sructure and functioning of the central nervous system constituing neurons, axons, dentrites and syanpses which make up the processing parts of the biological neural networks were the original inspiration that led to the developement of computational models of neural networks.
The first computational model of a neuron was presented in 1943 by W. Mc Culloch and W. Pitts. They called this model threshold logic.The model paved the way for neural network research to split into two distinct approaches. One approach focused on biological processes in the brain and the other focused on the application of neural networks to artificial intelligence.
In 1958, Rossenblatt conceived the Perceptron, an algorithm for pattern recognition based on a two-layer learning computer network using simple addition and subtractio. His work had big repercussion but in 1969 a violent critic by Minsky and Papert was published.
The work on neural network was slow down but John Hopfield convinced of the power of neural network came out with his model in 1982 and boost research in this field. Hopfield Network is a particular case of Neural Network. It is based on physics, inspired by spin system.
The Network
Hopfield Network is a recurrent neural network with bipolar threshold neurons. Hopfield network consists of a set of interconnected neurons which update their activation values asynchronously. The activation values are binary, usually {-1,1}. The update of a unit depends on the other units of the network and on itself.
A neuron in Hopfield model is binary and defined by the standard McCulloch-Pitts model of a neuron:
where ni(t+1) is the ith neuron at time t+1, nj(t) is the jth neuron at time t, wij is the weight matrix called synaptic weights , θ is the step function and μ is the bias.In the Hopfield model the neurons have a binary output taking values -1 and 1. Thus the model has following form:
where Si and ni are related through the formula: Si = 2ni - 1 (Since ni ϵ [0,1] and Si ϵ [-1,1] ). ϑi is the thresold, so if the input is above the threshold it will fire 1. So here S represents the neurons which were represented as n in equation 1. The sgn sign here is the signum function which is described as follow:
For ease of analysis in this post we will drop the threshold (ϑi = 0) as we will analyse mainly random patterns and thresholds are not useful in this context. In this case the model is written as:
Training the Network
In this post we are looking at Autoassociative model of Hopfield Network. It can store useful information in memory and later it is able to reproduce this information from partially broken patterns.
For training procedure, it doesn’t require any iterations. It includes just an outer product between input vector and transposed input vector to fill the weighted matrix wij (or synaptic weights) and in case of many patterns it is as follow:
The main advantage of Autoassociative network is that it is able to recover pattern from the memory using just a partial information about the pattern. There are two main approaches to this situation.
We update the nuerons as specified in equation 3:
- Syncronously: Update all the neurons simultaneously at each time step;
- Asyncronously: At each time step, select at random, a unit i and update it.
Implementation
Now that we have covered the basics lets start implementing Hopfield network.
import matplotlib.pyplot as plt import numpy as np nb_patterns = 4 # Number of patterns to learn pattern_width = 5 pattern_height = 5 max_iterations = 10 # Define Patterns patterns = np.array([ [1,-1,-1,-1,1,1,-1,1,1,-1,1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1.], # Letter D [-1,-1,-1,-1,-1,1,1,1,-1,1,1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,1.], # Letter J [1,-1,-1,-1,-1,-1,1,1,1,1,-1,1,1,1,1,-1,1,1,1,1,1,-1,-1,-1,-1.], # Letter C [-1,1,1,1,-1,-1,-1,1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,1,1,-1.],], # Letter M dtype=np.float)
So we import the necessary libraries and define the patterns we want the network to learn. Here, we are defining 4 patterns. We can visualise them with the help of the code below:
# Show the patterns fig, ax = plt.subplots(1, nb_patterns, figsize=(15, 10)) for i in range(nb_patterns): ax[i].matshow(patterns[i].reshape((pattern_height, pattern_width)), cmap='gray') ax[i].set_xticks([]) ax[i].set_yticks([])
Which gives the out put as :
We now train the network by filling the weight matrix as defined in the equation 4
# Train the network W = np.zeros((pattern_width * pattern_height, pattern_width * pattern_height)) for i in range(pattern_width * pattern_height): for j in range(pattern_width * pattern_height): if i == j or W[i, j] != 0.0: continue w = 0.0 for n in range(nb_patterns): w += patterns[n, i] * patterns[n, j] W[i, j] = w / patterns.shape[0] W[j, i] = W[i, j]
Now that we have trained the network. We will create a corrupted pattern to test on this network.
# Test the Network # Create a corrupted pattern S S = np.array( [1,-1,-1,-1,-1,1,1,1,1,1,-1,1,1,1,1,-1,1,1,1,1,1,1,-1,-1,-1.], dtype=np.float) # Show the corrupted pattern fig, ax = plt.subplots() ax.matshow(S.reshape((pattern_height, pattern_width)), cmap='gray')
The corrupted pattern we take here simply edditing some bits in the pattern array of letter C. We can see the corrupted pattern as follow:
We pass the corrupted pattern through the network and it is updated as defined in the equation 3. Thus, after each iteration some update is applied to the corrupted matrix. We take the hamming distance of the corrupted pattern which is being updated every time and all the patterns. And then we decide the closest pattern in terms of least hamming distance.
h = np.zeros((pattern_width * pattern_height)) #Defining Hamming Distance matrix for seeing convergence hamming_distance = np.zeros((max_iterations,nb_patterns)) for iteration in range(max_iterations): for i in range(pattern_width * pattern_height): i = np.random.randint(pattern_width * pattern_height) h[i] = 0 for j in range(pattern_width * pattern_height): h[i] += W[i, j]*S[j] S = np.where(h<0, -1, 1) for i in range(nb_patterns): hamming_distance[iteration, i] = ((patterns - S)[i]!=0).sum() fig, ax = plt.subplots() ax.matshow(S.reshape((pattern_height, pattern_width)), cmap='gray') hamming_distance
Here we see that the hamming distance between corrupted pattern and third pattern i.e. letter C has become 0 after few iterations thus correcting the corrupted pattern.
We can also see the plot for all the hamming distances below:
| https://iq.opengenus.org/hopfield-network/ | CC-MAIN-2020-05 | refinedweb | 1,221 | 55.34 |
Hey guys,
So I just started learning Java this year so you can say I'm fresh off the boat. Though I've learned programming concepts before (from Turing). Right now, I'm experiencing some difficulty in comparing/checking if a certain character is upper-case or lower-case.
This simple program just asks for the user to input a word/phrase and whatever letter is lower-case, I change it to upper-case and whatever letter is upper-case, I change it to lower-case.
import java.util.*; class UpperLower { public static void main() { String userInput; Scanner input = new Scanner (System.in ); System.out.println ("Please enter something...:"); userInput = input.nextLine(); String copyInput = userInput; for (int num = 0; num < userInput.length(); num++) { if (Character.isUpperCase(userInput.charAt(num))){ (userInput.substring(num)).toLowerCase(); } else { (userInput.substring(num)).toUpperCase(); } } System.out.println (userInput); } }
There seemed to be no compiler error however, when I tested my program, the letters' case were still unchanged. I'm not sure what is wrong with my code (perhaps it has to do with my if-condition?).
Please give this a try and see what is wrong. I really do appreciate your efforts, time and help. Thank you very much in advance! | http://www.javaprogrammingforums.com/whats-wrong-my-code/8164-switching-letter-cases-user-input%3B-why-not-working.html | CC-MAIN-2015-14 | refinedweb | 205 | 50.43 |
10:00 *** Log started on 1999-12-03 UTC-0500 *** 10:00 [RRSAgent] *** RRSAgent (swick@seahorse.w3.org) has joined channel #w3c 10:01 [larsga] *** larsga (larsga@pc-larsga.infotek.no) has joined channel #w3c 10:01 [mjs] Hello, also fairly new to mIRC, and IRC in general. 10:01 [sdo56] *** sdo56 (sdorshan@unknown-40-162.beasys.com) has joined channel #w3c 10:01 [DV_] mjs: hi, it's rather intuitive, no thick manual needed 10:01 [DanC] ok... note well: this channel is logged: 10:02 [DanC] better known as: 10:02 [DanC] OK... 10:02 [DanC] I'm Dan Connolly, of W3C, writing from Austin, Texas. Anyone else care to introduce yourself likewise? 10:03 [DV_] Daniel Veillard W3C Grenoble, France 10:03 [StevenPemberton] Steven Pemberton, Chair of the HTML WG, Amsterdam, The Netherlands 10:03 [mjs] Mike Spreitzer, Xerox Palo Alto (California) Research Center 10:03 [janet] Janet Daly, W3C/MIT 10:03 [CurtA] Curt Arnold, AEA Technology Engineering Software- Hyprotech, Houston, TX 10:03 [Lew] Lew Shannon, NCR, from sunny South Carolina 10:03 [jpsa] John Aldridge, Cambridge, England. 10:04 [SusanL] Susan Lesch, an XHTML onlooker in San Diego, California 10:04 [sdo56] Scott Orshan, BEA Systems 10:04 [Al] Al Gilman, W3C/WAI/PF, Arlington VA, USA 10:05 [Bert] *** Bert (bbos@lanalana.inria.fr) has joined channel #w3c 10:05 [DanC] Hi Bert; we've been introducing ourselves: name, affiliation, city where you're writing from. 10:06 [DanC] So... I haven't really prepared an agenda; Any suggestions? Questions? What's on your mind? 10:06 [DanC] Is anybody here hacking on XML tools? 10:06 [Bert] OK, I'm Bert Bos, located in Sophia Antipolis (south of France), working for W3C 10:06 [henry] Henry Thompson, University of Edinburgh and W3C, XML Schema structures editor 10:07 [DV_] I got a question yesterday on taht channel, someone asked if this could be open on a continuous basis rather than during scheduled times (like telcon) 10:07 [Bert] I'm expecting a phone call, so my attention to this window may be limited. 10:07 [DanC] hm... need an ice-breaker. 10:07 [DV_] IMHO this is better in IRC spirit to have a continuously open channel, but one need somewhat of a community to make it lively 10:08 [Bert] Hi Daniel. I prefer asynchronous communication (e-mail) 10:08 [DV_] Bert: for me both has advantage and drawbacks ... 10:08 [CurtA] Anyone interested in talking about schemas? 10:08 [Al] Apple pie: there is a place for IRC, Slashdot, email, and formal draft cycles. Just have to discern what belongs where. 10:08 [DanC] what about schemas, Curt? Do you have a question? 10:09 [CurtA] curious about the upcoming changes to floating point data, dateTime, etc. Are doc elements in the Dec16 draft, etc 10:10 [CurtA] All without violating the W3C process. 10:10 [DanC] Curt, I'm curious too! Hard to say what the Dec16 draft will say until Dec16. 10:10 [henry] I can't speak about float, think that's in already (Nov 6), but doc will be coming, yes 10:11 [henry] This is close to an issue we're still discussing, namely "How open to user additions should schemas be"? 10:11 [DanC] Curt, do you have a particluar application you're trying to use schemas for? 10:12 [CurtA] Modeling engineering systems (car parts, chemical plants, heat exchangers). I build UML models, translate the XMI to XML Schema. Unambigiuous definitions are vitally important 10:12 [henry] Unambiguous in what sense? 10:12 [DanC] unambiguous in what sense? 10:12 [DanC] ;-) 10:13 [CurtA] Clearly documented so that others can build systems that don't do something like misinterpret the units and send spacecrafts plunging into the martian landscape 10:13 [DaveR] *** DaveR (dsr@slip139-92-229-45.war.uk.prserv.net) has joined channel #w3c 10:14 [DanC] Hi Dave. We've been introducing ourselves: name, affiliation, city where you're writing from today. 10:14 [DaveR] Dave Raggett, W3C/HP, near Bath in the west of England. 10:14 [DanC] Curt, I had an interesting discussion with somebody about ambiguity of dates; folks seem to write dates without timezones, but assume a timezone. 10:15 [Al] I have experience with this, CurtA, we should talk at more length offline. 10:15 [DaveR] This also crops up for expiry dates on credit cards in order forms. 10:15 [henry] Right, well the issue of units is actually a tricky one, but in general the XML Schema language itself will define the meaning of only a modest part of its vocabulary, namely the simple string types such as float, timePeriod, etc. 10:15 [DaveR] and is an issue for work on XForms - mapping presentation to internal data values. 10:15 [Al] Dan, I think that Cowan and I covered that, perhaps in private mail. Its a frames-based knowledge issue and there is a pretty clear model for it 10:16 [CurtA] The processors don't need to be aware of it, but it does need to be clearly communicated the the developers of the systems. 10:16 [henry] In particular, we do NOT currently envisage providing built-in measurement units 10:16 [henry] So NASA still have to take responsibility :-) 10:16 [DanC] It seems to me we should treat dates a little bit like floating-point numbers; 1.732 has some fuzz around it; 1999-12-03 should be seen a roughly 36 hour period centered at 1999-12-03T12:00Z 10:16 [Al] There are post-processors that need to be aware, and operate on the XML-built DOM. 10:17 [CurtA] I agree with that (and I've commented on that in the W3C comments list). However, I need to provide that interpretation to developers through schema documentation 10:17 [Al] For science and Engineering Aps, the extension path through schemata needs to be there to make precise your model of the fuzz. 10:17 [henry] That's another good point -- as it stands the DOM still speaks only of 16-bit strings at the end of the day: do people want/expect more than that? 10:20 [DanC] DOM talks about 16-bit chunks as encoding strings, but they allow surrogates; all unicode characters can go through the DOM (as I understand it). 10:20 [DanC] (hm... 36 hour or 48 hour? anyway...) 10:20 [Lew] I have one...Where are the dependencies for fragments? Is it a show stopper? 10:21 [CurtA] I was thinking that a DOM that used type specific nodes (real nodes, etc) would be faster than allocating all those strings, however I was suprised that conversion to double was slower than string allocation. I'm not sure on that. However, I sure that a lot of my types of apps only use strings as a way to represent numbers 10:22 [larsga] this is what is nice about untyped languages: this whole problem just disappears 10:22 [CurtA] It just moves 10:22 [larsga] I'm really looking forward to the combination of Python DOM and schema types 10:22 [larsga] interface-wise it disappears 10:23 [mjs] DanC: your frame is too small. Sometimes a date is just a date. 10:23 [larsga] shouldn't the frame size be app-dependent? 10:24 [Al] The tolerance frame should only be spread if the locale in which the date is stated cannot be determined. 10:25 [CurtA] Some of the problems that I had with dateTime was that you couldn't easily constrain it to the limitations of dateTime types widely supported. If you allow the omission stuff in the ISO rep, you've got to be able to state in the schema that a date has to be a specific date 10:25 [Al] I don't believe in "just a date" until you tell me what compare operations are required on dates. 10:26 [Al] the ISO -mm-dd elliptical pattern is ambiguous, for example. Has two interpretations of a repeat pattern day-of-the-year or day of context-supplied year. 10:26 [mjs] Al: huh? Date < Date; Date = Date; Date > Date. Isn't that obvious? 10:26 [DaveR] Does a date have to have a timezone? How do I tell from a credit card expiry field e.g. "03/00" 10:27 [CurtA] I think that you need to be able to require a time zone in a schema. But without that facet, it can be omitted 10:27 [DaveR] Sounds reasonable 10:27 [henry] Folks, I feel like we're rat-holing a bit -- how about a non-XML Schema topic? 10:28 [DanC] other topics are always welcome, but I don't want to squelch any discussion 10:28 [larsga] ok, how do people feel about SML? 10:28 [mjs] What about XML Simplification? IS that being pursued anywhere? 10:28 [larsga] that's what SML is 10:28 [larsga] a proposal from Don Park on xml-dev 10:28 [mjs] Yeah. Sanctioned by W3C? 10:29 [larsga] btw: I'm Lars Marius Garshol, STEP Infotek, Oslo, Norway (forgot that) 10:29 [CurtA] STEP-XML interoperability might be a good topic for later 10:29 [DaveR] SML raises the issue of variations across XML processors, e.g. validating or non-validating, but that is just the tip of the iceberg 10:29 [mjs] What I meant is, is the W3C going to form a WG on it, or just see what develops on XML-DEV? 10:30 [DV_] Well, IIRC such a "cleanup" was attempted, but we didn't got that much support 10:30 [mjs] And do you folks think it is a good idea? 10:30 [larsga] is it conceivable that if SML 'succeeds' the W3C will adopt it? 10:30 [DV_] The problem is define what is in and what is not, and each application case may have a different boundary :-) 10:30 [DanC] W3C has not plans to persue SML at this time; ironically, we *did* charter a WG to try it, but that WG (the XML Syntax WG) never reached consensus on requirements, so we dropped it. In short: been there, done that; good luck! 10:31 [DV_] mjs: I did put my personal opinion on xml-dev, basically it's sound to define a subset so taht one can build and share tools 10:31 [mjs] DanC: Yeah, I can imagine the SML effort going that way too 10:32 [CurtA] I'm pessimistic on SML, but if Don and his disciples put together something reasonable, let them submit a W3C Tech Node 10:32 [DV_] mjs: but it's hard to do a clean cut everybody will be interested into 10:32 [DaveR] But that still leaves open the interoperability problems e.g. my xml processor does schemas but yours only does DTDs - do we need a profiling mechanism? 10:32 [DV_] CurtA: s/Tech Node/NOTE/ 10:32 [CurtA] Expect misspellings at the end of a message, enter key is too close. 10:33 [DV_] DaveR: that's why i also clearly state if SML accepted non well formed XML I would fight against it :-) 10:33 [CurtA] to close. 10:33 [mjs] Hey, some apps will only need a single fixed schema; some will need only a restricted class of schemas. Those won't have interoperability problems. 10:33 [zurvan2] *** zurvan2 (abryant@h00a02401c38d.ne.mediaone.net) has joined channel #w3c 10:33 [DV_] mjs: what I'm afriad of is specialized stuff wich would not be reuseable by generic one 10:34 [Al] The records the Aps create need to interoperate. no Ap is an island. 10:34 [DanC] I don't think we need a profiling mechanism; interoperability at the well-formedness is guaranteed; other stuff is layered on top. That's how I see it. 10:34 [mjs] DV: Specialized software is OK. Really. 10:34 [mjs] Al: I'm assuming SML will be a subset of XML. So an SML record would be understandable to a general XML processor. 10:35 [DaveR] That does appear to be the intention 10:35 [larsga] at the moment it's not a subset, though 10:35 [mjs] The really scary thing is the multitude of schema languages: DTD, Microsoft schemas, W3C Schemas, ... 10:35 [CurtA] Profiling of parsers I don't see the need for. But it would be a good think, if an app could state that a) I accept documents that adhere to some schema but b) only those that have additional constraints like all country codes must be US 10:36 [DaveR] Don't forget DCDs 10:36 [aki--] *** aki-- (aki@193.166.158.93) has joined channel #w3c 10:36 [CurtA] How about the XSLT based validation proposals 10:36 [larsga] seem rather complementary to the others to me 10:36 [DanC] XSLT-based validation is an interesting idea; XSLT is turing-complete, so of course it could, in theory, support XML 10:37 [DanC] ... XML Schemas per se. 10:37 [larsga] (btw, it's XPath-based more than XSLT-based, really) 10:37 [larsga] I believe CurtA is thinking of the schematron, which uses XPath 10:37 [Waldbaer] *** Waldbaer (koch@westerland.pixelpark.com) has joined channel #w3c 10:37 [CurtA] There is another one too announced on xml-dev in the last few weeks. 10:38 [Waldbaer] hi there 10:38 [DV_] hi 10:38 [larsga] CurtA: what's the name? 10:39 [CurtA] My understanding is minimal, but I think they don't give you guidance on how to construct a document so something like Xeena based on schematron would be difficult 10:39 [mjs] I'm interested in using schemas as one of several inter-converted ways of declaratively describing data (which are going to be authomatically converted based on that metadata); computation-based schemas look pretty unpleasant for that 10:39 [Al] Yes, but the criteria should be in a standard KR like RDF. (as opposed to active XSLT) 10:39 [Waldbaer] :-) My name is Johannes Koch, an aerospace student in Berlin.de. I work at Pixelpark 10:40 [DV_] Waldbaer: :-) 10:41 [Al] What's best forum to continue date drivel? I have more... 10:42 [CurtA] I'd be up for more date drivel, maybe in another chat room or later 10:43 [DV_] Al: why not here, unless others want to change topic 10:43 [DaveR] No, dates are something I need to deal with for the XForms work at W3C 10:43 [Al] My sense is Henry was right, not to devote this hour to that rathole. But I want to know where we should take the thread. 10:44 [aki--] *** aki-- (aki@193.166.158.93) has joined channel #w3c 10:44 [DV_] If someone want to raise another topic, just feel free to put it on the table, the chair (i.e. the IRC op) is a robot so he doesn't care :-) 10:45 [DanC] another topic: Does everybody know how to find stuff in ? 10:45 [DaveR] # Appears as ANNA 10:46 [CurtA] I know how to find tech notes and process, but what other stuff (non W3C member) 10:46 [DV_] CurtA: we have a generic search engine at 10:47 [DV_] It does index all the Web site and the mailing-lists archives 10:47 [DanC] does everybody know where to send feedback on specs? how to find the archive? (usually, we have the relevant links, but sometimes...) 10:47 [CurtA] That is how I found the process docs, but you do need to know that something might exist before you search 10:47 [Al] I have had mixed results with search.w3.org; probably need some way to get questioner-based META keys or some such. 10:47 [DV_] CurtA: right 10:49 [CurtA] Does the amount of public comment on the specs seem too much (or too unreasoned) or too little 10:50 [janet] Some relevant comments arrive and are quite useful - some comment lists are rather quiet. 10:51 [janet] And there are multiple fora (like xml-dev) where matters are discussed, but are not w3c lists per se 10:52 [Al] I have been thinking about the Slashdot discussion engine as a friendly amendment to the way we currently communicate on Web engineering concerns. 10:53 [CurtA] xml-dev is nice in that you get some feedback as to whether your idea has any value in persuing (or if anyone else is interested). It is fairly rare to know if you are recovering stuff that the WG is already aware of or are talking heresy in the comment archives 10:55 [CurtA] Any thoughts on adding back minimal list data types (decimals, reals, etc) to schema? 10:56 [DaveR] (#G>10E@10M1) There is a big push to move to decimal arithmetic for ECMAScript, which will effect how people script apps 10:56 [DanC] So... anything anybody needs before we wrap up? The channel will stay open indefinitely, but I'm not sure who will be watching after the top of the hour. 10:56 [DanC] Curt, decimals, floats, and doubles are in the schema spec; they were never taken out. 10:57 [SusanL] I'd like to know when XHTML is expected to reach recommendation or note. The HTML Roadmap says January, based on the last version. 10:57 [DV_] CurtA: you think that installing the /. engine on a server at w3C and launching debate here would be useful ? 10:57 [CurtA] Sorry, "decimals" not "decimal" a white space separated list of decimal values 10:57 [DanC] ah! that's what you mean by list data types. Hm... 10:58 [larsga] DV_: I think no. the interface is IMHO terrible. give me news groups any day. 10:58 [CurtA] DV_: debate on what? 10:59 [Al] Debate on: what's the real demand/requirement for 'validation' functions? 10:59 [janet] CurtA: I think DV meant discussions 10:59 [DV_] CurtA: W3C related activities, say last version of the xyz spec 10:59 [CurtA] ECMAScript decimal: maybe as an option, but I really need to do float calcs 11:01 [DV_] Al: for example 11:01 [Al] People interested in date/time classes and XML reps for them stay in touch with DaveR c/o XML Forms. OK Dave? 11:01 [DaveR] (#G210E010M1) Sure 11:01 [CurtA] Do you coordinate with schema? 11:02 [DanC] Dave, did you see SusanL's question? XHTML is still expected to be done January-ish, right? 11:02 [DaveR] (#G610E210M1) We expect to go to PR again very shortly for XHTML 1.0 11:02 [SusanL] OK, thanks. 11:02 [StevenPemberton] It has entered the cycle for PR already 11:03 [CurtA] I put some comments on the schema comments list on dateTime. I'll have to reread them again myself and have refined my thoughts since then too 11:03 [Al] DV: see Megginson on why clients don't validate to content models on XML Plenary (part of number of namespaces discussion). I mean trying to wrestle this divide to a We agree on X, we disagree on Y level of refinement. 11:04 [janet] Please watch for an announcement on the document re-entering Proposed Recommendation. 11:04 [janet] document=XHTML 1.0 11:04 [Al] Does the log disclose emails of participants? 11:05 [DanC] the log discloses whatever crossed the channel, only: 11:05 [CurtA] We didn't do emails in our intro: I'm CurtA@hyprotech.com 11:05 [DanC] I note RRSAgent is still around, and still logging; I'm not sure how long that will be the case. 11:06 [Al] Sayonara 11:06 [StevenPemberton] steven.pemberton@cwi.nl 11:06 [StevenPemberton] bye 11:06 [SusanL] Thank you all for being here. Good day! 11:06 [larsga] larsga@garshol.priv.no 11:06 [StevenPemberton] *** StevenPemberton (steven.pem@adsl-145-99-72-162.snelnet.nl) has left channel #w3c 11:06 [larsga] /leave 11:06 [larsga] *** larsga (larsga@pc-larsga.infotek.no) has left channel #w3c 11:07 [DaveR] I'm off (a presentation to write), cheers 11:07 [DaveR] *** DaveR (dsr@slip139-92-229-45.war.uk.prserv.net) has left channel #w3c 11:07 [DanC] Thank you all for coming! 11:07 [DanC] Any thoughts on doing this again sometime? 11:07 [DanC] Perhaps on a different topic at W3C? 11:08 [mjs] bye 11:08 [CurtA] henry: still space on your tutorial on Sunday? I haven't made my mind up yet 11:08 [mjs] *** mjs (spreitze@phobos.parc.xerox.com) has left channel #w3c 11:09 [henry] I don't know -- GCA is in charge! 11:10 [aki--] DanC: I am interested in the World Wide Web accessible to mobile devices 11:10 [waxthenip] *** waxthenip (hroi@jonazty.christiania.org) has joined channel #w3c 11:11 [DanC] for the log: pointers to the CFP news:38457E5B.D018C9EA@w3.org 11:11 [DanC] ah... I'll look into that, Aki. 11:12 [ErikL] *** ErikL (.@dialup-209.246.85.27.NewYork2.Level3.net) has left channel #w3c 11:12 [CurtA] CFP? 11:12 [DanC] Aki, have you seen the recent CFP for a workshop... 11:12 [DanC] 1999-11-17: Call for participation: Joint W3C-WAP Forum workshop on "Position 11:12 [DanC] dependent information services". Deadline for position papers: 20 December, 1999. 11:12 [aki--] DanC: Thanks :) 11:12 [DanC] 11:12 [aki--] DanC: I will read it 11:13 [aki--] DanC: I read it. Good to know. Thanks. 11:14 [Lew] bye all cu next week 11:15 [Lew] *** Lew (lew.shanno@ppp098.conterra.com) has left channel #w3c 11:16 [CurtA] DanC: Austin, do you have an affliation other than W3C? 11:17 [DanC] no, I'm W3C XML Activity Lead. It's what I do for a living. 11:17 [DanC] see 11:17 [CurtA] Nice place to do it. 11:17 [DanC] I telecommute. 11:18 [CurtA] henry: I think you post to the STEP-XML mail exploder. What are your thoughts on migration of traditionally STEP domain problems to XML 11:20 [Waldbaer] Why is XHTML1.0 back in WD status? What were the problems in the PR? 11:21 [CurtA] Use of three namespaces seemed to be the primary reason dfor the veto (w3c outsider) 11:21 [DanC] c.f. 11:21 [DanC] Fw: XHTML 1.0 returned to HTML WG 11:21 [DanC] Tim Berners-Lee (timbl@w3.org) 11:21 [DanC] Wed, 3 Nov 1999 16:33:41 -0500 11:21 [DanC] 11:22 [DanC] Somebody referred to xml-dev as "not a W3C list, per se"; Just FYI: I see xml-dev as the primary public discussion forum for XML. I don't think it would be constructive for W3C to host a separate public discussion forum for XML. 11:22 [CurtA] The three namespaces hinted at the need to distinguish between what a app can handle (i'm a minibrowser who can't do frames) and what a schema can express (I can express frames and more) 11:23 [CurtA] I would be nice if this expression of "I'm an app that can't handle everything in this schema but..." be done in a consistent manner with schema. 11:26 [CurtA] Leaving now, for those of you going, have a good time in Philly 11:26 [CurtA] *** CurtA (CurtA@cs27107-230.houston.rr.com) has left channel #w3c 11:30 [jpsa] Thanks for the invitation -- I'll be here if you do this again 11:50 *** Log ended on 1999-12-03 *** | http://www.w3.org/1999/12/w3c-irc2409 | CC-MAIN-2016-07 | refinedweb | 3,951 | 70.43 |
MSMQ on Pocket PC 2003
Introduction
A few years ago, mainstream software development was all about desktops and servers, both being Personal Computers. This is rapidly changing as more and more devices emerge. Today's world has Smartphones, Pocket PCs, Tablet PCs, Media Centers, and many more to emerge. As complex as it is to understand all these devices and their differences, Microsoft has made it equally complex to understand the different Windows brands—Windows Embedded, Windows CE, Windows Mobile, and so forth. A few years ago, it seemed to be cool and bleeding edge to support different devices other then the mainstream PC. But, as more devices emerge and as it becomes easier to develop software for those devices, the more rapidly consumers and corporations will adopt them. A few years from now, it will be essential to support such devices and for developers to have experience with development on such devices. This article builds on top of the existing article "MSMQ, your reliable asynchronous message processing." It will show how MSMQ can be used on Pocket PC 2003 and at the same time provide an introduction to mobile development and the Compact Framework (CF).
Understanding the Different Windows Brands
Microsoft uses three main Windows brands. Each brand is targeted towards a different set of devices. There are gray areas among the different brands, but the device to support will determine which Windows version to use:
- Windows Embedded—This encompasses all versions of Windows targeted towards any device other then the PC (desktop and server). Windows Embedded consists of two main brands: Windows XP Embedded and Windows CE.
- Windows XP Embedded—This is a componentized version of Windows XP Professional. Thus, you select from the existing Windows XP Professional components which ones you want to include in your OS image. This allows you to create smaller OS images for different devices while still supporting any Windows-based application (as long as the components the application requires are included in the OS image). Windows XP Embedded only supports Intel x86 hardware and is not a real-time OS. Examples would be kiosks, retail devices, ATMs, and so forth.
- Windows CE—This is a real-time operating system that also supports platforms other than Intel x86. It is not bound to a specific device, but rather contains components to support a wide variety of small devices.
- Windows Mobile—Microsoft created Windows Mobile to provide a rich experience for end users as well as to provide strict guidelines for Pocket PCs and Smartphones. Windows Mobile only runs on devices that support the Windows Mobile standard. The three main types of devices supported are:
- Pocket PC—Windows-based PDAs that support WiFi and Bluetooth and provide mobile Word, mobile Excel, mobile Outlook, and more.
- Smartphones—Mobile phones that also support e-mailing, text messaging, Web browsing, and instant messaging.
- Pocket PC phone editions—For devices that combine PDA-type features with your mobile phone. This supports all features of Pocket PC and Smartphone.
Microsoft also ships a Compact Framework used to build .NET applications for Windows CE and Windows Mobile (both Windows Pocket PC and Windows Smartphone).
Building Your Pocket PC 2003 Application
When you create a new project, you can select the project type (list on the left side). Under Visual Basic and Visual C#, you see an entry called "Smart Device." Underneath it you find Pocket PC 2003, Smartphone 2003, and Windows CE. These are the three different devices you can use the Compact Framework on and which VS.NET 2005 allows you to create applications for. You can create for each an application (Windows forms), class library, or control library (not supported for Smartphones). This by default references the Compact Framework. Under the references, you also suddenly see an "mscorlib", which is the "mscorlib" for the Compact Framework. When you add new references, you see also that the list is smaller. That is because the Compact Framework only supports a subset of the full framework. The Compact Framework 2.0 added the System.Messaging assembly/namespace, which provides full support for MSMQ on Pocket PC and Windows CE but not for Smartphones.
Windows forms are available for all three devices and differ from the traditional desktop Windows forms in that the screen size available is much smaller. The designer shows a fixed-size window that reflects the size available on selected devices. How to add controls through the toolbox, how to position and resize it, how to set its properties, and how to add event handlers is the same as for the traditional desktop Windows forms. The list of properties and events will be shorter because not all are supported by the Compact Framework, or more specifically by the devices themselves.
When running the application, the VS.NET IDE shows a deployment dialog. You can choose where to deploy and run the application. VS.NET provides Emulators so you can run and test the applications without requiring an actual physical device. Emulators are available for Pocket PC 2003, Smartphone 2003, and Windows CE 5.0. You also can choose a form factor, meaning the skin used when showing the device in the emulator. For example, you can choose between a "Pocket PC 2003 Portrait" and a "Pocket PC Phone 2003 Portrait."
Running on a Pocket PC 2003 Emulator
Choose "Pocket PC 2003 SE Emulator" to deploy and run your application on the Pocket PC Emulator. This starts a virtual machine and loads the Pocket PC 2003 OS into that virtual machine. Devices such as Pocket PCs and Smartphones can utilize an Intel x86 processor or an ARM (Advanced RISC Machines) processor. The emulators that come with VS.NET are emulating ARM-based devices. All device emulator images are stored in the following location: "C:\Program Files\Microsoft Visual Studio 8\SmartDevices\Emulators\Images". You find the Pocket PC image under the sub folder "PocketPC\2003\1033" and the Smartphone image under the sub folder "Smartphone\2003\1033".
Note: Keep in mind that because emulators are emulating a Pocket PC or Smartphone, they will always be slower then an actual device itself.
The emulator window shows a Pocket PC booting up, like a real Pocket PC. It then asks in the emulator window whether the Pocket PC is connected to the Internet or Work; choose "The Internet." Because this is the first time the emulator is started and no Compact Framework is yet loaded, VS.NET first deploys the Compact Framework onto the emulator. After that, VS.NET again shows the dialog to choose where to deploy the application (it is unclear to me why this is required, but if you always deploy to the same device or emulator you can unselect the option "Show me this dialog each time I deploy the application"). Now, VS.NET starts deploying your application files onto the Pocket PC emulator. When completed, VS.NET will start the application on the Pocket PC while remotely connecting to it so you can debug the application remotely. In this example, it will show an exception as soon as a System.Messaging type gets loaded and called. This is the case because MSMQ is not yet installed and configured on your Pocket PC emulator.
You can tell the VS.NET IDE to upload not just the project files but also any other files you need to get onto the Emulator. The MSMQ redistributable files can be found at the following location: "C:\Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\SDKRedist\MSMQ". Because the emulator is ARM-based, you take them from the ARM sub folder. Add all six files to the project and set "Build Action" in the file properties (in VS.NET) to "Content". All files marked as content will be deployed in the same folder as your project. To change the location where your application is deployed, bring up the Project properties (in VS 2005, double-click the item Properties). Go to the "Device" tab and change the "Output file folder." This by default always points to "\Program Files" followed by your project name. Also, any files you marked with "Content" in the build action are deployed into this folder. To deploy your application again, run it again, or choose "Build | Deploy Solution." After redeploying the application, go to the Pocket PC emulator window so you can set up MSMQ on it.
The Basics of Using the Pocket PC Emulator
The Emulator shows you Pocket PC as it would be on any real Pocket PC device. In the upper-left corner, you see the "Windows start button." Click the start button and it will show the start menu. Select "Programs" to bring up the installed programs, one of them being the "File Explorer." Open the "File Explorer" by double-clicking it; by default, it shows the "My Documents" folder. Click on the white space at the bottom of the file explorer and keep the mouse pressed till the popup menu shows. Select from the "View All Files" menu so we see all files. Right under the Windows start button in the upper left corner, it shows "My Documents" with a down arrow. This is your current location; clicking the down arrow brings up a menu. Click it and select "My Device" to jump to the root folder of your device.
Next, double-click "Program Files." This shows the "Program Files" folder where you see a "NET CF 2.0" folder where VS.NET deployed the Compact Framework as well as an "MSMQ Pocket PC" folder where your application has been deployed. Now, you want to copy the MSMQ redistributable files to the Windows folder. Go to the "MSMQ Pocket PC folder" and select the following six files (by holding down the CTRL key and clicking on each file): visadm, msmqrt, msmqd, msmqadmext, mqoa, and msmqadm. Click one of the selected files and hold down the mouse until the popup menu shows; then select "Copy." Next, again click the arrow beside the current folder location (right under the Windows start button) and select "My Device" from the menu. This again shows the root folder of the device. Double-click the "Windows" folder, press the END key to jump to the end of the file list, click an empty space, hold the mouse key down till the menu appears, and select "Paste." Now, all six files have been copied to the Windows folder.
Next, we configure MSMQ on this Pocket PC. This requires changing the default Pocket PC name. Click the Windows start button and select "Settings" from the start menu. Select the "System" tab at the bottom and then double-click the "About" icon in the list. This shows the Windows "about" screen. Select the tab "Device ID" at the bottom; it shows the current Device name as "Pocket_PC." Change the name to something like "EnterpriseMinds" and click the Ok button in the upper-right corner. This brings you back to the Settings screen that you can close with the "X" in the upper-right corner. This brings you back to the File Explorer that still shows the files you copied into the Windows folder. Double-click "visadm" to open the visual MSMQ administrator console. Click the "Shortcuts" button and select "Install" from the menu. Click the "Shortcuts" button again and select "Register" this time.
Next, we need to restart the Pocket PC for the changes to take effect. Click the "Exit" button to close "visadm" and next, on the Emulator window itself, click the "Power button" (upper-right corner). This will ask you if you are sure; say yes, which shuts down the device, shows a black screen, and then boots it up again (this may take a while). Now, we have reset the device and we want to check whether MSMQ has been set up properly. Go back to the File Explorer, which now also appears in the start menu and by default jumps back into the Windows folder. Start "visadm" again, click the "Shortcut" button, and select "Verify". This shows that MSMQ has been properly installed. Now, we can go back and run our sample application. First, close "visadm" with the "X" in the upper-right corner, as well as the File Explorer. Run the sample application from your VS.NET IDE again; this will re-deploy any changed files. Then, launch the sample application while still being connected to it remotely so you can debug through the VS.NET IDE.
There are no comments yet. Be the first to comment! | http://www.codeguru.com/csharp/csharp/cs_misc/sampleprograms/article.php/c8295/MSMQ-on-Pocket-PC-2003.htm | CC-MAIN-2015-48 | refinedweb | 2,088 | 64.41 |
HTML5 - Microdata
Microdata is a standardized way to provide additional semantics in your web pages.
Microdata lets you define your own customized elements and start embedding custom properties in your web pages. At a high level, microdata consists of a group of name-value pairs.
The groups are called items, and each name-value pair is a property. Items and properties are represented by regular elements.
Example
To create an item, the itemscope attribute is used.
To add a property to an item, the itemprop attribute is used on one of the item's descendants.
Here there are two items, each of which has the property "name" −
<html> <body> <div itemscope> <p>My name is <span itemprop="name">Zara</span>.</p> </div> <div itemscope> <p>My name is <span itemprop="name">Nuha</span>.</p> </div> </body> </html>
It will produce the following result −
Properties generally have values that are strings but it can have following data types −
Global Attributes
Micro data introduces five global attributes which would be available for any element to use and give context for machines about your data.
Properties Datatypes
Properties generally have values that are strings as mentioned in above example but they can also have values that are URLs. Following example has one property, "image", whose value is a URL −
<div itemscope> <img itemprop="image" src="tp-logo.gif" alt="TutorialsPoint"> </div>
Properties can also have values that are dates, times, or dates and times. This is achieved using the time element and its datetime attribute.
<html> <body> <div itemscope> My birthday is: <time itemprop="birthday" datetime="1971-05-08"> Aug 5th 1971 </time> </div> </body> </html>
It will produce the following result −
Properties can also themselves be groups of name-value pairs, by putting the itemscope attribute on the element that declares the property.
Microdata API support
If a browser supports the HTML5 microdata API, there will be a getItems() function on the global document object. If browser doesn't support microdata, the getItems() function will be undefined.
function supports_microdata_api() { return !!document.getItems; }
Modernizr does not yet support checking for the microdata API, so you’ll need to use the function like the one listed above.
The HTML5 microdata standard includes both HTML markup (primarily for search engines) and a set of DOM functions (primarily for browsers).
You can include microdata markup in your web pages, and search engines that don't understand the microdata attributes will just ignore them. But if you need to access or manipulate microdata through the DOM, you'll need to check whether the browser supports the microdata DOM API.
Defining Microdata Vocabulary
To define microdata vocabulary you need a namespace URL which points to a working web page. For example can be used as the namespace for a personal microdata vocabulary with the following named properties −
name − Person name as a simple string
Photo − A URL to a picture of the person.
URL − A website belonging to the person.
Using about properties a person microdata could be as follows −
<html> <body> <div itemscope> <section itemscope <h1 itemprop="name">Gopal K Varma</h1> <p> <img itemprop="photo" src=""> </p> <a itemprop="url" href="#">Site</a> </section> </div> </body> </html>
It will produce the following result −
Google supports microdata as part of their Rich Snippets program. When Google's web crawler parses your page and finds microdata properties that conform to the vocabulary, it parses out those properties and stores them alongside the rest of the page data.
You can test above example using Rich Snippets Testing Tool using
For further development on Microdata you can always refer to HTML5 Micordata. | http://www.tutorialspoint.com/html5/html5_microdata.htm | CC-MAIN-2016-30 | refinedweb | 602 | 50.97 |
Odoo Help
This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.
How to generate automatic sequence number in one2many field?
I want to generate sequence number in purchase.requisition.line. Below is my code. Can anyone please correct me?
class purchase_requisition(osv.osv):
_inherit = 'purchase.requisition'
def update_seq(self, cr, uid, ids, line_ids, context=None):
print "line_ids",line_ids
new_order_line = []
counter = 1
x = {}
for line in line_ids:
if line[0] in [1,4]:
line[0] = 1
if type(line[2]) == type({}):
line[2].update({'serial_no':counter})
print "counter1",counter
#x = counter
else:
line[2] = {'serial_no':counter}
print "counter2",counter
#x = counter
counter = counter + 1
print "counter",counter
x = new_order_line.append(line)
print "new_order_line",new_order_line
return {'value': {'line_ids': x} }
class purchase_requisition_line(osv.osv):
_inherit = 'purchase.requisition.line'
def update_seq(self, cr, uid, ids, line_ids, context=None):
print "line_ids",line_ids
new_order_line = []
counter = 1
for line in line_ids:
if line[0] in [1,4]:
line[0] = 1
if type(line[2]) == type({}):
line[2].update({'serial_no':counter})
print "counter1",counter
else:
line[2] = {'serial_no':counter}
print "counter2",counter
counter = counter + 1
print "counter",counter
new_order_line.append(line)
print "new_order_line",new_order_line
return {'value': {'serial_no': new_order_line} }
_columns={
'serial_no':fields.integer('Serial No'),
}
_order = 'serial_no desc, serial_no, id'
_defaults = {'serial_no': 1,
}
purchase_requisition_line()
I didnt get the output.
Hello Rosey,
Here I wrote simple code to generate next sequence for one2many field.
step1: pass your one2many field it self in property context from xml.
<field name="ref_ids" context="{'ref_ids':ref_ids}"/>
step2: override the name_get method of one2many field model
def default_get(self, cr, uid, ids, context=None):
res = {}
if context:
context_keys = context.keys()
next_sequence = 1
if 'ref_ids' in context_keys:
if len(context.get('ref_ids')) > 0:
next_sequence = len(context.get('ref_ids')) + 1
res.update({'sequence': next_sequence})
return res
Note :consider line)ids is your one2many field name in your model you need to pass and use whatever your field you have used and sequence is field name for sequence in one2many fields' model. in your case might be different.
Hope this will useful for you.
Thank you..
its default_get function you don't need to call it will automatically called by openerp framework when you click on add item button it will be call automatically.
if 'line_ids' in context_keys: what the if condition means? thanks for the quick response
function is not working from if 'line_ids' in context_keys: what i need to check. please help me...
I have improved code now check it. I have used line_ids. but instead line_ids you need to use your field. replace line_ids with your one2many field.
@Anil, I tried your code. But there is a problem, if a record is deleted. For instance, 1,2,3,4,5.. I deleted sequence=4. then according to your code, the next sequence will be len(list)=4 so 4+1==> 5. didnt get step 1 and step 2. can you please explain?.
i tried but its not working. i will try again | https://www.odoo.com/forum/help-1/question/how-to-generate-automatic-sequence-number-in-one2many-field-67834 | CC-MAIN-2016-50 | refinedweb | 508 | 60.82 |
POSIX Inter-process Communication (IPC)
IPC is used for real-time extensions. These message queues are a part of Linux. These calls are used as a standard now but might be a part of contemporary versions. These calls are easy to implement with a much cleaner interface.
POSIX Message Queues in Linux
V message queues in a Linux system are identified using keys that are obtained using ftok calls. These POSIX message queues usually use name strings. In Linux systems, POSIX queues are called strings. These strings are considered to start with / and then have other characters. Processes that follow and know the name of the queue name with appropriate rights can send or receive messages to and from the queue. This will help in performing important functionalities.
What Are POSIX Message Queue Calls?
POSIX message queues must link with any library that exits for real. Following are a few calls that are used:
Call names begin with the mq_prefix
The details of Queue Calls are discussed below:
>> mq_open, mq_close
This function is used to open up a POSIX queue.
Mq_open is a function that is used to call the name of the queue. The next parameter is a flag used to receive the messages. O_WRONLY is used to send messages, and O_RDWR is used to send and receive operations within the queue. Users can use the O_NONBLOCK flag to specify the queue to the non-blocking mode and mq_send and mq_receive to send and receive data in a queue.
Syntax
The syntax for the above queue call is displayed below:
/* used to open the files */
#include <sys/stat.h>
/* to determine a file based on the path */
#include <mqueue.h>
/* to include message queue descriptions */
mqd_t mq_open (const character *name, int oflag);
/* to open up and access the queue */
mqd_t mq_open (const character *name, int oflag, mode_t mode,
struct mq_attribute *attribute);
Mq_Flags: Could be O or non-block
Mq_MaxMsg: Maximum number of messages that can be entered inside the queue
Mq_Msgsize: Maximum number of bytes in a message
Mq_CurMsgs: Currently sent messages within a queue
mq_close calls: To close all of the queue descriptors.
mq_notify
It is a call used to register and unregister arrival notification when a message enters an empty queue.
Syntax
/* to include all of the message queue descriptions from the code */
int mq_notify (mqd_t mqdes, const struct sigevent *sevp);
/* to notify the arrival of the message in a queue */
mq_unlink
It is used to remove the queue having queue_name.
Syntax
/* To remove the queue having name as queue_name */
mq_getattr, mq_setattr
This function has an attribute structure:
struct mq_attr is used as a message queue for descriptors.
mq_setattr is used for setting the attributes inside a queue.
Syntax
int mq_getattribute(mqd_t mqdes, struct mq_attribute *attribute);
int mq_setattribute(mqd_t mqdes, const struct mq_attribute *newattribute,
struct mq_attribute*oldattr);
Example: Client-Server Communication via POSIX
The following is an example of performing client-server communication via POSIX message queues. In the example, we will have a client file and server file.
We will have two files: the first (server) file is server.c, and the other (client) file is client.c.
Server Code
The image displayed below shows the code that we used for client-server communication. First, we called some libraries to define the strings, variables, and functions. Then, we defined the fcntl function and the name of the queue server. After that, we defined the name of the server queue, followed by its message size and buffer size, to define the size of messages to fit our buffer at a time. Next, we called and described the queues, then we generated the next tokens to see the client response once it was sent to the client. Finally, the confirmation was completed by printing the message from the server end. In the next section, you will see the flags discussed in the earlier section.
We initialized all flags, including mq_flags, mq_maxmsgs, etc. to proceed with storing requests. Then, we applied the condition to the name of the server and stored the messages in the queue buffer. After this, at the time of storage, we ensured that the queues followed a first-come-based priority rule. At the end, the code displays a failure message if there are any errors received from the client-end. Finally, we exited the server to send the request to the client.
Save the server.c file
Client Code
We will now discuss the second file. The image displayed below is the code we used for the client-server communication. The code began by calling standard libraries and defining variable headers. Then, we defined the strings and all types of data. After that, we declared the header of the queue to define the server queue name. Next, we defined the permission queues and message size inside the queue, along with the size of the message buffer (the maximum size that could fit inside the queue).
We will describe the queues and create a new client to receive the messages sent from the end of the server. Then, we will call the flags and initialize them, and call the client-end function. It will exit the function in the case of an error. The value is stored inside the buffer, and a request response is sent to the server. In case of a response, the server will then provide the token, which is printed once the client end has entered the input. In case of an error, it will return the error values, i.e., the client has not been able to send a message to the server. After that, we will exit the client.
Save the client.c file
Executing the Files
We are using a gcc compiler to execute the files. To run the server end file, type the appended command in the terminal window:
Next, type the following:
The output will appear as follows:
Moving on to the client response, type the following:
Then run the following:
The output will appear as follows:
Conclusion
In this article, you learned how to send POSIX Message Queues with C programming, as well as some of its functions. Then, you saw some examples of this process in greater detail. | https://linuxhint.com/posix-message-queues-c-programming/ | CC-MAIN-2022-05 | refinedweb | 1,034 | 71.24 |
Illegal Prime Number Unzips to DeCSS
CmdrTaco posted about 13 years ago | from the allright-thats-pretty-friggin-clever dept.
.
Isn't that whole DeCSS thing getting kind of old? (1)
Anonymous Coward | about 13 years ago | (#355825)
Re:In other news.. (1)
Anonymous Coward | about 13 years ago | (#355826)
The best reason why 1 is not considered prime is so that the Fundamental Theorem of Arithmetic can be stated elegantly. The Fundamental Theorem of Arithmetic is that every natural number has a unique prime factorization. If 1 were prime that factorization would not be unique. But if you're not into hardcore math then you can call 1 whatever the heck you want since everybody will still know what you talking about.
'Gotta love that math! (1)
Anonymous Coward | about 13 years ago | (#355827)
Re:Hmmm... (Hey moderators) (1)
Anonymous Coward | about 13 years ago | (#355828)
Like evrything, moderation should be done in moderation.
Re:Hmmm... (2)
Anonymous Coward | about 13 years ago | (#355830)
Re:Hmmm... (2)
Anonymous Coward | about 13 years ago | (#355831)
Re:Isn't that whole DeCSS thing getting kind of ol (2)
Anonymous Coward | about 13 years ago | (#355832).
Useful math? (1)
Indomitus (578) | about 13 years ago | (#355834)
</sarcasm>
Re:Hmmm... (1)
MassacrE (763) | about 13 years ago | (#355840)
Hmm.. (5)
Chacham (981) | about 13 years ago | (#355841)
---
ticks = jiffies;
while (ticks == jiffies);
ticks = jiffies;
Other uses of primes (2)
acb (2797) | about 13 years ago | (#355846)
Re:Isn't that whole DeCSS thing getting kind of ol (2)
dattaway (3088) | about 13 years ago | (#355851)
Tomorrow's Headlines Today (5)
Just Some Guy (3352) | about 13 years ago | (#355852)
RIAA Petitions Congress To Ban Number Theory
Mathematicians Declared "Enemy of Intellectual Property (and the American Way)"
Rambus Patents Prime Numbers
Any guesses about which one you'll see first?
:)
Re:Hmm.. (1)
heretic (5829) | about 13 years ago | (#355858)
Re:In other news.. (2)
ocie (6659) | about 13 years ago | (#355862)
Re:Numbers and hyperlinks (1)
dwlemon (11672) | about 13 years ago | (#355873)
Re:In other news.. (1)
HeghmoH (13204) | about 13 years ago | (#355874)
Of course, does it really matter?
Re:In other news.. (1)
HeghmoH (13204) | about 13 years ago | (#355875)
Re:Hmmm... (2)
HeghmoH (13204) | about 13 years ago | (#355876)
So, I guess what I'm saying is, yeah, that's probably what happened, but so what?
Easy--infinite number of primes (4)
crow (16139) | about 13 years ago | (#355881):Hmm.. (1)
ibis (16191) | about 13 years ago | (#355882)
Re:Isn't that whole DeCSS thing getting kind of ol (1)
Teun (17872) | about 13 years ago | (#355886)
Re:Shorter code (1)
wavelet (17885) | about 13 years ago | (#355887)
Another illegal prime, efdtt.c (5)
wavelet (17885) | about 13 years ago | (#355888)
Incredibly Cool... (1)
augustz (18082) | about 13 years ago | (#355889)
Re:Easy--infinite number of primes (3)
platypus (18156) | about 13 years ago | (#355892):Hmmm... (1)
mTor (18585) | about 13 years ago | (#355895)
And now for something completely different...
Let me digress a bit... I checked your homepage and I agree 100% with what you said right here:
It's amazing how now things changed. Check this link:
I think that this passage from 1984 sums it all up the best:
Hmmm... (5)
mTor (18585) | about 13 years ago | (#355896):numbers and itellectual property (3)
mindstrm (20013) | about 13 years ago | (#355898) (5)
dutky (20510) | about 13 years ago | (#355899)
Re:Hmmm... (2)
YoJ (20860) | about 13 years ago | (#355900)
numbers and itellectual property (5)
Saint Nobody (21391) | about 13 years ago | (#355901).
Hmm.. (2)
abelsson (21706) | about 13 years ago | (#355904):In other news.. (prime) (1)
proffi (21949) | about 13 years ago | (#355905)
1 is NOT prime!
(see e.g. "Kleine Enzyklopädie Mathematik", p. 24, Verlag Harri Deutsch, Frankfurt, 1984)
Apart from that little question, I still have to verify the claim deposited on that
Don't conform!
IkKampfProfessor75
Hee hee hee. (1)
ChrisGoodwin (24375) | about 13 years ago | (#355908)
--
Re:In other news.. (1)
suraklin (28841) | about 13 years ago | (#355910)
In other news.. (1)
PovRayMan (31900) | about 13 years ago | (#355915)
- Age
- Math Class
- Slashdot UIDs
- Programming
Judge Sipowitz was then sued by CmdrTaco because of his slashdot uid. CmdrTaco is also suing for emotional damages...
(I asked a bunch of people on IRC if 1 was a prime number. I got lot of yes and no responses. Then again turning to IRC for help? I must be crazy.)
----------
Windows 2000 encoded to a single number! (5)
alex@thehouse (43299) | about 13 years ago | (#355920)... (2)
cyberdonny (46462) | about 13 years ago | (#355921)... (2)
cyberdonny (46462) | about 13 years ago | (#355922)
Trailing zeroes (1)
alehmann (50545) | about 13 years ago | (#355926)
Number and the GPL (1)
alehmann (50545) | about 13 years ago | (#355927)
...Which brings up an interesting question... can a _number_ be GPL'd? What about patented? This scheme allows basically any computer program to be represented as a number, and if you want a prime all you have to do is append trailing garbage (ignored by gzip) until the number is prime.
Re:What about binaries... (1)
alehmann (50545) | about 13 years ago | (#355928)
A-HA (3)
mr100percent (57156) | about 13 years ago | (#355930)
BTW, doesn't the MPAA's address have the number 666 in it? Or am I thinking of another corp.?
--Never trust a tech who tattoes his IP to his arm, especially if its DHCP.
You can reduce this further. (5)
TrevorB (57780) | about 13 years ago | (#355934)
However determining this number would be (ludicrously) computionally expensive. Another quest for distributed.net?
Why work on the CSS code, why not the keys themselves? That would be more interesting.
One: prime or composite? (1)
Cantara (68186) | about 13 years ago | (#355940)
+-1 is a unit.
Re:Isn't that whole DeCSS thing getting kind of ol (4)
dbrutus (71639) | about 13 years ago | (#355944)
Reminds me of the Crystal Rod Encyclopedia (5)
Speare (84249) | about 13 years ago | (#355954):Easy--infinite number of primes (1)
cheese_wallet (88279) | about 13 years ago | (#355958)
I don't know if you could always find such a prime number, but I have a gut feeling that such a number exists for each case.
Oh grow up! (2)
donutello (88309) | about 13 years ago | (#355959)
What about binaries... (2)
jmv (93421) | about 13 years ago | (#355960)
Re:Hmmm... (2)
OmegaDan (101255) | about 13 years ago | (#355966)
I can't wait for the t-shirt
:)
Re:Sans Tables? (1)
BradleyUffner (103496) | about 13 years ago | (#355973)
=\=\=\=\=\=\=\=\=\=\=\=\=\=\=\=\=\=\=\=\
Pre-Slashdot Effect? (1)
rograndom (112079) | about 13 years ago | (#355978)
prime directive (2)
jafuser (112236) | about 13 years ago | (#355979)
--
EFF Member #11254
Re:In other news.. (2)
(void*) (113680) | about 13 years ago | (#355982)
Where 1 is a prime or not is largely a matter of contention. But you certainly cannot call it a composite number, for then all other prime numbers would have to be composite as well.
Re:One: prime or composite? (2)
(void*) (113680) | about 13 years ago | (#355983)
LOL. (1)
kormoc (122955) | about 13 years ago | (#355986)
Re:Hmm.. (2)
hrieke (126185) | about 13 years ago | (#355989)
Numbers and hyperlinks (1)
pallex (126468) | about 13 years ago | (#355990)
Perhaps we'll find out soon whether numbers CAN be illegal - not just very very long ones, such as a cd (or religious secret), but short or natural ones.
Re:numbers (1)
pallex (126468) | about 13 years ago | (#355991)
So a database of prime numbers would have to exclude certain numbers? What year do you think it will be when the last country with internet access on earth bows to the wishes of an American judge and orders a such a database to be taken off line? I dont think it will happen this year, anyway?
Primster? (2)
pallex (126468) | about 13 years ago | (#355992)?
Patent Office closing early today. (1)
crashnbur (127738) | about 13 years ago | (#355994)
*low growl*
Higher Text book prices (2)
Adler (131568) | about 13 years ago | (#355995)
I'm gonna go start work on "Texter" an internet text book trading programme.
Re:In other news.. (1)
jedwards (135260) | about 13 years ago | (#355998)
Re:Incredibly Cool... (2)
jedwards (135260) | about 13 years ago | (#355999)
Re:Hmmm... (1)
coolgeek (140561) | about 13 years ago | (#356003)
Re:Isn't that whole DeCSS thing getting kind of ol (2)
Salsaman (141471) | about 13 years ago | (#356004)
This prime number _IS_ deCSS. The MPAA will either have to ban this prime number, ban gzip, or ban anyone from telling people that the number is deCSS.
Either way, I don't see this getting through the courts, even in the US...
Re:1984 online? (2)
elegant7x (142766) | about 13 years ago | (#356008)
Rate me on Picture-rate.com [picture-rate.com]
length == precision (2)
elegant7x (142766) | about 13 years ago | (#356009)
Rate me on Picture-rate.com [picture-rate.com]
numbers (1)
gunner800 (142959) | about 13 years ago | (#356010)
Just how persuasive is that? I don't know. Windows is copyrighted; the bigass number is not.
I suspect the final outcome will be some judge saying "too bad" and declaring this number illegal without actually explaining himself.
My mom is not a Karma whore!
CSS not an honest attempt at encryption (2)
Dram (149119) | about 13 years ago | (#356015)
Re:Hmm.. (1)
d_pirolo (150996) | about 13 years ago | (#356016)
Shorter code (1)
Pxtl (151020) | about 13 years ago | (#356017)
Re:Hmm.. (2)
chipuni (156625) | about 13 years ago | (#356026)
One advantage (1)
eric434 (161022) | about 13 years ago | (#356029)
DeCSS old, but an illegal number is certainly inte (2)
TeknoHog (164938) | about 13 years ago | (#356035)
This also raises the interesting question whether you could take any pattern in nature, filter it through some (legal) algorithm and get DeCSS. You could always (in principle) hack such a filter that produced the DeCSS code out of any pattern you happen to choose. Because there number of such patterns is infinite, there would be an infinite number of filters (including all filters already written). But since they cannot outlaw nature (I hope), all filters would become illegal.
However, the above scenario is so absurd that the only conclusion is: you just can't outlaw DeCSS!-)
--
Not just DeCSS! (4)
Dyolf Knip (165446) | about 13 years ago | (#356036):Isn't that whole DeCSS thing getting kind of ol (1)
dadragon (177695) | about 13 years ago | (#356043)
Segfault wallpaper (2)
Alien54 (180860) | about 13 years ago | (#356048)
one of those pretty random number things, and then get is distributed on the free downloads sites as a windows theme....
share the wealth.
Re:48565...2944 (1)
Ratcrow (181400) | about 13 years ago | (#356049)
Re:Hmm.. (1)
Ratcrow (181400) | about 13 years ago | (#356050)
Re:Hmm.. (1)
bn557 (183935) | about 13 years ago | (#356065)
Excellent (2)
ZanshinWedge (193324) | about 13 years ago | (#356071)
Ya know, this battle of wits between the DVD CCA / MPAA and the hackers of the world is not going particularly well for the corporate interests.
every code is just a number... (1)
ponxx (193567) | about 13 years ago | (#356072)
The one reason this is interesting though is that it highlights an important question about code (and speach in general), does someone "create" it, or does one just "find" it. If I write a programme and combile it I could say I just researched for a while to come up with the hexadecimal number that executes to run a word processor...
Maybe, I can claim prior art on all code by just writing down a mathematical representation for all natural numbers (e.g. the commonly used N) + an algorithm for converting it into code (such as the change to hexadec. and gunzip it, or just rename to
.exe and execute it). I have in effect written down all possible computer programmes, just because someone else "found" one of them as well does not mean I don't hold my rights to it :), and just because i haven't tested every single one of them, does not mean they don't exist...
It might be worth trying to get a US patent on all code that can be obtained from a single number
:) (i.e. all code)
Irony (2)
OverCode@work (196386) | about 13 years ago | (#356078)
-John
Portable (1)
perlyking (198166) | about 13 years ago | (#356079)
--
Write an encryption program with this (1)
guinsu (198732) | about 13 years ago | (#356080)
Sans Tables? (3)
Mr. Polite (218181) | about 13 years ago | (#356088)
Woohoo (3)
kosipov (218202) | about 13 years ago | (#356089)
Enough with the Java and Perl script... (1)
AFCArchvile (221494) | about 13 years ago | (#356091)
Re:Enough with the Java and Perl script... (1)
AFCArchvile (221494) | about 13 years ago | (#356092)
Re:Hmm.. (1)
ThymePuns (222253) | about 13 years ago | (#356093)
Great.... (1)
codewolf (239827) | about 13 years ago | (#356102)
Re:Shorter code (1)
samrolken (246301) | about 13 years ago | (#356104)
I would like to see an illegal prime number.
Re:Hmm.. (2)
Anoriymous Coward (257749) | about 13 years ago | (#356106)
--
#include "stdio.h"
Someone has to say it (3)
Joey7F (307495) | about 13 years ago | (#356115)
Re:48565...2944 -- NOT!! (1)
xkenny13 (309849) | about 13 years ago | (#356117)
or what if... (2)
screwballicus (313964) | about 13 years ago | (#356122)
- Someone writes a java app capable of searching Pi for a number series identical to the ASCII values of the text they wish to tranfer.
- Upon finding this series, the location of it in Pi is transferred in a format something like "12137-12193" meaning "the message begins at place 12137 and ends at place 12193"
- Bingo. Your recipient has the message and all you transferred was two completely unrelated numbers.
Then again, maybe Pi is illegal.
48565...2944 (1)
KingFOOL (314876) | about 13 years ago | (#356123) | http://beta.slashdot.org/story/17124 | CC-MAIN-2014-15 | refinedweb | 2,298 | 79.9 |
Test-Driven Development
TDD is an iterative development process. Each iteration starts with a set of tests written for a new piece of functionality. These tests are supposed to fail during the start of iteration as there will be no application code corresponding to the tests. In the next phase of the iteration, Application code is written with an intention to pass all the tests written earlier in the iteration. Once the application code is ready tests are run..
Benefits of TDD
- Unit test proves that the code actually works
- Can drive the design of the program
- Refactoring allows improving the design of the code
- Low-Level regression test suite
- Test first reduce the cost of the bugs
Drawbacks of TDD
- Developer can consider it as a waste of time
- The test can be targeted on verification of classes and methods and not on what the code really should do
- Test become part of the maintenance overhead of a project
- Rewrite the test when requirements change
If we were to summarize this as phases in the development process we can write as
Phase 1 (Requirement Definition)
We will take a simple example of a calculator application and we will define the requirements based on the basic features of a calculator. For further simplicity, we will condense the calculator application to a simple java class named
public class Calculator{
}
In phase 1 application requirements are gathered and defined. Taking the example of a simple calculator we can say that in iteration 1 we would like to implement
1. The ability to add two numbers
2. The ability to subtract two numbers
3. The ability to multiply two numbers
At this time we will open Eclipse or any Java IDE of your choice and create a Java project called Calculator. In the project, we will create two folders (Src & Tests). Src will contain all the application code which is the code of calculator application and the Tests folder will contain all the tests. We will be using Junit tests here. If you are not familiar with Junit already. Take a look at our Junit tutorial.
So as said earlier TDD starts with defining requirements in terms of tests. Let's refine our first requirement in terms of tests
Requirement 1: Calculator should have the ability to add two numbers.
Test 1: Given two numbers of positive numbers (10 and 20) calculator should be able to add the two numbers and give us the correct result (30)
Test 2: Given two negative numbers (-10 and -20) calculator should be able to add the two numbers and give us the correct result (-30)
This list of tests will go on and also for each requirement. In phase 1 all we have to do is to write tests for all the requirements. At this point in time, in the Calculator application, we will just have a class called Calculator.
package source; public class Calculator { }
We will write all our tests against this class. Here is how our Test 1 will look like. We will put all our Adding tests in a class called AddingNumbersTests
package AppTests; import org.junit.Assert; import org.junit.Test; import source.Calculator; public class AddingNumbersTests { private Calculator myCalculator = new Calculator(); public void addTwoPositiveNumbers() { int expectedResult = 30; int ActuaResult = myCalculator.Add(10, 20); Assert.assertEquals("The the sum of two positive numbers is correct" , expectedResult, ActuaResult); } public void addTwoNegativeNumbers() { int expectedResult = -30; int ActuaResult = myCalculator.Add(-10, -20); Assert.assertEquals("The the sum of two negative numbers is correct" , expectedResult, ActuaResult); } }
Now the very first thing that will come to our mind is that the Calculator class doesn't have any methods and in our tests, we have used a method named Add() on calculator class. This will give us a compilation error. Well, that's the whole point of writing the tests first. This will force us to add only the code that's necessary. Ignoring the compilation error, let's just move on to the next step.
Phase 2: Executing Tests
In this phase, we will simply run our tests. Let's do it one by one
Attempt 1: When we run our tests for the first time we will get this error message
java.lang.Error: Unresolved compilation problem: The method Add(int, int) is undefined for the type Calculator
This error clearly states that Add method is not present in the Calculator class. In details, you can see in this screenshot
Phase 3: Adding/Refactoring code
After the test failure in the previous step, we will take a logical action and we will simply add a method called Add in our Calculator class and make it return 0 for the time being. Now our Calculator class will look something like this
package source; public class Calculator { public int Add(int number1, int number2) { return 0; } }
With this change, we will move to the next step that is rerun our tests. Which is nothing but Phase 2 mentioned earlier. Let's see what is the test result that we get this time.
Results from the two tests is
java.lang.AssertionError: The the sum of two positive numbers is incorrect expected:<30> but was:<0> at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
And
java.lang.AssertionError: The the sum of two negative numbers is incorrect expected:<-30> but was:<0> at org.junit.Assert.fail(Assert.java:88)
Now with this test failure, we conclude that addition of two positive and negative numbers is not happening properly. Based on the test failure we will add just enough code that these two tests pass. As we do this we move to the next phase which is Phase 3. This phase is already describer earlier. I will just show you how the code of our Calculator will look like after this phase
package source; public class Calculator { public int Add(int number1, int number2) { return (number1 + number2); } }
Now we will run our tests Phase 2. The test results after this change will make all our tests pass. Once all the tests will pass we will conclude that our Iteration has been completed. Tests results:
Once all the tests pass it signals the end of iteration. If there are more features that need to be implemented in your product, product will go through the same phases again but this time with new feature set and more tests.
Summarizing it in a figure can be done like this
With this understanding of TDD we will move to BDD. Which will form the basis of understanding Gherkin and eventually Cucumber.
Join me in the next tutorial to learn more.
Similar Articles
| https://www.toolsqa.com/cucumber/test-driven-development-tdd/ | CC-MAIN-2022-27 | refinedweb | 1,113 | 61.36 |
Opened 9 years ago
Closed 9 years ago
Last modified 6 years ago
#6209 closed (fixed)
FormPreview never passes security_hash validation when a BooleanField is set to False
Description
when you give a boolean field in Form preview, and you give the boolean field "False" value, Django will not commit correctly.
First, if i press "preview" button, it will preview my form content correctly, but next i press "submit" button, Django give the boolean
field "True" value unexpected, and stay at this page. Next, i press "submit" button again in this page(now the boolean field has "True" value), Django can commit correctly...
this is my model
class TestPreForm(models.Model): test = models.CharField(max_length=20, null=True, blank=True) is_test = models.BooleanField(default=False)
this my views
class TestPreFormPreview(FormPreview): def done(self, request, cleaned_data): _test = cleaned_data['test'] _is_test = cleaned_data['is_test'] TestPreForm.objects.create(test = _test, is_test = _is_test) return render_to_response('preform/form_ok.html', {'test':_test, 'is_test':_is_test})
this is my urls
(r'^preform/preview/$', TestPreFormPreview(forms.models.form_for_model(TestPreForm))),
Attachments (3)
Change History (21)
comment:1 Changed 9 years ago by
comment:2 Changed 9 years ago by
comment:3 Changed 9 years ago by
comment:4 Changed 9 years ago by
Original poster was asked for more information. No feedback since 6 weeks. Closing it. Please reopen if the bug
is still in the latest trunk and more information is given.
comment:5 Changed 9 years ago by
I've also hit this problem.
I have a field,
beta_test = BooleanField(required=False).
When I submit the form with the checkbox unticked, the preview renders as I expect: the template snippet "
{% if form.beta_test.data %}True{% else %}False{% endif %}, {{ form.beta_test.data }}" renders as "
False, False".
However, when I confirm the submission, the preview page is re-rendered, the previous snippet rendering "
True, False"; the contents of the
<form>, with the exception of the
hash field, are identical but for the ordering of attributes within the various
<input> fields.
If the field is ticked for the original preview, the submission works as expected first time (the preview snippet producing "
True, on").
comment:6 Changed 9 years ago by
comment:7 Changed 9 years ago by
comment:8 Changed 9 years ago by
comment:9 Changed 9 years ago by
comment:10 Changed 9 years ago by
I'll take a crack at this.
Changed 9 years ago by
Patch fixes issue and adds a unit test for this case
comment:11 Changed 9 years ago by
comment:12 Changed 9 years ago by
Changed 9 years ago by
comment:13 Changed 9 years ago by
comment:14 Changed 9 years ago by
comment:15 Changed 9 years ago by
Ticket #7038 was marked as a duplicate of this, but will not be fixed unless security_hash in wizard.py is patched as well. Maybe the fixed version of security_hash should be moved elsewhere so both FormPreview and FormWizard can share it. Either the patch for this ticket needs to fix FormWizard as well, or #7038 needs to be reopened.
Changed 9 years ago by
Revised patch to share security hash implementation between preview and wizard
comment:16 Changed 9 years ago by
Latest patch works very nicely for me. Thanks everyone.
comment:17 Changed 9 years ago by
comment:18 Changed 6 years ago by
Milestone 1.0 deleted
Is this in latest trunk? Can you add a paste of the preview form html to dpaste? This should be handled correctly, if the hidden field has the value 'True' or 'False' | https://code.djangoproject.com/ticket/6209 | CC-MAIN-2017-22 | refinedweb | 591 | 61.26 |
I'm trying to use the importlib library to verify whether the nmap library is installed on the computer executing the script in Python 3.5.2
I'm trying to use
importlib.util.find_spec("nmap")
>>> import importlib
>>> importlib.util.find_spec("nmap")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'importlib' has no attribute 'util'
#!/usr/bin/pythonw
import importlib
from importlib import util
#check to see if nmap module is installed
find_nmap = util.find_spec("nmap")
if find_nmap is None:
print("Error")
Try this:
from importlib import util util.find_spec("nmap")
I intend to investigate, but honestly I don't know why one works and the other doesn't. Also, observe the following interactive session:
>>> import importlib >>> importlib.util Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'importlib' has no attribute 'util' >>> from importlib import util >>> util <module 'importlib.util' from '/usr/lib/python3.5/importlib/util.py'> >>> importlib.util <module 'importlib.util' from '/usr/lib/python3.5/importlib/util.py'>
So...yeah. I am sure this makes perfect sense to someone, but not to me. I will update once I figure it out.
Comparing this to something like:
>>> import datetime >>> datetime <module 'datetime' from '/usr/lib/python3.5/datetime.py'> >>> datetime.datetime <class 'datetime.datetime'>
I think the difference is that in this case the first
datetime is a module and the second is a class, while in the
importlib.util case both are modules. So perhaps
module.module is not OK unless the code from both modules has been loaded, while
module.class is OK, because the class code is loaded when the module is imported.
Nope, it seems like in many cases
module.module is fine. For example:
>>> import urllib >>> urllib <module 'urllib' from '/usr/lib/python3.5/urllib/__init__.py'> >>> urllib.error <module 'urllib.error' from '/usr/lib/python3.5/urllib/error.py'>
So perhaps it is something specific to
importlib. | https://codedump.io/share/AMR97JWzLO52/1/error-when-using-importlibutil-to-check-for-library | CC-MAIN-2016-44 | refinedweb | 325 | 53.07 |
I just found out about a really interesting use of Python, that Red Hat Emerging Technology is developing called func. This was in a recent article at Red Hat Magazine, who I happen to write for as well btw.
We will be covering some examples of func in our book. At a high level though, func allows you to administer machines with python and python scripts. Here are a few examples from their front page:
import func.overlord.client as fc client = fc.Client("*.example.org;*.example.com") # package controls! client.yum.update() # service controls! client.service.start("acme-server") # hardware info! print client.hardware.info() # etc ... etc ..
I really like this example too, of rebooting all machines running http:
results = fc.Client("*").service.status("httpd") for (host, returns) in results.iteritems(): if returns == 0: fc.Client(host).reboot.reboot()
It is great to see Python use exploding at Red Hat. The cobbler/PXE boot project is also quite cool.
Func plus Amazon EC2 seems like a match made in heaven! Create a virtual server farm on Amazon for $0.10 per server, then script your administration work using func. Awesome! | http://www.oreillynet.com/onlamp/blog/2008/02/red_hats_emerging_technology_g.html | crawl-002 | refinedweb | 191 | 61.63 |
X applications that load fonts had a *heavy* delay at startup time if using the
en_US.UTF-8 locale. The delay doesn't occur if the locale is set to
en_US.iso88591, or C.
I discovered the error with XEmacs, but it only happens with MULE. The bug also
happens in xfontsel and xman. The delay doesn't occur in xclock, for example. My
guess is because xclock doesn't use fonts. The bug is very easy to reproduce
(with LC_ALL unset):
$ LANG=en_US.UTF-8 xfontsel # delay
$ LANG=en_US.iso88591 xfontsel # no delay
$ LANG=C xfontsel # no delay
I'm not sure if the bug is related to Xft, fontconfig, or something else. I'm
reporting it here because I don't know better.
I'm using Gentoo, with X.org 6.8.4. Originally I reported the bug in Gentoo:
My locale is en_GB.UTF-8 setup as described at.
When starting Eterm with this locale there is a 2 minute (!) delay in the call
to XCreateFontSet. During this time the X process is consuming 100% of the cpu.
Changing the locale to C reduces the startup time to 8 seconds.
I also get the delay with xman and xfontsel.
strace shows lots of calls like:
read(3, 0xbfc68c80, 32) = -1 EAGAIN (Resource temporarily
unavailable)
backtrace:
0 0xffffe410 in __kernel_vsyscall ()
#1 0xb7bf521d in select () from /lib/tls/libc.so.6
#2 0xb7cbc56b in _XWaitForReadable () from /usr/lib/libX11.so.6
#3 0xb7cbc9ad in _XRead () from /usr/lib/libX11.so.6
#4 0xb7cbdbc6 in _XReply () from /usr/lib/libX11.so.6
#5 0xb7ca142f in XListFonts () from /usr/lib/libX11.so.6
#6 0xb7f23bc3 in get_font_name () from
/usr/lib/X11/locale/lib/common/xomGeneric.so.2
#7 0xb7f240cb in parse_fontdata () from
/usr/lib/X11/locale/lib/common/xomGeneric.so.2
#8 0xb7f2539c in create_oc () from /usr/lib/X11/locale/lib/common/xomGeneric.so.2
#9 0xb7cd89b1 in XCreateOC () from /usr/lib/libX11.so.6
#10 0xb7cd7c35 in XCreateFontSet () from /usr/lib/libX11.so.6
#11 0xb7f433c3 in create_fontset (font1=0x804f930 "fixed",
font2=0xb7f964e8
"-misc-fixed-medium-r-semicondensed--13-*-75-*-c-*-iso10646-1") at command.c:1759
#12 0xb7f4444d in init_locale () at command.c:1801
#13 0xb7f46afb in init_command (argv=0xfffffdfe) at command.c:2996
#14 0xb7f82340 in eterm_bootstrap (argc=1, argv=0xbfbc5f04) at startup.c:331
#15 0x0804857e in main (argc=-514, argv=0xfffffdfe) at main.c:31
Apparently the default glibc utf-8 locale performance just plain sucks
(). There are some hints in the unicode faq on optimising the code.
Possibly a dupe of #2475?
See also: bug #7832.
XCreateFontSet / XListFonts are core X11 font requests, not Xft - reassigning to
the right place so people see it.
Sorry about the phenomenal bug spam, guys. Adding xorg-team@ to the QA contact so bugs don't get lost in future.
I think this is the same issue I've been investigating. I have a small app that might help testing.
Some libXt apps (like xmessage and xcalc) take a lot of time to start if:
- you have many fonts
- you don't have some specific fonts (see below)
- you're using utf-8.
For example, consider the following program:
===
#include <assert.h>
#include <locale.h>
#include <stdio.h>
#include <X11/Xlib.h>
int main(int argc, char *argv[]) {
Display *d = XOpenDisplay(NULL);
assert(d);
char **missing_charset_list;
int missing_charset_count;
char *def_string;
XFontSet f;
int i;
if (argc != 2) {
fprintf(stderr, "PLEASE SPECIFY LOCALE\n");
return 1;
}
setlocale(LC_ALL, argv[1]);
f = XCreateFontSet(d, "-*-*-*-R-*-*-*-120-*-*-*-*,*", &missing_charset_list,
&missing_charset_count, &def_string);
printf("missing_carset_count: %d\n", missing_charset_count);
for (i = 0; i < missing_charset_count; i++) {
printf("%s\n", missing_charset_list[i]);
}
XSync(d, False);
return 0;
}
===
I start it with: ./cfs pt_BR.UTF-8
- if I have a lot of the "x11-font-*" packages installed
- but if I _don't_ have these fonts installed: x11-font-daewoo-misc, x11-font-isas-misc, x11-font-jis-misc, x11-font-wqy-bitmapfont,
Then this app will take like 7 seconds to start.
If I install daewoo-misc, isas-misc and jis-misc, the apps will start fast again...
This might not be the real fix for the algorithm slowness, but is a workaround =)
I'll keep investigating.
Created attachment 41576 [details]
log of the XCreateFontSet routine
with
- the code given in comment #7,
- libX11 1.4.0
- modules/om/generic/omGeneric.c with #define FONTDEBUG
- added a timer around the call to parse_omit_name() in parse_fontdata()
I found that most of the slowdown happens in:
This code seems to have been enhanced in the past ( ^deae12c ) but is still the main slow down for 90% of simple X apps.
With libX11 1.4.0, for the code given in comment #7, the results are :
- 250 msec: iso8859-1 (1 iteration)
- 3.5 sec : utf-8 (15 iterations + 2 iterations for NULL font_set->font_name)
And most of these 3 more seconds is spent for the NULL font names, more exactly in:
Each call to parse_omit_name() adds approximately 1.5 seconds
(see attachment above)
As a side note, I think this problem is distinct from bug #7832 which modifies the libXfont.
> I found that most of the slowdown happens in:
>
All commit f6af6dd2f76c12b56ec166bb771457b9f08fe246 does is to replace
the idom:
sprintf(r, "%s-%s", r, f[n]);
with:
strcat(r, "-");
strcat(r, f[n]);
(Note how r shows up as both the target and as a source for the
sprintf(3).)
If that slows down, then that suggests that there is something broken in
either your libc or the linkage.
Glibc’s C version of strcat(3) is simple and clean. The assembly
versions, however, might be too complex for a simple invocation like
the one in omGeneraic.c.
Perhaps the whole for loop could be improved?
(In reply to comment #10)
> > I found that most of the slowdown happens in:
>
> >
>
> All commit f6af6dd2f76c12b56ec166bb771457b9f08fe246 does is to replace
> the idom:
...
I'm sorry, the URL was misleading and the problem has nothing to do with this specific commit (I just wanted to point to a fixed line number)
As I attempted to show in the attached log, it happens that parse_omit_name() can takes 1.5 second before returning (called by parse_fontdata(), called by parse_fontname())
The loop l. 1165 of parse_fontname() may be rewritten (someone did in bug #7832) but the root is in parse_omit_name() which should either
- not be called innocently -especially if it is expected to return false-
- enhanced to spent less time
[ I still have to dig the insides of the slowness ]
I should also say that, obviously, removing KSC5601.1987-0 and GB2312.1980-0 from XLC_LOCALE skip them from the parse_fontname() loop and makes xcalc 4 times faster to launch.
Narrowed down :
The process so far is:
-*-*-*-R-*-*-*-120-*-*-*-* KSC5601.1987-0 : is not found
* KSC5601.1987-0 : is attempted which implies going through the part of parse_omit_name() intitled:
/* This may mot be needed anymore as XListFonts() takes care of this */
This part contains a loop calling get_font_name() for every possible wildcard prefix combinations:
*-*-GB2312.1980-0
*-*-*-GB2312.1980-0
...
*-*-*-*-*-*-*-*-*-*-*-*-*-GB2312.1980-0
And get_font_name() calls XListFonts() for each of them for a cost of 0.1 to 0.2 second for each.
The comment comes from c6349f43193b74a3c09945f3093a871b0157ba47 ("Merging XORG-CURRENT into trunk")
I didn't yet check but if I understand correctly:
XListFonts() already check every wildcard combination.
get_font_name() calls XListFonts().
get_font_name() is already called (twice) with the original font_data->name.
The 12 more times _seems_ useless.
Obvious patch, whose side effects are unknown, attached.
Created attachment 41765 [details] [review]
removes the 12 additionnal calls to get_font_name() in parse_omit_name()
Can you please send your patch to xorg-devel for review?
Hm, as I said in bug 2475 for me in ru_RU.UTF-8 this is not an issue anymore. But probably it's worth to check in other locales as well.
Ok, then closing. Thanks.
I'm still able to consistently reproduce the (huge) slowdown, with the test program from comment #7 and some X apps (like xcalc or xpdf).
Every (UTF-8) locale (generated beforehand) going through KSC5601.1987-0 and GB2312.1980-0 cases is affected.
I've not sent the patch in comment #13 to the mailing-list (see below about xpdf) but I hope there will be a consensus on reopening this bug (anyone reproducing)
# (be sure that the locale (eg: fr_FR.UTF-8) has been generated)
$ time ./cfs fr_FR.UTF-8
missing_charset_count: 2
KSC5601.1987-0
GB2312.1980-0
real 0m1.719s # AMD 4200+ !
user 0m0.007s
sys 0m0.004s
# patch from comment #13 applied
$ time LD_LIBRARY_PATH=patched-x11-git-sources/.libs ./cfs fr_FR.UTF-8
missing_charset_count: 0
real 0m0.009s
user 0m0.005s
sys 0m0.003s
I'm quite sure there *is* a bug waiting a fix.
comment #13 is not the the right one (it makes xpdf dying with a bunch of warnings) but I'm confident it's a pointer to the right direction anyway.
Ok, then I think #7832 should fix this.
*** This bug has been marked as a duplicate of bug 7832 ***
bug/show.html.tmpl processed
on Jan 16, 2017 at 14:57:16.
(provided by the Example extension). | https://bugs.freedesktop.org/show_bug.cgi?id=4939 | CC-MAIN-2017-04 | refinedweb | 1,522 | 67.55 |
Created on 2012-01-19 14:14 by scape, last changed 2012-01-19 16:33 by scape.
I believe I am having a similar issue to this:
I am in the middle of programming a quick script and now I cannot seem to get beyond this issue; as it is printing up the expiration times from the AD user listings (many of which print 1601 year) it finally fails after the same user account, I have compared accounts and the expiration is the same as other accounts in AD: which is set to (never)
any ideas of what's going on here and how I can bypass this error?
error report:
Traceback (most recent call last):
... line 14, in <module>
print user.name + ": " + str(user.accountExpires)
File "C:\Python27\lib\site-packages\active_directory.py", line 425, in __getattr__
self._delegate_map[name] = converter (attr)
File "C:\Python27\lib\site-packages\active_directory.py", line 335, in convert_to_datetime
return ad_time_to_datetime (item)
File "C:\Python27\lib\site-packages\active_directory.py", line 319, in ad_time_to_datetime
return BASE_TIME + delta
OverflowError: date value out of range
code:
import active_directory
from datetime import datetime,timedelta
##check AD for account expirations
users = active_directory.AD_object ("LDAP://ou=administration,dc=domain,dc=com")
for user in users.search (objectCategory='Person'):
dn = user.distinguishedName
dn = dn.encode("utf-8") #for the occasional apostrophe
if "Adjuncts" in str(dn):
print user.name + ": " + str(user.accountExpires)
print "done"
example output:
CN=John Hancock: 1601-01-01 00:00:00
CN=Jane Smith: 1601-01-01 00:00:00
...
I dug a little deeper using an error trap and found some of the problematic accounts in AD have their attribute set to a wildly long number and not 0 (as are others when 'never' is specified.) i'll dig further, it also does not seem to be an issue with python but more of an issue with the module I am using (active_directory) and its datetime handling (likely not fixed as was Python)
I don't think the issue is necessarily solved, but I'll close it anyways as I think I have atleast my solution now | http://bugs.python.org/issue13825 | crawl-003 | refinedweb | 353 | 52.9 |
April 9, 2020 Single Round Match 730 Editorials
IntervalIntersections
Used as: Division Two – Level One:
There are several cases to consider. We need to check if segments intersect or not.
- y1 < x2: the answer is x2 – x1.
- y2 < x1: the answer is x1 – y2.
- Otherwise, segments intersect and the answer is zero.
int ans = 0; if(y1<x2) return x2 - y1; if(y2<x1) return x1 - y2; return 0;
ExpectedMinimumPowerDiv2
Used as: Division Two – Level Two:
For each s, let’s count in how many ways s is the minimum element. We must choose s and also x – 1 elements greater than x. So we want to calculate
We can calculate the n choose r for each i. This leads to an O(n^2) solution. Note that n choose r never overflows from the 64-bit integer (e. g. long long in C++) when n, r are in the range [1, 50].Another solution is to calculate n choose r for all of the possible values in the range [1, 50] (preprocessing). Like the code below by cxhscst2:
const int M = 60; long long c[M][M]; double findExp(int n, int x) { memset(c, 0, sizeof c); // fill all of the array with 0 c[0][0] = 1; for(int i = 0; i <= 50; i++){ c[i][0]; for(int j = 1; j <= i; j++) c[i][j] = c[i - 1][j - 1] + c[i - 1][j]; } double ans = 0; for(int i = 1; i <= n - x + 1; i++){ int now = n - i; double ss = 1; for(int j = 1; j <= i; j++) ss = ss * 2; ans = ans + ss / (double) c[n][x] * c[now][x - 1]; } return ans; }
Another solution written in java:
public double findExp(int n, int x) { long total = 0; long p = 0; for (int min = 1; min <= n - x + 1; min++) { long sets = comb(n - min, x - 1); total += sets; long bit = (1L << min); p += bit * sets; } return p / (double) total; } private long comb(long n, long k) { if (k == 0) return 1L; return (n * comb(n - 1, k - 1)) / k; }
StonesOnATreeDiv2
Used as: Division Two – Level Three:
StonesOnATree
Used as: Division One – Level One:
The main goal of the game is to put a stone on the root. What is the last step before we can do it? Putting a stone on each of the children of the root. Because w[] is increasing, we will put a stone on each of the children one by one. i. e. we find a permutation of children, then we will manage to put a stone on each of them one by one.
dp[v] = The smallest W for which there is a way to put a stone on v such that during the game the total weight of nodes with stones never exceeds W. Note that we only consider subtree of v.
For example, consider the root has only two children: c, d. If we choose to put a stone on c then d, the answer is max(dp, w + dp[d]).
If we choose permutation p, then dp[0] = max(dp[p[0]], w[p[0]] + dp[p[1]], w[p[0]] + w[p[1]] + dp[p[2]], …).
We should find a permutation that leads to the minimum answer. Consider two children c, d. We put c before d in the permutation if and only if w + dp[d] < w[d] + dp.
So we sort the children with the comparison function above and calculate the dp.C++ code by Kriii:
int minStones(vector<int> p, vector<int> w) { int n = p.size() + 1; vector<vector<int> > g(n); for (int i = 1; i < n; i++) g[p[i - 1]].push_back(i); vector<int> a(n); for (int i = n - 1; i >= 0; i--) { vector<pair<int, int> > u; for (auto &x : g[i]) u.push_back({ w[x],a[x] }); sort(u.begin(), u.end(), [](const pair<int, int> &a, const pair<int, int> &b) { return max(a.second, a.first + b.second) < max(b.second,b.first+a.second); }); int r = 0, s = 0; for (auto &p : u) { r = max(r, s + p.second); s += p.first; } a[i] = max(r, s + w[i]); } return a[0]; }
Subgraphs
Used as: Division One – Level Two:
Here is the graph:
- There is no edge between vertices in the range [1, k].
- All of the vertices in the range [k+1, 2k] are pairwise connected.
- Vertex i (i <= k) is connected to k + 1, k + 2, … k + i.
Now to select a subgraph with x edges and k vertices, let p be the greatest integer such that p * (p – 1) / 2 <= x. We select the vertices in the ranges [2k – p + 1, 2k], [1, k – p – 1], and the vertex k – p + x – p * (p – 1) / 2.
vector<string> findGroups(int k) { int f[50][50] = { 0, }; vector<string> choose; choose.push_back("YN"); for (int j = 2; j <= k; j++) { vector<string> nchoose; for (auto &s : choose) nchoose.push_back(s + "NY"); for (int i = 0; i < 2 * j - 2; i++) f[i][2 * j - 2] = f[2 * j - 2][i] = 1; int u = j * (j - 1) / 2; for (int i = choose.size(); i <= u; i++) { nchoose.push_back(choose[i - (j - 1)] + "YN"); } choose = nchoose; } vector<string> ans; int n = 2 * k; for (int i = 0; i < n; i++) { string s; for (int j = 0; j < n; j++) { if (f[i][j]) s += '1'; else s += '0'; } ans.push_back(s); } ans.insert(ans.end(),choose.begin(), choose.end()); return ans; }
ExpectedMinimumPower
Used as: Division One – Level Three:
The problem is asking for
We calculate
instead and then double the answer.
Consider the following problem: “We have n people. Choose one of them as the leader, then choose x – 1 people with greater index as deputy and choose a subset (possibly empty) of people with less index (than the leader) as an employee. How many ways are there?
You can deduce that answer to this problem is
Let’s calculate the answer in another way. For each of the ways for the above problem, the last x – 1 chosen persons are deputy. The x-th one is the leader and others are employees.
So, for each subset of n people having at least x people, it is also an answer to the above problem. So,
typedef long long LL; #define MOD 1000000007 LL powmod(LL a, LL n){ if(n == 0) return 1; if(n % 2) return (a*powmod(a,n-1)) % MOD; LL c = powmod(a, n/2); return (c*c) % MOD; } LL inv(LL a){ return powmod(a, MOD-2); } // call init(); class ExpectedMinimumPower{ public: LL findExp(LL n, LL x){ LL ans = 0; LL cur = 1; for(LL a = 0; a < x; a++){ ans += cur; cur = (cur * (n - a)) % MOD; cur = (cur * inv(a + 1)) % MOD; ans %= MOD; } ans = powmod(2, n) - ans; ans %= MOD; ans *= 2; ans %= MOD; while(ans < 0) ans += MOD; return ans; } };
a.poorakhavan
Guest Blogger | https://www.topcoder.com/single-round-match-730-editorials/ | CC-MAIN-2020-34 | refinedweb | 1,164 | 77.37 |
Test.Hspec.Monadic
Contents
Description
There is a monadic and a non-monadic API. This is the documentation for the monadic API. The monadic API is suitable for most use cases, and it is more stable than the non-monadic API.
For documentation on the non-monadic API look at Test.Hspec.
Synopsis
- type Spec = SpecM ()
- class Example a
- data Pending
- describe :: String -> Spec -> Spec
- context :: String -> Spec -> Spec
- it :: Example v => String -> v -> Spec
- pending :: String -> Pending
- hspec :: Spec -> IO [EvaluatedSpec]
- hspecB :: Spec -> IO Bool
- hspecX :: Spec -> IO a
- hHspec :: Handle -> Spec -> IO [EvaluatedSpec]
- runSpecM :: Spec -> [Spec]
- fromSpecList :: [Spec] -> Spec
- descriptions :: [Spec] -> Spec
- type Specs = SpecM ()
Introduction
The three functions you'll use the most are
hspecX,
describe, and
it.
Here is an example of functions that format and unformat phone numbers and
the specs for them.
import Test.Hspec.Monadic import Test.Hspec.QuickCheck import Test.Hspec.HUnit () import Test.QuickCheck import Test.HUnit main = hspecX")
A type class for examples.
To use an HUnit
Test or an
Assertion as an example
you need to import Test.Hspec.HUnit.
To use a QuickCheck
Property as an example you need to
import Test.Hspec.QuickCheck.
Instances
Defining a spec
pending :: String -> PendingSource
A pending example.
If you want to report on a behavior but don [EvaluatedSpec]Source
Create a document of the given specs and write it to stdout.
hHspec :: Handle -> Spec -> IO [EvaluatedSpec]Source.
Deprecated types and functions
descriptions :: [Spec] -> SpecSource | http://hackage.haskell.org/package/hspec-1.1.3/docs/Test-Hspec-Monadic.html | CC-MAIN-2015-35 | refinedweb | 243 | 66.64 |
Yesterday I posted a Channel 9 interview
with Avner Aharoni, a Program Manager on the Visual Basic Team. In this interview Avner shows us how to enable XML IntelliSense in Visual Basic using the XML to Schema Wizard. He also shows the differences between how IntelliSense works with axis properties on XDocument and XElement objects and speaks to how the wizard can infer multiple schemas from multiple sources as well as the affect XML namespaces have on IntelliSense.
Get started with LINQ to XML in Visual Basic with these How-to Videos.
Enjoy!
Join the conversationAdd Comment
Hi Beth Massi, had a blast on the Geek Speak today. If you missed it, they will have it available on demand from their | https://blogs.msdn.microsoft.com/bethmassi/2008/01/18/channel-9-interview-xml-properties-and-enabling-intellisense/ | CC-MAIN-2017-09 | refinedweb | 121 | 59.64 |
today i finished the last exercise on functions, it was about writting a prog that takes 2 numbers, and gives u the power, u had to do this using recursion. after i finished it i went back to check the answer and tested the answer the book had, well i have to say that i was disappointed.
they only tested for 1 base case when in a prog like this u have to test for 2 correct?
they were only testing forthey were only testing forCode:{ if (power == 1) return n; { if (power ==0) return 1; else return (n * PowerFunc(n,power -1)); }
so would u say that their answer was incomplete?so would u say that their answer was incomplete?Code:if (power == 1) return n;
another question, recursion function do they always have 2 base cases? should i email them to correct it? eheh | http://cboard.cprogramming.com/cplusplus-programming/52129-recursion-question.html | CC-MAIN-2015-35 | refinedweb | 146 | 67.99 |
java 1.5 enums and MysqlBrian Oct 12, 2005 5:01 PM
Hi all,
I'm using jdk 1.5 persisted enums referenced in my ejb3 entity beans. I'm also using Mysql. They seem to be being persisted in the database as Blobs. Has anyone else used these and seen this?
thanks,
Brian
1. Re: java 1.5 enums and MysqlJonn Beames Oct 12, 2005 7:28 PM (in response to Brian)
I am using enums as field in my entities and am using MySQL 4.1 and I am not seeing my enums persisted as blobs.
Originally I created my table manually and created the columns that hold the enum values as varchars. An enum would get inserted into the table as its text value. Later, I let hbm2ddl create my tables and it created the enum columns as integers in which the enum gets persisted as its ordinal value.
In either case the persistance layer handles the enums appropriately and the app sees them as expected.
Sorry that I can't second your experience, but thought more info may be helpfull,
Jonn
2. Re: java 1.5 enums and MysqlBrian Oct 13, 2005 6:13 AM (in response to Brian)
Thanks Jonn,
I really appreciate it. I have a few questions for you if you don't mind.
1) I'm letting the database get created automatically on deployment of the ear. Is that what you mean by hbm2dll?
2) Can you tell me what version of jboss and of the ejb3 release you're using?
thanks so much again for the reply,
cheers,
Brian
3. Re: java 1.5 enums and MysqlJonn Beames Oct 13, 2005 1:24 PM (in response to Brian)
1) I'm letting the database get created automatically on deployment of the ear. Is that what you mean by hbm2dll?
Yes. I set the "hibernate.hbm2ddl.auto" property to "update" in persistance.xml, dropped my tables manually, deployed my ear and the tables were recreated with enum columns created as type INTEGER.
2) Can you tell me what version of jboss and of the ejb3 release you're using?
I started out using AS 4.0.3RC2 with the provided version of EJB3 (when I was using the manually created table). I switched to AS 4.0.3 plus EJB-3.0_RC3 a couple of days ago (this is the version I was using while doing auto table creation experiments).
My enums are really simple right now. Example:
public enum MpaRating { NAV, G, PG, PG13, R, NC17, NR; public String getDescription() { switch (this) { case G: return "G"; case PG: return "PG"; case PG13: return "PG-13"; case R: return "R"; case NC17: return "NC-17"; case NR: return "NR"; case NAV: default: return "--"; } } }And are used in enties like:
@Entity @Table(name = "MOVIES") public class Movie { private long id; private String title; ...other fields... private MpaRating mpaRating; @Id(generate = GeneratorType.AUTO) public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } ...other getters and setters... public MpaRating getMpaRating() { return mpaRating; } public void setMpaRating(MpaRating mpaRating) { this.mpaRating = mpaRating; } }
I hope this helps,
Jonn
4. Re: java 1.5 enums and MysqlBrian Oct 14, 2005 4:49 AM (in response to Brian)
This really helps Jonn, thanks so much. I'm sure I'll get it working now. | https://developer.jboss.org/thread/106370 | CC-MAIN-2018-39 | refinedweb | 571 | 67.76 |
14 May 2010 23:59 [Source: ICIS news]
LONDON (ICIS news)--European methyl ethyl ketone (MEK) prices have reached record highs this week due to tight supply, buyers and sellers confirmed on Friday.
“No one has material,” said a distributor.
Another distributor said: “A lot of end-users are looking desperately for material.”
MEK prices increased by €50-300/tonne ($63-375/tonne) this week, depending on market, to reach €1,350-1,800/tonne – their highest level since ICIS pricing records for MEK began on 17 November 1999.
All prices were settled on a free delivered (FD) northwest Europe (NWE) basis.
The previous record high was €1,600/tonne, reported from 22 October to 5 November 2004.
The majority of producers said that they were sold out of material for the rest of May.
Numbers at the top end of the range were representative of the distribution market, with producers reporting prices of €1,350-1,550/tonne and distributors’ prices starting at around the €1,500/tonne mark.
Some sources saw prices even higher, at up to €2,000/tonne, but this was not viewed as representative of the wider market.
Prices in the ?xml:namespace>
The wide range of prices reflected the supply shortages, with trading volumes erratic, sources said.
Tight supply was reportedly the result of unconfirmed production issues at several European plants.
The low availability was also attributed to lower production stockpiles as a result of stronger-than-expected demand in March and April, as well as a lack of imports.
“The shortages are due to production problems. I don’t know when they’ll be resolved,” said a third distributor.
The lack of imports was due to tight supply in overseas regions and the strong US dollar against the euro, which made material from other regions unattractive to European buyers, sources said.
Demand was strong, players reported, as buyers attempted to secure supply.
However, sources added that it was difficult to assess underlying demand, as consumption was being fuelled by the low availability of material.
“It’s likely some people will substitute. Customers say they may have to if they can’t get hold of product,” said a major producer.
Some sources in the MEK market said applications that could switch to ethyl acetate (etac), such as printing and automotive, would move away from MEK in order to ensure supply.
Etac was currently trading at €850-880/tonne, up to €950/tonne below MEK prices. Buyers were yet to confirm the substitution of material.
($1 = €0.80)
For more on ME | http://www.icis.com/Articles/2010/05/14/9359832/europe-mek-prices-hit-record-high-on-tight-supply.html | CC-MAIN-2014-35 | refinedweb | 427 | 63.19 |
Jupyter™ Notebooks is one of the most popular IDE of choice among Python users. Traditionally, Jupyter users work with small or sampled datasets that do not require distributed computing. However, as data volumes grow and enterprises move toward a unified data lake, powering business analytics through parallel computing frameworks such as Spark, Hive and Presto becomes essential.
We covered connecting Jupyter with Qubole Spark cluster in the previous article. In this post, we will show how Jupyter users can leverage PyHive to run queries from Jupyter Notebooks against Qubole Hive and Presto clusters in a secure way.
The following diagram depicts a high level architectural view of the solution.
A Jupyter Notebook that is running on your local computer will utilize Qubole API to connect to a Qubole Spark Cluster. This will allow the notebook to execute SQL code on Presto or Hive Cluster using pyhive. Please follow the Step-by-Step Guide bellow to enable this solution.
Step-by-Step Guide
Step 1. Follow steps in this article to connect Jupyter with Qubole Spark Cluster.
Step 2. Navigate to Clusters page in Qubole & click the ellipsis on the same Spark cluster you used on the previous step. Click “Edit Node Bootstrap”.
Step 3. Add the following command to the Node Bootstrap outside of any conditional code to make sure that this command runs for both, master and slave nodes.
pip install pyhive
Step 4. Start or Restart the Spark cluster to activate pyhive.
Step 5. Set Elastic IP for Master Node in the cluster configuration for both Hive and Presto clusters. This step is optional. However, it will help reconnecting to Hive and Presto clusters after their restart.
Step 6. On Hive cluster, enable Hive Server 2
Step 7. Make sure that port 10003 on the master node of Hive cluster and port 8081 on the Presto cluster are open for access from Spark cluster. You may need to create security groups and apply them as Persistent Security Groups on the cluster configuration.
Step 8. Start or restart Hive and Presto clusters and take a note of the Master DNS on the Clusters page. If you configured Elastic IPs on Step 5 use them instead. Here is an example of how the Master DNS may look.
Step 9. Start Jupyter Notebook and open an existing or create a new PySpark notebook. Please refer to this article on details of starting Jupyter Notebook.
Step 10. To connect to Hive, use this sample code below. Replace <Master-Node-DNS> with the values from Step 8.
from pyhive import hive hive_conn = hive.Connection(host="<Master-Node-DNS>", port=10003) hive_cursor=hive_conn.cursor() hive_cursor.execute('SELECT * FROM your_table LIMIT 10') print hive_cursor.fetchone()
Step 11. To connect to Presto, use this sample code below. Replace <Master-Node-DNS> with the values from Step 8.
from pyhive import presto presto_conn = presto.Connection(host="<Matser-Node-DNS>", port=8081) presto_cursor=presto_conn.cursor() presto_cursor.execute('SELECT * FROM your_table LIMIT 10') print presto_cursor.fetchone()
References:
- Connecting Jupyter to Qubole Spark:
- PyHive: | https://www.qubole.com/blog/hive-presto-clusters-jupyter-aws-azure-oracle/ | CC-MAIN-2021-04 | refinedweb | 504 | 67.55 |
?
Basje Wrote:Well, I am not going to change it in the script because on Linux/Windows the high bitrates is much nicer and on Xbox you can use the contextmenu to select the lowbitrate stream. But it's very easy change yourself:
Just open the chn_svt.py and go to line number 277. That line reads:
Code:
def PlayVideoItem(self, item, lowBitrate=False, player="defaultplayer"):
change it to
Code:
def PlayVideoItem(self, item, lowBitrate=True, player="defaultplayer"):
(just replace the False with True)
Then it will play the low bitrate stream by default.
def PlayVideoItem(self, item, lowBitrate=False, player="defaultplayer"):
def PlayVideoItem(self, item, lowBitrate=True, player="defaultplayer"):
deeed Wrote:Hello, I can't get this to work.
Running XOT 3.2.3 as a script in XBMC on XBox.
I have replaced "False" with "True" in line 276 in the chn_svt.py script, so it now reads:
def PlayVideoItem(self, item, lowBitrate=True, player="defaultplayer"):
But the script still fetches the 1280x720 resolution video.
Also when selecting a video and going into context menu (i assume it's the white button), I don't have the option to play lowBitrate. Only options are: Add-on settings, DownloadItem, Play using MPlayer and Play using DVDPlayer.
Any idea what might be causing this?
Basje Wrote:Well, it does not work anymore in version 3.2.3! Read the readme.txt or the changelog because I improved it (due to popular demand)!
You can now specify the bitrate using the Add-On Settings of XOT-Uzg.v3. Just go into the context menu (in the script itself or while selecting it from the list of scripts in XBMC) and select Add-On settings. You get a bunch of settings and you can set the playback quality to Low or Medium there. XOT will then select that quality for playback (that is why the menu options playback low and high were removed).
Keep in mind that not all channels support this feature yet, but SVT does.
PS: undo your changes to the .py file, because it might break other stuff.
Basje Wrote:It has to do with the character encodings. It will be fixed in the next version of XOT.
Keep in mind that ATV2 support is very beta at this moment. So more features will not work (rtmp playback).
Zsurfer Wrote:I'm having similar problems running on OpenELEC. My log file shows error messages about non-ASCII characters. So far I've managed to get it to work by simply removing the swedish characters from the comments lines in the python code, but of course it breaks every time it updates.
It works fine on XBMC on Ubuntu on another partition on the same machine, so it seems to be related to OpenELEC. One difference that I recently learned about is that OpenELEC is using python 2.6 instead of 2.4.
Do you think this issue will be solved by the next version, or am I experiencing a completely different problem?
Cyzor Wrote:First off, great work on this add-on!
XBMC now runs on the Apple TV 2 thanks to the awesome work of the XBMC devs. one of the few things the ATV2 implementation is lacking is the support for MMS streams so the XOT-UZG add-on doesn't work at all on the ATV2.
The beta site of Uitzending Gemist offers HTML5 support for the iPad which means that there are "Apple compatible" h.264 m4v files on the UG servers. When I change the user agent of my browser to that of an iPad I can download the m4v files which play without conversion on the Apple TV.
Do you think it is in any way possible to also include the h.264 m4v option when you choose the bitrate?
Basje Wrote:Could you let me know the useragent string that you are using?
Mozilla/5.0 (iPad; U; CPU OS 3_2_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B500 Safari/531.21.10
>
Cyzor Wrote:I just did some more digging and you don't need to change the user agent at all to get to the HTML5 video URL. Sticking with the "Wie is de Mol?" example. Looking at the source of the episode page, near the botton is this code:
Code:
>
The bold text is the "episode specific" part. Paste that code in the base url and you get: beta.uitzendinggemist.nl/video_streams/AVRO_1409266?quality=std
Another example, this is the code from the Wikileaks episode of Tegenlicht: VPWON_1151208 which makes this URL: beta.uitzendinggemist.nl/video_streams/VPWON_1151208?quality=std
It looks like all the video's are 1Mbit H.264 files of good quality. I can even paste these URLs into the AirFlick application and the video starts playing on my Apple TV through AirVideo. It would be great however if this would be a selection in the XOT-UZG add-on so I don't need my Mac to get the URL and stream the video but to be able to just select it from within XBMC. | http://forum.kodi.tv/showthread.php?tid=25522&page=60 | CC-MAIN-2016-07 | refinedweb | 860 | 73.78 |
Upload image
Upload image Hai i beginner of Java ME i want code to capture QR Code image and send to the server and display value in Mobile Screen i want code in Java ME .java extension..
Regards
senthil
To capture an image... to database
The given code allow the user to browse and upload selected file... be upload in the server and their path should be stored in database either
Upload image
Upload image Hai team,
I beginner of Java me now i crated code for to capture image and upload to server.
Here i taken a snap but when am going... help me. Jsp Upload Image
1)page.jsp:
<%@ page language="java a image
upload a image sir,how can i upload a image into a specified folder using jsp Hi Friend,Try the following code:1)page.jsp:<p>&...;<HEAD><TITLE>Display file upload form to the user<
To scan a image and upload to server
To scan a image and upload to server I am beginner of JavaME I want a code to scan a image and upload to server
scan a image and upload to server
scan a image and upload to server Hai i am beginner of Java ME..I want the code To scan a image and upload to server
scan a image and upload to server
scan a image and upload to server I have code for capture image and upload to server..after capture that image decoded it going to be convert digit... refer me,to send a code for to scan a image and upload to server in j2me
Thanks
Image upload file - JSP-Servlet
Image upload file I want a code for image upload jsp or servlet. Hi friend,
For image upload jsp or servlet visit to :
http
How display a Image on servlet from file upload - JSP-Servlet
; Hi friend,
I am sending running code.
Image upload page... ask a question that How display the Image on servlet through file upload.
Today I get your answer.
But Sir,
It code not display the image on servlet
upload an image
upload an image Hello, i would like to upload an image to the database. how can i do it? what field type should i set in the database? thanx
UPLOAD
UPLOAD how to upload image using html
image upload How to access image file from database using jsp?
... rs=st.executeQuery("SELECT images FROM image WHERE id = 1");
if(rs.next...("image/jpeg");
while((size=sImage.read(bytearray))!= -1
upload image data
upload image data Hii
Upload image dat in csv
Imge upload
Imge upload how to upload image in jsp.I am using Glassfish server..
Here is a code that upload an image on tomcat server and save...;HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>
image upload - Struts
image upload Can any one help me how to upload an image using struts
Text Editor Image upload
Text Editor Image upload how to browse an image from text editor instead of giving url of particular image using javascript
Jsp Upload
an error when Uploading to an database Mysql
the code is given below</p>...-data") >= 0)) {
File image=new File(contentType... into gallery values(?)");
fis=new FileInputStream(image, here is my code which gives me an error..
Addfile.jsp
<%@ page import
Servlets
Servlets What is the filter code to authenticate the user
upload image to database
upload image to database i am try to upload image to MySql database using netbeans.
when jsp execute it return no error. but also data does inserted in database. i am using blob datatype and preopared statement Upload Error
Image Upload Error hi,
I created one education website in jsp....in my registration page image uploading option also i attached in real path...it's working well in local file....when i upload file in live Using FT
upload images - JSP-Servlet
upload images How to write the jsp code to upload images... to upload any file therefor it can also upload an image and can insert...://
Thanks
upload image in php
upload image in php after select image,how to save it in a folder...;
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
2
Upload Image and save in database using jsp-servlet mvc
Upload Image and save in database using jsp-servlet mvc Here is my code..
In jsp ...
<form name=frm
<table>
<tr><TD ><B>Upload Image</B><
Upload Image and save in database using jsp-servlet mvc
Upload Image and save in database using jsp-servlet mvc Here is my code..
In jsp ...
<form name=frm
<table>
<tr><TD ><B>Upload Image</B><
Having problem with image upload....
Having problem with image upload.... I am uploading profile pictures... that the image is getting uploaded.I also right clicked on the home page... of the image absolutely correct.But when I click on the url it is saying requested... in multi part form data.
3.As write code to upload text and image.As it is working
Upload and Download multiple files
Upload and Download multiple files Hello Sir/Madam,
I need a simple code for upload and download multiple files(it may be image,doc... link:
struts2 upload image public_html
struts2 upload image public_html How to upload images in public_html file in Struts 2 application.
Thanks in advance
How to upload and save a file in a folder - Java Beginners
; Hi Friends,
I need that code using servlets and jsp.....
Please let me... in solving the problem :
Image Upload...How to upload and save a file in a folder Hi
How to upload
Multiple file upload - Struts
Multiple file upload HI all,
I m trying to upload multiple files... need to upload is dynamically generated.
I have tried using formfile. and also array of formfile.
Can anyone suggest me or send me some sample code to resolve
How display a image on servlet from file upload - JSP-Servlet
is: How display a image on servlet from file upload
I receive your answer today.
That is:
Answers Hi friend,
I am sending running code.
Image upload page
Employee Image JSP Hibernate
upload image using JSP Hibernate sir,
I want to take image from user and save to database(MYSQL) using Hibernate and JSP
Thanks in advance
image upload and stored in database - JSP-Servlet
image upload and stored in database How can i upload a image and store that image in a database
servlets - Servlet Interview Questions
page "mypage.jsp":
The following code is from the "myservlet" class...,HttpServletResponse response)throws servletException {
//incomplete
}
(a)How can... or pseudo code. Hi
registration form in jsp
Upload Image using Servlet
Upload Image using Servlet
This application illustrates how to upload an image using servlet... the
uploaded data and saves the image on the server.
Following programming code
Photo upload, Download
Photo upload, Download Hi
I am using NetBeans IDE for developing... am loading photo.
BufferedImage image=null;
JFileChooser chooser = new...) {
File myFile = chooser.getSelectedFile();
try {
image
image
image how to add the image in servlet code
give the code for servlets session
give the code for servlets session k give the code of total sample examples of servlet session
Photo Upload - JSP-Servlet
Photo Upload Dear Sir,
I want some help you i.e code for image upload and download using Servle/jsp.
Thanks&Regards,
VijayaBabu.M ... = 0;
//this loop converting the uploaded file into byte code photo - Java Beginners
Upload photo Morning,
Can you tell me coding how to upload photo...,
Hendra
Hi Friend,
Try the following code:
import java.io....);
Action uploadAction = new UploadAction("Upload");
Action browseAction = new
Upload Code error on deploying
Upload Code error on deploying on deploying the above code as it is said it is giving error that " No getter method for property thefile of bean org.apache.struts.taglib.html.BEAN
"
Error 500--Internal Server Error
how to upload photo - Java Beginners
{
public static void main(String[] args){
JFrame frame = new JFrame("Upload Image...());
}
}
});
JButton button = new JButton("Upload Image...how to upload photo dear sir,
I has a case like that, first i
upload image and fields.....fields is id name.....
upload image and fields.....fields is id name..... Hi this is sreenu
my problam is capcharing data to the servler
thi is my frame
Id:
Name:
browse:Image are file
upload image and fields.....fields is id name.....
upload image and fields.....fields is id name..... Get Data using Java Servlet
The frame takes following input..
Id:
Name:
browse:Image are file
File Upload
File Upload when i execute the image upload to mysql database it shows an exception that file path cannot be found
java code - Servlet Interview Questions
java code i write program to upload image into perticular folder.but i want to store that path into database but not image and display that image in webpage from the db.pls any one send me code for that in servlets asap.pls
File Upload Tutorial With Examples In JSP
with image
This
tutorial will help you to understand how you can upload...
File Upload Tutorial With Examples In JSP
... in the developing the
project in which you have to upload any type of files
upload video
upload video hi sir i want to code of upload and download video in mysql database using jsp...
and plz give advice which data type is used to store video in table
how to upload and download images in java?
how to upload and download images in java? what is the code....
Upload and Download images:
1)page.jsp:
<%@ page language="java" %>
<HTML>
<HEAD><TITLE>Display file upload form
insert name city and upload image in database using mysql and jsp
insert name city and upload image in database using mysql and jsp insert name city and upload image in database using mysql and jsp
Crop Image Code in Applet
Crop Image Code in Applet Sir,
Can somebody please provide me with code to crop and save an image in applet
HTML Upload
HTML Upload Hi,
I want to upload a word / excel document using the html code (web interface)need to get displayed on another webpage. Please let me the coding to display on another webpage using
image effects - Java Beginners
java.awt.image.FilteredImageSource;
public class Upload extends JPanel {
BufferedImage image;
Image img...image effects hey can u help me in loadin an image file... with comments whereever possible Hi Friend,
We are providing you a code
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://www.roseindia.net/tutorialhelp/comment/96863 | CC-MAIN-2015-22 | refinedweb | 1,776 | 63.09 |
2006
Filter by Day:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Convert string into Actionscript Code
Posted by saavedrajj at 3/31/2006 11:10:03 PM
I need one function that converts string into actionscript code, i've been searching but I don't find anything. I'm using Flash 8. Example: myString = "Number(var1.txt) * Number(var2.txt) + 1000"; result.text = desiredFunction(myString); // is equal > result.text = Number(var1.txt) ...
more >>
Conflicting loadMovie files
Posted by beevyarr at 3/31/2006 9:59:11 PM
Working in Flash MX 2004, I have a page w/ which I have loaded 3 movies into different emptyMovieClips. One movie is a scrolling navigation whose buttons load a product ID variable. This variable affects which frame labels of the other two movies get played. My problem is that one of ...
more >>
WHO TO: detect which button is pressed down
Posted by MnemonicFish at 3/31/2006 9:29:01 PM
Thanks fot taking the time to helpout. Okay I have 5 nav buttons, which have the following functions, rollover, rollout, press and release (please see code attached) Once a button is released it calls function getUrl and its state stays down, I want it to stay down untill the user hits a...
more >>
accessing var defined in function
Posted by abeall at 3/31/2006 8:54:43 PM
In this case...: function myFunc(){ var myVar; myOtherFunc(); } function myOtherFunc(){ //access to myVar? } ...is it possible to edit myVar from myOtherFunc? If I had built myself the 3k lines of code I'm dealing with I would have avoided this in the first place(myVar being ha...
more >>
referencing a variable throughout different timelines
Posted by (_seb_) at 3/31/2006 8:29:38 PM
I have the following code, which resides, in the timeline, at: _root.myLoader.theLoader.control: var loadImages:LoadVars = new LoadVars(); loadImages.onLoad = function() { if (this.totalImages != undefined) { imagesToLoad = new Array(); for (var i = 0; i < this.totalImages; i++) { ...
more >>
action script to turn on or off the layer (div)?
Posted by micheal_newby at 3/31/2006 8:21:18 PM
Hello, Is there anyone who had discovered how to turn off or on a layer <DIV> with actionscript? For example i have created a layer that goes over the flash animation. But i want to use a button in flash that hides this layer. Is this possible and does any one have the actionscript code...
more >>
file upload w/ php - can't set session vars on the Mac
Posted by ShazamFu at 3/31/2006 8:12:01 PM
Hi, I've got a file upload module that works great on the PC. It allows the user to upload .jpgs. It calls a PHP script to do the actual uploading. After the uploading is complete, the user is redirected to a page where thumbnails are displayed of the images that they just uploaded. L...
more >>
Need Help - Navigating with a mouse click
Posted by WolfmanVancouver at 3/31/2006 6:52:12 PM
Hi if anyone could offer any help that would be greatly appreciated. I have a product demo that I am currently working on. The demo is currently controlled by either hitting the space bar or enter key to advance the animation. I would also like to have the file advance by using a single or ...
more >>
Don't see what you're looking for? Search DevelopmentNow.com.
Generating Buttons with Actionscript
Posted by Dieter Kahl at 3/31/2006 6:41:00 PM
Hi, is it possible to generate buttons with actionscript? And what is the code or where can I get more information? Thanks Dieter...
more >>
actionscript and variables
Posted by Armo_Director_user at 3/31/2006 6:29:29 PM
I have a flash movie with actionscript that runs in frame one. I have nested movies (animated buttons) with actionscript in their frames as well. What I need to do is have the button set a variable to a "previous" when clicked on, send a call to a function in the actionscript of the movie th...
more >>
CGI Http_Host Variable
Posted by patb96 at 3/31/2006 5:08:11 PM
Just wondering if I can tell the what the HTTP_HOST variable is of an swf file. If i cannot... is there a way to call a webservice using a relative path. The URL of the webservice resides in the same folder as the SWF. I have a testing and production server and wanna dynamically generate ...
more >>
Array's disapearing from attachMovie movieClips
Posted by MCR at 3/31/2006 5:06:47 PM
I am readin in a XML file containg a personal chart structure in the form of a Spider Chart. So I read through the XML structure and dynamically attach MC's with attachMovie and then use recursive function calls to produce all the children of each node of the spider diagram. Each MC that has c...
more >>
Flash6 to Flash8 problem
Posted by Rallim at 3/31/2006 5:06:40 PM
:disgust; I know there are tons of post about this and I tried to solve my problem by reading them but I'm missing something. I need a fresh pair of eye to look at this code to see how to make it work in Flash 8 I'm stumpped!!!! HELP ANYONE!!!!!! here is a link to the FLA www3.sympa...
more >>
Show/Hide layer with button
Posted by gv0523 at 3/31/2006 3:58:07 >>
Curved text
Posted by gigisfarleaza at 3/31/2006 3:21:43 PM
Can someone tell me hai can i curve text in Flash ? withouth breaking him apart an arange every leter by hand.......
more >>
load movie flicker on load
Posted by guido626 at 3/31/2006 3:11:39 PM
Below is the standard behavior script that flash has made for me while loading an external swf. I'm using several of these statements loading 6 swf's on my page. Problem is, they seem to flicker/reload while each of them load. They stop when all 6 of them are loaded. Can anyone tell me if t...
more >>
Does screenweaver stop fscommands?
Posted by RobGT at 3/31/2006 2:50:18 PM
Subject says it all really. I'm wondering if my exe file (flash movie compiled using screenweaver) is not successfully using fscommand because of screenweaver somehow? If someone knows - please advise. Cheers, Rob ...
more >>
Is this possible to do?
Posted by Hermet at 3/31/2006 2:46:31 PM
I have a flash application. It has a dynamic text field. When I run the application an swf movie loads into flash. The swf movie has a button on it. Is it possible to make the button (on release) load some text into the dynamic text field? what do I write inside the button's AS window? ...
more >>
Returns on dynamica texts.
Posted by JimmySlam at 3/31/2006 2:02:48 PM
I have a text and I want to add a ENTER (RETURN to the next line) I really dont want to add a enter on the XML because i will look messy when I check the XML. is it any way to add a enter like on C is "\r". or on VB is &vbrtrn (or something like that). Anyone knows that is the code for a ...
more >>
Chained List
Posted by delatroy at 3/31/2006 12:42:06 PM
Im looking to build a multi-user game in flash. Does action-script support a chained-list? I need some kind of way to manage six users in one animation. Refer to this URL to get a detailed example of a chained-list in C. >...
more >>
load from external txt file
Posted by Denesh Kumar at 3/31/2006 5:08:15 AM
Hi, How want to load text from text file into dynamic text box of a movie ??? reply me ...
more >>
How do you expire a SWF?
Posted by SunSeekerNC at 3/31/2006 5:00:40 AM
Hi: I want to be able to: (1) expire a swf within a certain number of days after it is first run. I know I can use getDate() to determine the current date. However, how to I have the swf (1) determine the current date (2) save this info somewhere and (3) have the swf expire (say 60 ...
more >>
XMLSocket vs. the Enter key
Posted by blemmo at 3/31/2006 4:04:06 AM
Hi forum, I came across a strange problem with a function that makes use of a XMLSocket. The function just connects the socket; after that the socket's events should handle the connection. Now I have a textfield for user input (just a name), and a "connect" button. The 'connect' function i...
more >>
Giving actions to dynamic text link ?
Posted by billy nugz at 3/31/2006 3:44:35 AM
I have a scrolling dynamic text feild with a few hyper links in it. Instead of just having a hyper link can I give certain protions of that text actions like normal buttons? If NO Is there a way to scroll movie clips using the scrollbar component ? (scrollbar component from flash excha...
more >>
goto and play issue
Posted by Jimmathy at 3/31/2006 3:04:39 AM
I want to make it so that when the right arrow key is pressed that a movie clip goes to and plays at a frame labeled "rhit". But here's the problem, I also wan't it so that if another movie clip called "head" is at the _y location of 125 then it also goes to and plays at a frame labelled "smac...
more >>
Resizing loaded Flashpaper - I give up!!
Posted by rodolfo1216 at 3/31/2006 2:25:50 AM
I can't believe it, I just can't believe it. This is hard. All I want to do is load an swf file I made with Flashpaper into a movie I'm making. It loads in okay using loadMovie, but I can't figure out how to resize it. Can anyone tell me how to resize a flashpaper swf? why is this so hard...
more >>
pass variables to Flash
Posted by turlon at 3/31/2006 12:00:00 AM
I am attempting to pass a variable to a flash movie on each page of an e-learning course, the pages of which are generated by a tool called Lectora. (It produces html and js pages that are SCORM compliant - handy seeing as I dont know how to go about this using just flash) Each page contains a...
more >>
How can I know the size (Y) of a dynamic text?
Posted by JimmySlam at 3/31/2006 12:00:00 AM
Im triying to find out on the fly the size of several textboxs that are dynamic... Can I do it? ...
more >>
unique URL
Posted by jonnybennett at 3/31/2006 12:00:00 AM
Okay this isn't strictly a flash question, but it is for a flash site I am working on, so needs to be maniplted for flash. I have seen many sites that offer their users a unique url... eg... This will then load a page but with their personal settings, howev...
more >>
Strange keyPress problem
Posted by OniLink at 3/31/2006 12:00:00 AM
First of all, I'm using Flash 8, but I'm exporting to Flash Player 6. I have this code on a movieclip: on (keyPress "<Up>") { trace("UP!"); var focus:String = Selection.getFocus(); if (focus.indexOf("input") != -1) { _root.searchItems(); } } The trace never returns! I c...
more >>
Two different frame rates in one movie
Posted by tegan719 at 3/31/2006 12:00:00 AM
Hello, I have a movie clip of a 3d logo in my main time line that I would like to run at a slower frame rate than the main movie. What's the actionscript for this? Or do i need to load it as a seperate swf? Thanks Tegan ...
more >>
Run one exe file from another
Posted by RobGT at 3/31/2006 12:00:00 AM
Hi, I need to add some code to a button in a flash movie (an EXE - not a movie running in a browser window) that will launch a second flash based exe. No browsers involved. I have tried using an FS Command, but all that does is throw an error saying "unknown command"!!! Please help. Chee...
more >>
getPixel32 bug or something?
Posted by katopz NO[at]SPAM sleepydesign.com at 3/31/2006 12:00:00 AM
import flash.display.BitmapData; var out_bmp:BitmapData = new BitmapData(10,10,true,0x33FF3300); trace("get : 0x"+out_bmp.getPixel(0, 0).toString(16)+" ("+out_bmp.getPixel(0, 0)+")"); trace("get32 : 0x"+out_bmp.getPixel32(0, 0).toString(16)+" ("+out_bmp.getPixel32(0, 0)+")"); result is...
more >>
fading in/out external movie clips
Posted by blueprnt at 3/31/2006 12:00:00 AM
Hi, What I am trying to do is load a external swf into a movie clip (blank_mc) on my main time line. So something like this this.menu1_mc.onPress = function() fade out movie loaded into blank_mc unloadMovie("_root.blanc_mc"); fad...
more >>
Data in Objects
Posted by doug777 at 3/31/2006 12:00:00 AM
Is it permissible to have data that needs to be resolved in objects? E.g. is this allowed? var var1:String = "Hello"; var str2:String = "World"; var myObject:Object = {var1:1+1, var2:str1 + " " + str2}; A trace would return 2 Hello World or would there be an error? Doug...
more >>
Embedded Video Object Sound Control
Posted by ropeGun at 3/31/2006 12:00:00 AM
Hello Flash AS Gurus, I am streaming in FLV's (eventually with sound) into an Embedded Video Object instance on my stage. I am using NetConnections and NetStreams to load in the FLV's into the instance. I would like to make a "mute" button where the user can click and mute the FLV's sound ...
more >>
Posted by n-Qube at 3/31/2006 12:00:00 AM
Does any one have an ideas how this site was createdhttp,://? is it possible to achieve that using tween classes... >>
What is UP with this removeItem At command?
Posted by conquerors04 at 3/30/2006 11:51:09 PM
OK, I'm trying to use that removeItemAt() command to remove an Item out of the 0 selectedIndex space but it won't delete it. It works for the others. The documentation says it won't work for the "0" space (says the number has to be greater than 0? Why?) but how do you remove an Item with th...
more >>
Interactive photo slideshow
Posted by Armo_Director_user at 3/30/2006 10:00:17 PM
I have atached actionscript code and xml file code as references. I found these files available for download from someone's site (he distributed for free, what a great guy!!) Well, I am a flash newbie, and what may seem real simple to others, has now given me a splitting headache. This code cr...
more >>
Scrolling Background
Posted by Ginger85 at 3/30/2006 9:38:36 PM
Hello.. I am building a website and I would like the background to scroll along when the mouse cursor touches the edges of the screen. Basically like this: Any suggestions would be more than welcome! Thanks, Ginger ...
more >>
Textfields and strings
Posted by jollyguy998 at 3/30/2006 9:30:15 PM
Probably a simple answer but... When i try to add text to my sting and show it in my textbox like mess.htmlText = newtext + '<br>' + mess.htmlText; so that the newly added text is at the top of my screen the old text loses its spacing and line breaks from before.. i.e. what i want ...
more >>
Replace Colors in a movie clip
Posted by rogz at 3/30/2006 9:04:57 PM
Is it possible to replace colors in a movieclip through actionscript. I have a movie clip that contains some blue and white and i want to swap the blue with red...can i do this or do i need to go the route of reloading the movie clip with images? ...
more >>
Stupid problem w/Javascript
Posted by Nickels55 at 3/30/2006 8:00:41 PM
I have a button in flash that I want to call a javascript function when pressed. For some reason the code is no longer working. I searched for the answer here but nothing really helped. I don't care if the method is an action like: button1.onRelease.getURL("javascript:myfunct()",_self"); ...
more >>
Re: error -handling
Posted by LuigiL at 3/30/2006 7:59:09 PM
Stubbern... Try this: Put an instance of the loader on the stage and give it an instance name 'loader'. Code on frame 1 (seperate layer): try { if(this.loader.contentPath="images/02.jpg"){ throw new Error("Image path incorrect"); } } catch (e:Error) { trace("Error: "+e.messa...
more >>
ComboBox (List goes from bottom to Top)
Posted by babo_ya at 3/30/2006 7:39:33 PM
Not sure why, but, my UI ComboBox List shows up in a wrong direction. When I click the comboBox, the list goes where the comboBox is and to UP Why? and how do I fix this? cmbOrder = container_mc.createClassObject(ComboBox, "cmbOrder", container_mc.getNextHighestDepth()); cmbOrder.set...
more >>
need help with my class
Posted by SimonDoer87 at 3/30/2006 7:19:07 PM
Hey, I need some help here. I've got a flash movie that creates an empty movie clip and then loads an swf into that movie clip. I have an external class and I want to have the movieClip inherit from the class. I can't figure out how to do it without setting the linkage in the library. Any ...
more >>
Recommendation needed...
Posted by Sai_Zelion at 3/30/2006 7:05:47 PM
I'm creating an email form for my flash site, I want to use PHP since it seems so simple to set up. My current Web Hosting Provider requires me to download a PHP script for email. I visited hotscripts.com and was overwhelmed by the choices. Does anyone have any recommendations? Thanks ...
more >>
XMLSocket server security
Posted by JesperBisgaard at 3/30/2006 6:41:34 PM
Hi, I have build a XML socket server on one site and i have a few swf files running on another site but i have a problem getting the files to connect to my server. I have placed a crossdomain file with *.myswfdomain at the root of the server containing the XML socket server but it dosent s...
more >>
LocalConnection
Posted by JuxtaposeTurtle at 3/30/2006 6:09:00 PM
:confused; I am trying to get two separate Flash movies to communicate. I finally got them to talk to one another, but I am finding that the effect only works for one and a half loops. What I am trying to accomplish is to have a top banner transition between photos and then have a side bar...
more >>
·
·
groups
Questions? Comments? Contact the
d
n | http://www.developmentnow.com/g/69_2006_3_0_0_0/macromedia-flash-actionscript.htm | crawl-001 | refinedweb | 3,233 | 72.56 |
If you add "runat="server" to most normal html controls, you can reference
them in code-behind.
These are in the System.Web.UI.HtmlControls library.
Example: an HtmlAnchor for the <a> tag can be found in MSDN here
with a code sample at the end.
I think maybe a tag wasn't closed. But this is what I added:
#footer{
width: 860px;
margin: 0 auto;
}
And it seems to be working. Fiddle
While this is a bug, you could use this work around:
<div class="nojs"><noscript>This website requires JavaScript to
run. Please </noscript><a href="activatejs.php"class="link"
target="_blank"><noscript>enable
it</noscript></a><noscript> or use a web browser that
supports JavaScript.</noscript></div>
All controls must be rebuilt in Page_Load so that event handlers and value
binding can occur. So, if you create the controls initially in an event
handler then you need to cache enough data in Session, or ViewState, so
that you can rebuild those controls on Page_Load.
A lot of times a basic Tuple will work to provide enough information for
those controls to be recreated. A little note though. You're going to need
to ensure you set the ID property the first time they are built and when
they are rebuilt. That's how value binding occurs.
Frisco inherits lots of files from BP Default. Look in this file:
/members/single/profile.php
This function bp_get_options_nav(); returns that menu.
Why do you want to have exit in if condition ? You are any ways redirecting
so i guess that is not required
Also what if customer comes after one month why will you ask for email
again.
What if he clears his cookies? He will be prompted for the email again.
I would suggest you to store his email and check from database itself
instead of cookies, if the email exist and then redirect him accordingly.
Hope it helps you.
if you are trying to find control inside the master page you should
this.Master.FindControl("controlName").
Other case is with you are inside master page and want to find a control
inside a page so you should ContentPlaceHolder1.FindControl("controlName").
Please also check:
How to access content page controls from master page in asp.net
Nested Masterpages and .FindControl
The way you're processing and displaying the RSS in a view isn't the way
I'd do it, but the quick answer is that you need to call html_safe for any
HTML strings you build in this way.
This may be unsafe, as the incoming RSS data may have code in it that
causes cross site security issues. You can handle that by using the
sanitize helper. I think the sanitize helper automatically calls html_safe
for you.
So, at the end of your blog_feed method, replace the html return value
with:
sanitize html
try this code snippet
<?php
echo $this->Html->link('Company' . $this->Html->tag('b',
'', array('class' => 'caret')), '#',
array('class' => 'dropdown-toggle', 'data-toggle' =>
'dropdown','escape' => false));
?>
you can try to use javascript,
suppose A.aspx is parent page and B.aspx is the open page,
you can use "opener" to contronl DOM of A.aspx.
A.aspx link tag and javascript :
<a href="B.aspx" target="_blank">open page B</a>
<script type="text/javascript">
function fun_A() {
alert("hello");
}
</script>
B.aspx
<input id="btnChild" type="button" value="call function in Page A"
onclick="opener.fun_A();" />
when you open B.aspx from A.aspx, and click the button from B.aspx,
you will see A.aspx alert message "hello".
hope this can help>
...
pChart can either render its output to a file, or as a stream of binary
data with an HTTP Content-Type of image/png.
So the easiest way to incorporate pChart with a webpage is to place the
charting/drawing functions in a separate PHP file, then call that separate
script from within your HTML via an image tag: <img
src="yourPChartFile.php"> which will display the image generated from
the script because the separate script is returning an image/png that your
browser can render.
If you insist on creating the chart in the same PHP file as your HTML page,
you have to save the pChart script results to an image file (via
$myPicture->render("FILE_NAME_HERE.png")) in a location your webserver
can access, then link to that generated file in your <img> tag.
All this is described in
Here is complete sample code how you can access ContentPlaceHolder:
First master code (Site1.master):
<%@ Master Language="C#" AutoEventWireup="true"
CodeBehind="Site1.master.cs" Inherits="WebTesterInherit.Site1" %>
<!DOCTYPE html>
>
Now custom class that inherits from Page:
public class MyPage: System.Web..
h
I found the way to refresh the URL so the new URL gets the new page name on
it. Go to your task flow and add
<redirect/>
inside the view tags that you want their URL's to be refreshed.
<view id="help_id">
<page>/help.jspx</page>
<redirect/>
</view>
This is what the Jdev help says about the redirect tag:
Redirect:
Choose true if the ADF controller should issue an HTTP redirect for a view
activity request. The redirected request creates a new browser URL for the
view activity. The original view URL is no longer used.
Html.LabelFor reads the metadata from a model property and displays the
name of the property.
You can configure the displayed name with the Display or DisplayName
attributes.
Your model has no properties, so LabelFor is completely useless in your
example.
What do you want to achieve?
When you want to render a label with the value of the string just create a
label:
<label>@names</label>
Add a hidden field. Set the value in that field to the value of the
variable in Javascript.
<form action="cgi-bin/runalg.cgi" method="post"
enctype="multipart/form-data">
[...]
<input type="hidden" name="ID" value="default">
</form>
And then on javascript:
<script type="text/javascript">
document.forms[0].elements["ID"].value = getValue("ID");
</script>
The index for the form may vary in your document.
The page that you've put the content control is not a master page based
page. Check the top of the page, if you've got html like
<html>
<body>
tags then the likelihood is that you've created a new page rather than a
new page based off a masterpage.
Server controls may or may not render HTML depending on how you use them,
for example I use the Literal control to output text to the page and Labels
where I want to "associate" text to another control - but essentially HTML
output is the same. What is it you are you trying to acheive?
these links can help you in regards to papulate views in mvc
The Page has a Render method, within the page hierarchy (process runs after
PreRender page event). This Rendering process navigates through the
control hierarchy of the page, and calls the Render method on each control.
label has a Render method that renders a label or span accordingly, and
the Rendered HTML flushes to the browser.
When you drag a control onto the page in the Visual Studio designer (or
other tool), it places that control within a hierarchy that contains all of
the page's controls, so the Label would be rendered within the hierarchy.
For instance, if you had:
Page
Panel control
Label control
The label will be rendered within the markup of the panel, since the Panel
is the parent of the Label.
That particular element would actually be a TextBox MSDN TextBox
It would look like this <asp:TextBox. this would then render <input type="text"
id="_Email" class="contact-form" />
The Literal control doesn't produce an HTML element and allows you to add
text/html to your page and not wrap it in any other HTML.
The Label control actually outputs a <span></span> and puts
your Text in between it.
you can use mvc htmlhelpers. for example a flexible htmlhelper for
dropdownlist that accept collection and other parameters. another
htmlhelper to get collection and delivers listbox and .....
and in your view you can use of this htmlhelpers by their types.
You load controls dynamically via control.add method. First get an object
of user control and then use control.add property for that.
See following link for the reference.
Make sure you have added the ScriptManager to your Masterpage - or standard
Web forms if not using a MasterPage.
This needs to go inside your <form runat="server"> tag
<asp:ScriptManager</asp:ScriptManager>
To access the controls in your child page do the following steps:
1-declare a variable of the type you want to access. For example if you
want to access a Label in your child page use:
Label lbl_child=this.ContentPlaceHolder1.findcontrol("your label id in
child page") as Label;
Now you have your label and you are free to make changes on it. Every
change on this control will be reflected on the child control.
ContentPlaceHolder1 is your contentplace holder id so change it with your
content id.
Setting the IsEnabled property to false of the parent control should
disable child controls.
It was due to the fact that the video object was faded in by jQuery after
the documented loaded and a link was clicked - I assume it was because of
the fading transition that IE9 couldn't handle the video object properly.
What I did was allow the fade in, and once complete I cloned the video
object to reinstantiate it.
You have different ways:
1. Use only one row to add or edit a record and use a gridview or repeater
to show data
2. use gridview in editmode (but i'm not expert about this)
3. you can put controls in gridview or repeater and manage all events using
item/rowcommand
I think you must use a layout container. However, Grid is also a layout
container. If you don't want to use a StackPanel or any other control which
behaves like you described, you can also define rows and columns inside of
a Grid.
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Label Content="Firstlabel" Grid.
<Label Content="Secondlabel" Grid.
</Grid>
You can also set the width of the RowDefinition.
I changed your class a little bit and it now uses async/await instead of
busy-waiting.
You can use it as
var th = new WebsiteThumbnailImage("", 1024, 768, 256,
192);
this.BackgroundImage = await th.GenerateWebSiteThumbnailImage();
.
class WebsiteThumbnailImage
{
public WebsiteThumbnailImage(string Url, int BrowserWidth, int
BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
{
this.Url = Url;
this.BrowserWidth = BrowserWidth;
this.BrowserHeight = BrowserHeight;
this.ThumbnailHeight = ThumbnailHeight;
this.ThumbnailWidth = ThumbnailWidth;
}
public string Url { set; get; }
public int ThumbnailWidth { set; get; }
public int ThumbnailHeight { set; get; }
public int BrowserWidth { set; get; }
Try this in your template:
<div id="post">
<h1> {{ post.title }}</h1>
<p>{{post.content|safe}}</p>
<i>{{post.date}}</i>
</div>
You should expose all controls from ucA as properties, then look for the
control inside the DevxPopup the same way you doing. Given that all the
controls that you need at the ucA has properties to access them, you could
do all the logic you need!
Example:
public ucA : UserControl
{
public string myTextBoxText
{
get
{
return ((TextBox)Controls.FindControl("myTextBox")).Text;
}
}
/*And lot of controls*/
}
Then you looking for the popup at the Form
var ucA =
(UcA)Form.Controls.FindControl("myPopup").Controls.FindControl("myucA");
ucA.myTextBoxText = /*Do stuff here with the text*/
Hopes this help you!.
you are creating the dynamic controls in javascript? i.e. you are creating
html elements in javascript. It won't matter even if you put a
runat="server" attribute in there, because it is still at the client-end.
That would not be a part of the viewstate bag, so not populated in the
controls collection.
you need to change your logic. create dynamic control in code-behind on
button postback.
try this
<div>
<asp:TextBox</asp:TextBox>
<asp:Button ID="Button1" Text="test" Width="10%" Style="float:
right;" runat="server">
</asp:Button>
<asp:Label</asp:Label>
</div> | http://www.w3hello.com/questions/-Web-page-shows-straight-HTML-but-no-asp-controls- | CC-MAIN-2018-17 | refinedweb | 2,010 | 65.73 |
- a floor wax and a desert topping!!
Admin
That really makes me laugh ... I suppose it is possible that it might REALLY need to implement all these, but .... no it can't be possible. Now, it might be NECESSARY due to some really bad design decisions in the object hierachy of this library, but with a good design this should never happen ... ever hear of inheritence?
(A pre-emptive: yes, VB.NET has iheritence ... no, the WTF isn't just using VB in general ....)
Admin
This is a prime candidate for anonymous inner classes, I know some people hate them but I think they're better than implementing at the main class level thus making all the methods public. I guess it depends on how those interface methods are called.
Admin
Looking at all those listeners.. I wonder if those are all interfaces or not. Also, the question I have is.. why in the world is it written in c# using the keyword "implements" o.O are you sure this is written in vb.net? cuz it also has the { and // comments.
I doubt this even compiled!
Admin
Admin
Oh god damn!
Admin
how many lines of code does it take just to implement the interface members?
Admin
It could be any number of methods betwen 0 and n to implement each interface.
The real WTF is the sheer amount of events that must be firing left and right all over this application.
Admin
He should at least have a "ScheduleChangeListener", that would remove 4 or 5 of them.
Admin
Clearly this is a class made to attract women. Whenever women want to give a man a compliment they say "he's a good listener."
Admin
Lemme guess, all this and I only have to override one method too, right?
Admin
I'm particularly fond of the OKListener.
Admin
[:'(] HAHAHAHAHAHAHAHAHAHAHAHAHA...cough cough... gasp.... MUAHAHAHAHAHAHAHAHAH...Crash.. (fall dead on floor) WTF is this programmer thinking???? Why not just implement every thing and then you would never need to use any other object but yours.
Admin
<FONT style="BACKGROUND-COLOR: #efefef">oops, yes it is C#, not VB.NET .....</FONT>
Admin
Admin
*sigh* It is Java, damnit, and it's a "feature" of java that if you want to listen to an event, you must implement an interface which is <eventname>Listener.
Yes, anonymous inner classes are a common way of hacking around this stupid implementation choice, but .Net's delegate approach is much better.
MFL is better than YFL.
Admin
I like the Google ads for this thread... :)
Admin
That... was painful.
Admin
The plural of 'knife' is 'knives'.
Admin
That's an insult to C# coders :p
Admin
btw, as it was already said, it in Java, not C#.
At least, this could possibly be easy to fix; just implements those methods in an abstract base class and inherit it where needed...
Admin
Guess this makes Java a WTF-worthy language.[8-)]
Admin
<font face="Georgia">It's possible to produce a WTF in any language. It's not the language, it's the programmer.<font face="Georgia">This is fairly reasonable: you keep your operations in separate modules and bring them all together in one place. It doesn't matter so much that the Dispatcher is a huge honkin' piece of blather, because at least it's centralised and easy to understand.
Until someone mentioned the <event>Listener issue and cast it in a new light (what can I say - I'm not a Java programmer so I don't know this stuff) I would have almost seen the reason for today's WTF. My theory was that the programmer had produced lots of interfaces that each did a single, discrete job, which is a Good Thing TM. Then, he had a single class that pulled it all together, presumably some sort of dispatcher of multiple operations. In the old days you'd do it like this (demonstrating in some made-up language):
</font>
However: today's WTF is not this. It's just a WTF. Can't do anything about it, other than instructing the programmer on the pros and cons of extreme event-handling.
</font>
Admin
Its much more than the latest Spishak product.
It slices, it dices,makes julien fries
Sings, dances and plays the guitar.
Admin
That's weird, it seems to be missing all the system, io, network, shutdown, and ui listeners. Man, what an abject failure. This should listen to EVERY event that could ever possibly occur, and make sure to handle it. If necessary, rewrite Java.
It's bound to come out better anyway.
Admin
Frankly, I don't see this as a WTF. Java Event Listener interfaces generally consist of a single method. If this were in MFC you'd have a message map like so:
BEGIN_MESSAGE_MAP(CMyWnd, CWnd)
ON_MESSAGE(WM_MESSAGE, OnMessage)
ON_MESSAGE(WM_ERROR, OnError)
ON_MESSAGE(WM_HELPREQUEST, OnHelpRequest)
ON_MESSAGE(WM_OPENSCHEDULE, OnOpenSchedule)
ON_MESSAGE(WM_ATTRIBUTEBIGLIST, OnAttributeBigList)
ON_MESSAGE(WM_OKLISTENER, OnOKListener)
ON_MESSAGE(WM_DELETESCHEDULE, OnDeleteSchedule)
ON_MESSAGE(WM_REFRESHSCHEDULELIST, OnRefreshScheduleList)
ON_MESSAGE(WM_SCHEDULEWEEKCHANGE, OnScheduleWeekChange)
ON_MESSAGE(WM_NETWORKCHANGE, OnNetworkChange)
ON_MESSAGE(WM_SCHEDULEITEM, OnScheduleItem)
ON_MESSAGE(WM_LAYOUTCHANGED, OnLayoutChanged)
ON_MESSAGE(WM_ITEM, OnItem)
ON_MESSAGE(WM_INTERNALFRAME, OnInternalFrame)
ON_MESSAGE(WM_RENAMESCHEDULE, OnRenameSchedule)
ON_MESSAGE(WM_CANCEL, OnCancel)
ON_MESSAGE(WM_MIRRORPOLICYCONTROL, OnMirrorPolicyControl)
END_MESSAGE_MAP()
I've certainly seen my share of MFC classes with message maps larger than that. The only WTFs I see are in the names of some of these listeners and in the fact that Java uses interface inheritance for event notifications, neither of which are likely in the control of the person who wrote this code.
Admin
While I would certainly agree that MFC message maps are the ugly beasts on the face of the planet, they actually use a cool little hack to map the actual events that one does indeed wish to handle to a class member function.
Now, I won't pretend to know the intricacies of java, however, if you are implementing an interface, can you provide a partial implementation in java or do you have to implement all of the methods for that interface? If it is the latter, then I would certainly say that the MFC version is less a WTF, yet more WTFugly.
Admin
No, it's a convention, not a requirement.
The entire interface model is by convention, there's not even any language construct to force you to obey any programmatic constructs.
The real WTF is the mess that java forces on you to follow the "Conventional" event model, which till doesn't even handle cross-thread events safely (not that .NET does either. but that's a different story).
Admin
It would be interesting to see the code for this. It could well be that this class has only one method, along the lines of:This would make a "generic listener" that you could attach at any place in the system to log the events that are being generated.
Of course, one would then wonder why it doesn't implement a generic Listener interface of which all of the above are subinterfaces, but maybe the WTF is that the API doesn't have that.
Admin
Actually, I think this is Java because of both the "{...}"s and the "implements" keyword
Admin
exactly my first thought when i saw this piece of code.
tobi
Admin
You can extend the adapter class for that particular interface and override only the methods you need.
Admin
You mean the WTF here wasn't the placement of the { ? [:D]
Admin
If you are criticizing this class declaration you obviously have no understanding of object oriented design.
Admin
It's the vitameatavegamin of programming!
Admin
I work with Java, and this is like the WTF of OO design. I can also never shake the feeling that Java forces you to create WTFs by design...
Admin
I Swiss Army Knife?
Admin
<FONT style="BACKGROUND-COLOR: #efefef">but why leave out 'KitchenSinkListener'?</FONT>
Admin
<FONT size=2> </FONT>
<FONT style="BACKGROUND-COLOR: #efefef">but why leave out 'KitchenSinkListener'?</FONT><FONT style="BACKGROUND-COLOR: #efefef" size=1>
Because that would be gratuitous?<?xml:namespace prefix = o<o:p></o:p></FONT>
Admin
Note about inheritance - yes VB.NET (and C#.NET, and WHATEVER.NET) support inheritance - but NOT multiple inheritance. So, interfaces would have to be used to fill that void.
Admin
In Java, if you have an interface (not a class), you must provide implementations for every method it names. This is because an interface is a form of a contract; it's a programatic way of stating, "I will always provide you with these methods".
The Java language developers quickly realized that many API users wouldn't want to provide implementations for all the events in a single listener interface. An example: WindowListener, I may only be interested in when the window is closed (so I can cleanup), but don't care when the window is minimzed or maximized.
So they provided classes called Adapters, which provide a default functionality for all the events in a given interface. So, the WindowAdapter class implements the WindowListener interface and does nothing when any of those events are provided. In design-pattern terms, this is an example of a Null Design pattern object: an object that meets a contract (interface) but doesn't actually do anything.
So, now I can make an new class extended from WindowAdapter that extends only the methods I care about and get proper default functionality.
As a few asides: this is all due to the mess that is Java's event conventions. Also, any one with any software-engineering competence quickly realizes that having both WindowListener and WindowAdapter is redundant; you could just have WindowAdapter and let the contract be implict in it's declaration. However, explict contracts seem to be the underlying practice in all Java design, so we end up with the mess we).
The irony of this is that while it simplies the language for the user, it doesn't make the language implementation any easier to the program. AFAIK, Java cannot handle the case where any two parent objects (be they classes or interfaces) declare the same method signature, it will fail to compile.
C++ provides mechanisms around this issue, as does C#.
Admin
Admin
Admin
NB: This forum software is tremendously broken. Somebody should fix it.
Still, I'm impressed by the originality of this quoting Bug.
Admin). "
I think you are saying exactly what I said, just in another way.
Admin
The key part, which you failed to quote, was "So, interfaces would have to be used to fill that void."
Admin
Yes, but it still is multiple inhertience.
People seem to think the interface construct is a magical thing; it's not, it's just a less-expressive (and arguably, less vauge when used correctly) object construct.
Saying Java doesn't have MI is somewhat like saying Java doesn't have pointers. It does, it just doesn't in the C/C++ sense.
Admin
It depends on how you define multiple inheritance.
The definition I subscribe to is "<font>a derived class with multiple base classes."
By this definition, I am correct.
Your definition is more like "</font><font>Inheritance from more than one existing construct".
It's a semantic issue.
</font>
Admin
Whatever do you mean by "less vauge"? Or "used correctly"?
And what's that "object construct" you're talking of? As far as I remember, there are no "interface-objects" - just objects of classes possibly implementing some interface(s). Even anonymus classes implementing some interface are just that, classes.
Yeah, right. But then, talking in the C++ sense, Java lacks references. (Besides some other really useful things.)
Also, my original question, before the board swallowed it last time, concerning the redundancy of WindowAdapter et al: Would you really prefer to be forced to derive from WindowAdapter or whatever Listener you might need to extending a class of your choice? Since, talking C++ of course, Java has no MI!?
I'm no Java guru, so you might care to help me out a little and enlighten me on these few things...
Admin
I guess the interface construct is useful because if all you had were abstract base classes, designers would be tempted to specify data as well as just methods. Which is frequently not desirable. Hence, we have interfaces, where data is disallowed.
Remeber that in C# and Java, everything that can be specified in an interface can be specified in an abstract class as well. Note that C++ doesn't have an explict interface construct, but I still can create them.
See the WindowListener/WindowAdapter example above. The fact that a class exists implementing "default" functionality for an interface tells me the interface doesn't need to exist, as what the interface models is made implict by the class anyway.
However in Java, frequently you have to have both because of the way the MI model is designed.
Perhaps an example will make things more clear. Say I have an object that wants two events: one when it succeeds and one when it fails (let's ignore the more obvious choice of a generic completion event with a success/fail flag). I need to handle three posibilities:
So, I have a few options as how to design this:
[code language="Java"]public interface ObjectSucceededListener {
public void objectSucceededListener(ObjectEvent e);
}
public interface ObjectFailedListener {
public void objectFailedListener(ObjectEvent e);
}[/code]This is an OK approach, but has some problems: it means the object generating the events has two keep two lists of events, one for success and one for failure (major); clients of type 3 have to declare themselves as implementing both interfaces (minor) ; and clients of type 3 have to register themselves twice (major). For two events, registering twice in no big deal. For thirty events, it's a PITA. Also, in Java, you'd have to write the same stupid code for each event you want to send, which is tedious and can be error-prone if you have a lot.
So while this is a workable solution, it's far from ideal. Let's see if we can do better.
public abstract void objectSucceeded(ObjectEvent e);
public abstract void objectFailed(ObjectEvent e);
}[/code]This solves the problems for clients of type 3. However, it creates a new problem for clients of type 1 and 2: they must implement some sort of behavior for whichever event they're not interested in. So we've just traded one set of problems for another. We can solve this by doing:[code language="java"]public class ObjectCompletionAdapter extends ObjectCompletionListener {
public void objectSucceeded(ObjectEvent e) { // Do nothing }
public void objectCompleted(ObjectEvent e) { // Do nothing }
}[/code]This solves the problem: now clients of all types can be served by our model, and the sending object only needs one list of events.
However, note the important part: What is the difference between ObjectCompletionListener and ObjectCompletionAdapter? Two blocks of "{ // Do nothing}". That's it. So isn't the ObjectCompletionListener interface redundant? Yes, it is. Which was my point. Everything the interface specifies is already specified by the class that extends from it.
So is the interface useful? If the behavior the class implements can't be used by everyone who wishes to implement the interface, then yes, it is useful. But the reality of it is that an Adapter that does nothing can implemented by anyone who would implement the inteface proper.. So in this case, the interface is redundant, and can be removed. This is ignoring the limitations of Java's MI model that may require you to have the interface anyway in some situations. Normally, you can get around those by creating an inner class or an anonymous class.
Yet, we see this pattern of interface -> class -> everyone else all the time in Java. Interfaces are useful when you want to state a set of behaviors (methods) that can be implemented by disjoint sets of data (meaning the behaviors are independent of the data/object that implements them) and there is no valid default behavior.
It's the last bit, the "no valid default" bit, that people forget.
That being said, the harm is somewhat negligible. It just means you have a redudant specification of your interface, which isn't inherently evil or anything of the sort. But it isn't something you have to do either, and I see people all the time writing code where every public method is specified in an interface even when it's unnecessary.
FWIW, this goes back to "Design-by-contract" programming, which is a good thing. But people seem to think that "Design-by-contract" can only be met by interfaces. This isn't true at all. It can also be met by abstract classes and regular classes.
I was refering specifically to classes and interfaces. In other langauges, anything a class can inherit from would be included.
You can create a variable of an interface type though, and then only have access to the methods the interface stated
I'd rather just have the Adapter and be forced to use anonymous inner classes. For events anyway, it reduces the amount of code I have to write. The only clear advantage interfaces give you is that you don't have to use inner classes, but the reality of Java is that you will anyway because it makes your code more managable and extensible.
So in this case, I don't see the gain. That being said, don't take that to mean I think interfaces should go away: they're a useful construct. And I do prefer having an interface type than having to do the C++:[code language="C++"]class Foo {
public:
virtual void func1() = 0;
virtual void func2() = 0;
};[/code]At the very least, the different in name (interface vs. class) makes my intent clear with what I'm creating. Sure, you can do the same thing with an ABT, but that doesn't make it neccessarily better. But if I do have default behavior that's valid all of the time, then I don't see the point of not creating just a class.
Hopefully I've been clear enough so you can understand what I'm getting at.And when you consider that the only difference between an interface and a class is that the former can only declare methods, you realize the former definition is full encasuplated by the latter, as such, it's a touch foolish to define MI solely by the latter.
Especially in C++ (which is where this thinking seems to come from) interfaces are classes (as in, they use the same keyword). Specifically, a pure C++ ABT is equivalent to a C# or Java interface.
</font> | https://thedailywtf.com/articles/comments/Implements_ISwissArmyKnife | CC-MAIN-2018-26 | refinedweb | 3,113 | 63.7 |
Hi all,
I could not find anything regarding this subject.
Does anyone know how to get the current round, when a round ends in counter strike source?
Thanks in advance!
Regards,
Flowan
[CSS] Get current round
Please post any questions about developing your plugin here. Please use the search function before posting!
2 posts • Page 1 of 1
Re: [CSS] Get current round
Currently, there is no such function available, but you can simply sum the wins of all teams, which usually reflects the round count.
Syntax: Select all
from players.teams import team_managers
from filters.entities import EntityIter
def get_round_count():
return sum(entity.score for entity in EntityIter(team_managers))
print(get_round_count())
2 posts • Page 1 of 1
Return to “Plugin Development Support”
Who is online
Users browsing this forum: No registered users and 1 guest | https://forums.sourcepython.com/viewtopic.php?f=20&t=1471 | CC-MAIN-2017-17 | refinedweb | 136 | 66.74 |
EUG:How to Contribute
How to Contribute to the Eclipse Users Guide
These wiki pages are the source of the ECF Users Guide. The text that will be created here will end up here, for everybody to read, in the Eclipse help that accompanies the ECF software and maybe even in the printed book, who knows.Click. You only have to type the horizontal line when inserting a link to a new page, the title will be automatically inserted without the namespace.
(2) The Complete Manual
This link lists the complete book on one single web page. This is done by a process called transclusion which is a fancy word for inclusion. If you edit the page that (2) links to, you will see this: | http://wiki.eclipse.org/index.php?title=EUG:How_to_Contribute&oldid=225647 | CC-MAIN-2015-32 | refinedweb | 125 | 76.05 |
Android Threading Tutorial and Examples
This is our android threading tutorial. We explore what a thread is and provide several abstractions for the
Thread class.
What is a Thread?
A thread is a path of execution that exists within a process.
One process may have one or more threads.
A Single-threaded process has one thread while a multi-threaded process has more than one threads.
In the single-threaded process, we have only one flow of execution of instructions while in multi-threaded process we have we have multiple sets of instructions executed simultaneously.
A multi-threaded process has parts running concurrently and each part can do a given task independently.
So multi-threadig is a mechanism that allows us write programs in a way in which multiple activities can proceed concurrently in the same program.
And especially in today’s multicore-device environment, developers should be capable of creating concurrent lines of execution that combine and aggregate data from multiple resources.
But, it is also important to note that in reality, a system that has only a single execution core can create the illusion of concurrent execution. It does this by executing the various threads in an interleaved manner.
But it does it fast such that we think that it’s actually doing tasks concurrently.
The Main Thread
Normally when you run your project,your application process will start. First there will be housekeeping threads for the Android Runtime or Dalvik Virtual Machine.
Apart from those the Android System will create a thread of execution called
main. This will be the main thread for your application.
This thread is also sometimes called the
UI thread.
You application can have many other threads, normally called background threads. However the main thread is the most crucial one. It is this thread that is responsible for interacting with Android Components and Views. It renders them and also updates their states.
This thread is very crucial especially given the fact as we’ve said, that it is where all android components(Activity, Services, BroadcastReceiver ) are executed by default.
This thread is the one responsible for handling and listening to user input events. Due to how important it is, it’s always adviced to keep it responsive by:
- Not doing any kind task that are likely to take along time like
input/output(I/O) in this thread. These tasks can block the main thread for an indefinite amount of time hence have to be ofloaded to a background thread.
- Not doing CPU-intensive tasks in this thread. If you have some expensive calculations or tasks like video encoding, you need to offload them as well to background thread.
This thread normally has a facility attached to it called Looper. Looper will hold a MessageQueue. A MessageQueue is just a queue of messages with some unit of work that are to be executed sequentially.
So when a message is ready to be processed on the queue, the Looper Thread will pop that message from the queue. That message will be forwarded synchronously(sequentially) to the target handler. That handler is already specified in the message.
Then the Handler will start it’s work and do it. When it finishes that work, then the Looper thread starts processing the next message available on the queue and pass it over for it to be also executed.
You can see this process is sequential. So suppose our Handler doesn’t finish it’s work quickly, the Looper will just be there waiting to process other pending messages in the queue.
In that case the system will show the Application Not Responding(ANR) Dialog. You may have already seen these in some apps. It means that application is not responding to user inputs. Yet it’s busy doing work.[notice] The ANR Dialog will be shown to users if an app doesn’t respond to user input within five seconds. The system will then offer users the option to quit the application.
[/notice]
You will run into this type of scenario when you try to do intensive tasks in your main thread. That means for example when you try to do the following in your main thread:
- Access the Network/Web Services/internet
- Access File system resources.
- Try processing large amounts of data or doing complex math calculations etc.
Most of the code you write like in your activities, fragments, services normally run in the main thread by defaulu, unless you explicitly create a background thread.
Android SDK is based on a subset of Java SDK. Java SDK is derived from the Apache Harmony project and provides access to low-level concurrency constructs such as:
java.lang.Thread.
java.lang.Runnable.
synchronizedand
volatilekeywords.
Thread class
The class
java.lang.Thread is the most basic construct used to create threads.
It is also the most commonly used. This class creates us a new independent line of execution in a Java program.
One way of creating a new thread is just by subclassing or extending the
java.lang.Thread class.
public class MyThread extends Thread { public void run() { Log.d("Generic", "Our thread is running ..."); } }
We can then do our background task inside the
run() method.
However that thread is not yet started. For that to happen we have to instantiate that class and explicitly start our thread:
MyThread myThread = new MyThread(); myTread.start();
The
start() method resides in the
Thread class. Invoking it tells the system to create a thread inside the process and executes the
run() method. The
run() will be executed automatically if we invoke the
start() method.
Common Threading Methods
(a). Thread.currentThread()
This method will return the Thread of the caller, that is, the current Thread.
(b). Thread.sleep(time)
This method will cause the thread which sent this message to sleep for the given interval of time (given in milliseconds and nanoseconds). The precision is not guaranteed – the
Thread may sleep more or less than requested.
Basically it pauses the current thread from execution for the
given period of time.
(c). getContextClassLoader()
This method will return the context ClassLoader for this Thread.
(d). start()
This method will start the new Thread of execution. The
run() method of the receiver will be called by the receiver Thread itself (and not the Thread calling
start()).
(e). Thread.getName() and Thread.getId()
These will get the
name and
TID respectively. These are mainly used for debugging purposes.
(f) Thread.isAlive()
isAlive() will check whether the thread is currently running or it
has already finished its job.
(g) Thread.join()
join() will block the current thread and wait until the accessed
thread finishes its execution or dies.
How to Maintain App Responsiveness
The best way to maintain app responsiveness is not by shunning away doing long running operations. Instead it is by offloading them from the main
thread so that they can be handled in the background by another thread.
The main thread can then continue to process user-interface updates smoothly and respond in a timely fashion to user interactions.
Normally there are a set of typical operations that are common in many applications and do consume not only alot of time but also device resources.
These include:
- Accessing and Communicating via the network, especially internet.
- File Input and output operations. These occur on the local filesystem.
- Processing Image and video.
- Complex math calculations.
- Text processing – Trying to process or analyze a large blob of text.
- Data encoding and decoding.
Quick Threading Examples
1. Creating simple Timer with Thread class
This is a class to show how to implement a simple timer. It doesn’t print our anything and is just a class showing how to implement such an idea.
import java.lang.Thread; public class TimerClass extends Thread{ boolean timeExpired; double mTime; /** Creates a new instance of TimerClass */ public TimerClass(double time){ mTime = time; } public void run(){ timeExpired = true; mTime = mTime * 1000; double startTime = System.currentTimeMillis(); double stopTime = startTime + mTime; while(System.currentTimeMillis() < stopTime && timeExpired == false){ try { Thread.sleep(10); } catch (InterruptedException e){ } } timeExpired = true; } public boolean getTimeExpired(){ return true; } public void cancel(){ timeExpired = true; } }
2. Full Reusable Thread Utility class
import android.os.Looper; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Threading tools * </p> */ public class ThreadUtils { private final static ExecutorService sThreadPool = Executors.newCachedThreadPool(); /** * Current thread */ public static Thread currentThread() { return Thread.currentThread(); } /** * Current process ID */ public static long currentThreadId() { return Thread.currentThread().getId(); } /** * Current process name */ public static String currentThreadName() { return Thread.currentThread().getName(); } /** * Determine if it is a UI thread */ public static boolean isUiThread() { return Looper.myLooper() == Looper.getMainLooper(); } /** * Runs on the UI thread */ public static void runOnUiThread(Runnable action) { if (action == null) { return; } if (Looper.myLooper() == Looper.getMainLooper()) { action.run(); } else { HandlerUtils.uiPost(action); } } /** * Runs in the background thread */ public static void runOnBackgroundThread(Runnable action) { if(action==null){ return; } if (Looper.myLooper() != Looper.getMainLooper()) { action.run(); }else{ sThreadPool.submit(action); } } /** * Run on asynchronous thread */ public static void runOnAsyncThread(Runnable action) { if (action == null) { return; } sThreadPool.submit(action); } /** * Runs on the current thread */ public static void runOnPostThread(Runnable action) { if(action==null){ return; } action.run(); } public static void backgroundToUi ( final Runnable background , final Runnable ui ) { runOnBackgroundThread(new Runnable() { @Override public void run() { background.run(); runOnUiThread ( ui ); } }); } } | https://camposha.info/android-threading/ | CC-MAIN-2019-51 | refinedweb | 1,537 | 58.18 |
0
I'm really kind of stuck here, and would really appreciate some help. I have a function that reads from a csv that can get quite large, and it will block some other routines from running in there allocated time slice. I need to make this code “non-blocking”. I think there might be a way to accomplish using the fnctl module, but I'm not sure how to implement it. The code is as follows:
def csv_parser(self): # read and format csv to csv_data try: openfile = open(g.FS_TMP_TREND, "r") reader = csv.reader(openfile, dialect='excel', delimiter="|") for row in reader: for i in range(12): if row[i] == '': v = 0 else: v= float(row[i]) self.csvData[i].append(v) self.csvWriteIndex += 1 except: err = error_dialog(_('There was a problem loading csv data')) err.show()
thank you for any help you can offer | https://www.daniweb.com/programming/software-development/threads/197300/non-blocking-csv-reader | CC-MAIN-2018-09 | refinedweb | 147 | 74.19 |
#include <CCScriptSupport.h>
Execute a scripted global function.
The function should not take any parameters and should return an integer.
Implemented in LuaEngine.
Execute a script file.
Execute script code contained in the given string.
Get script type.
Reimplemented in LuaEngine.
called by CCAssert to allow scripting engine to handle failed assertions
Parse configuration file.
Reallocate script function handler, only LuaEngine class need to implement this function.
Remove script function handler, only LuaEngine class need to implement this function.
Remove script object.
when trigger a script event ,call this func,add params needed into ScriptEvent object.nativeObject is object triggering the event, can be nullptr in lua | http://www.cocos2d-x.org/reference/native-cpp/V3.0/de/d6f/classcocos2d_1_1_script_engine_protocol.html | CC-MAIN-2018-26 | refinedweb | 107 | 54.9 |
lfc_getgrpbynam - get virtual gid associated with a given group name
#include <sys/types.h> #include "lfc_api.h" int lfc_getgrpbynam (char *groupname, gid_t *gid)
lfc_getgrpbynam gets the virtual gid associated with a given group name. groupname specifies the group name. It must be at most 255 characters long. gid specifies the address of a buffer to receive the Virtual Group Id.
This routine returns 0 if the operation was successful or -1 if the operation failed. In the latter case, serrno is set appropriately.
EFAULT groupname or gid is a NULL pointer. EINVAL This group name does not exist in the internal mapping table or the length of groupname exceeds 255. SENOSHOST Host unknown. SENOSSERV Service unknown. SECOMERR Communication error. ENSNACT Name server is not running or is being shutdown. | http://huge-man-linux.net/man3/lfc_getgrpbynam.html | CC-MAIN-2017-17 | refinedweb | 129 | 62.34 |
Contains JavaScript utility functions for environment tests and support queries.
Contains JavaScript utility functions for environment tests and support queries.:
In node:
var header = require('atropa-header').header;console.log(header);
In the browser this module is attached to the global namespace
atropa, which
will be created if it does not exist.
Include
./browser/atropa-header_web.js in your page and
atropa.header will be available in your page.
For full documentation see
docs/jsdoc. For Visual Studio intellisense files
see
docs/vsdoc.-header_tests.html in your
favorite web browser.
To edit the tests for both the browser and Node, edit the jasmine test files in
browser/tests. For tests specific to Node edit the files in the
specs
directory.-header.js please run the
srcFormat,
lint, and
buildDocs scripts on it before submitting a pull
request.
Matthew Kastor
The license, gpl-3.0, can be found in the
License folder or online at | https://www.npmjs.com/package/atropa-header | CC-MAIN-2016-22 | refinedweb | 154 | 53.27 |
4. Execution model¶
4.1. Structure of a program¶
A Python program is constructed from code blocks. as a command line argument to the
interpreter) is a code block. A script command (a command specified on the
interpreter command line with the ‘-c’.
4.2. Naming and binding¶
4.2.1. Binding of names¶
Names refer to objects. Names are introduced by name binding operations.).
Each assignment or import statement occurs within a block defined by a class or function definition or at the module level (the top-level code block).
If a name is bound in a block, it is a local variable of that block, unless
declared as
nonlocal or
global. If a name is bound at
the module level, it is a global variable. (The variables of the module code
block are local and global.) If a variable is used in a code block but not
defined there, it is a free variable.
Each occurrence of a name in the program text refers to the binding of that name established by the following name resolution rules.
4.2.2. Resolution of names¶.
When a name is used in a code block, it is resolved using the nearest enclosing scope. The set of all such scopes visible to a code block is called the block’s environment.
When a name is not found at all, a
NameError exception is raised.
If the current scope is a function scope, and the name refers to a local
variable that has not yet been bound to a value at the point where the name is
used, an
UnboundLocalError exception is raised.
UnboundLocalError is a subclass of
NameError..
The
nonlocal statement causes corresponding names to refer
to previously bound variables in the nearest enclosing function scope.
SyntaxError is raised at compile time if the given name does not
exist in any enclosing function scope.
The namespace for a module is automatically created the first time a module is
imported. The main module for a script is always called
__main__.
Class definition blocks and arguments to
exec() and
eval() are
special in the context of name resolution.
A class definition is an executable statement that may use and define names.
These references follow the normal rules for name resolution with an exception
that unbound local variables are looked up in the global namespace.
The namespace of the class definition becomes the attribute dictionary of
the))
4.2.3. Builtins and restricted execution¶
CPython implementation detail: Users should not touch
__builtins__; it is strictly an implementation
detail. Users wanting to override values in the builtins namespace should
import the
builtins module and modify its
attributes appropriately..
4.2.4. Interaction with dynamic features¶
Name resolution of free variables occurs at runtime, not at compile time. This means that the following code will print 42:
i = 10 def f(): print(i) i = 42 f().
4.3. Exceptions¶ | https://docs.python.org/3.8/reference/executionmodel.html | CC-MAIN-2018-22 | refinedweb | 482 | 64.61 |
Sage 8.1 eats memory until system freeze
Hi, I have a quite long code (which uses arbitrary precision real numbers) which runs perfectly on Sage 7.5.1 (ppa for Mint 17.3 - Ubuntu 14.04). On Sage 8.1 (sage-8.1-Ubuntu_14.04-x86_64.tar.bz2) it starts to eat the memory until it freezes the system. I would like to help in debugging. Is there something that I can try/run/test? I can also upload the code, if necessary.
Finally, I have a minimal working code
def test(m,c,precision): M = 3*m RRR = RealField(prec = precision) coef02 = [RRR(1/i) for i in [1..M+1]] g = coef02[M] for i in [M-1..2,step=-1]: # Horner g = x*g+coef02[i] ME = 32 disk = [exp (2*pi.n(precision)*I*i/ME) for i in range(ME)] gamma = abs(c)/2 ellipse = [(gamma*(w+c^2/(4*gamma^2)/w)) for w in disk] epsilon1 = max([abs(g(x=z)) for z in ellipse]) return m = 40 for c in [1/2..10,step=1/2]: for ell in [1..10]: test(m,c,165)
If I run this in 7.5.1, I see (in top) the memory percentage stable around 2.5. If I run in 8.1, it grows up to 7.3 before code termination. If I increase the length of the loops, memory usage continues to grow.
Use a profiler, e.g.
to see where the code spends the most time. (Implement somehow hard breaks to make it finish.) Then look exactly at the corresponding points. It is hard to do this without the code.
Some IDEs may have a profiler functionality, e.g.
(Never tried it with sage.)
It is also a good idea to run the code in the debugger and follow the jumps a while till the run freezes...
Note: We only know that approximate values are used. Make sure, that all sage algorithms used do not require exact algebra to terminate. | https://ask.sagemath.org/question/41009/sage-81-eats-memory-until-system-freeze/?answer=41030 | CC-MAIN-2020-29 | refinedweb | 339 | 78.96 |
#include "angband.h"
#include "buildid.h"
#include "init.h"
#include "ui-input.h"
#include "ui-output.h"
#include "ui-term.h"
In-game help..
Peruse the On-Line-Help.
References NULL, screen_load(), screen_save(), show_file(), and void().
Referenced by menu_question(), and roller_command().
Recursive file perusal.
Return false on "?", otherwise true.
This function could be made much more efficient with the use of "seek" functionality, especially when moving backwards through a file, or forwards through a file by less than a page at a time. XXX XXX XXX
References A2I, ANGBAND_DIR_HELP, ANGBAND_DIR_INFO, ARROW_DOWN, ARROW_UP, askfor_aux(), bell(), buf, buildid, keypress::code, COLOUR_WHITE, COLOUR_YELLOW, contains_only_spaces(), ESCAPE, EVENT_MESSAGE_FLUSH, event_signal(), file_close(), file_getl(), file_open(), format(), FTYPE_TEXT, i, inkey(), KC_END, KC_ENTER, KC_HOME, KC_PGDOWN, KC_PGUP, MODE_READ, msg, my_strcpy(), NULL, path, path_build(), prefix(), prt(), show_file(), size, streq, strescape(), string_lower(), strnfmt(), strskip(), tag, Term_clear(), Term_get_size(), Term_putstr(), and void().
Referenced by do_cmd_help(), do_cmd_wiz_help(), option_toggle_handle(), and show_file().
Make a string lower case.
Referenced by show_file(). | http://buildbot.rephial.org/builds/master/doc/ui-help_8c.html | CC-MAIN-2017-43 | refinedweb | 152 | 62.64 |
Respected Sir,
How can I determine the byte offset of a field within a structure?
How can I access structure fields by name at run time?
please help me sir .
Thank you sir !!!
hi, Srinivasan
(i)In c offsetof() macro is defined in
<stddef.h>. With the help of it you can compute the offset field in structure struct s as offsetof(type,field).
#include <stddef.h> size_t offsetof(type, field); e.g. struct st { int a, b; }; offsetof(struct st, b);
(char *) casting arranges that the offset so computed is a byte offset.
(ii)Maintain the offsets field computed by the offsetof() macro.
*(int *)((char *)stp + offsetf) = value;
in the above the value of f can be set indirectly, here stp is the pointer to an instance of the srurcture and the field is an int which has the offset offsetf.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions. | http://roseindia.net/answers/viewqa/IoC/19497-C-Language.html | CC-MAIN-2013-20 | refinedweb | 178 | 82.54 |
On April 23rd I had a job phone interview. The talk was about a Software Development Engineer in Test (SDET) position at Microsoft.
I already blogged about a C# Thread Safe Circular Queue, which was one of the questions of a screen test (prior to a phone interview) I completed on January for the same Microsoft job position.
On this last interview we (me and the Microsoft employee-interviewer) would talk a little bit and then get to the coding questions. It didn't happen as expected. Firstly the Microsoft interviewer tried to call me on my cellphone. I just couldn't hear a word of what he was saying. The sound was very low. Then we decided to start with the coding questions and then on the phone land line we would talk so that he could explain more about the position, etc.
We started a meeting on Microsoft Office Live Meeting. I was asked about a simple and easy question.
The question:
Write a program that changes the position of the words of a given sentence. For example, given the sentence "How are you going" as input, the output should be "are How going you".
Simple, isn't it? I thought that too at the moment.
As you can see, the first and second words change of position and then the third and forth words change of position and so forth.
The interviewer explained that I could write any code. It didn't need to be written with the syntax of a programming language, it could be a pseudocode.
I'm so used to code using code auto-completion (IntelliSense) and the debugger that I just didn't write any good code to solve the question. It was really frustrating. All what I needed to do was clear in my mind but I just couldn't express it. Was that the case of me being nervous? Beats me.
Today I decided about writing a post with a possible solution to this simple programming question. I opened Microsoft Visual Studio C# Express and wrote some code. In just 5 minutes I had a working code that did the job.
There are things in life that are really weird. I passed more than 45 minutes trying to write a pseudocode and then with the help of IntelliSense and debugger catching my mistakes, things flowed flawlessly and rapidly. Why that faster? I don't know how to explain it, maybe because of IntelliSense and the presence of a handy debugger!
For sure the solution I present here isn't the better, but it's a solution and that's what was asked.
Bellow is the code I wrote:
namespace WordPermuter { class Program { static void Main(string[] args) { List<string> sentences = new List<string>() { { "How are you going my dear?" }, // are How going you dear? my
{ "I am going fine honey." } // am I fine going honey };
DoPermutation(sentences); }
static void DoPermutation(List<string> sentences) { foreach(string sentence in sentences) { // Split the sentence when it reaches a white space var splitted = sentence.Split(' ');
// Increment the counter on a scale of 2 for(int i = 0; i < splitted.Length; i = i + 2) { if(i < splitted.Length - 1) { var aux = splitted[i];
splitted[i] = splitted[i + 1];
splitted[i + 1] = aux; } }
foreach(var str in splitted) Console.Write(str + " ");
Console.WriteLine(); } } } }
What's the purpose of this code? Aha... It isn't the code itself but what approach you took to get to a solution. The interviewer wants to see how is your thinking process. No matter if you coded it wrong, but at least you should show something. As the recruiters always say: "Think it loud so that we can help you."
After a solution has been presented, the interviewer will probably ask you what if questions. What if I did this way? What If I did that way? What is the breach? What are the possible bugs?... The list of possible questions is innumerable.
I think my solution is OK! If you find any bug, please tell me. | https://www.leniel.net/2008/05/csharp-word-permuter-shifter.html | CC-MAIN-2019-13 | refinedweb | 675 | 75.4 |
Prev
Java JVM Code Index
Headers
Your browser does not support iframes.
Re: Do I need to sync Get methods that return thread-safe collections
From:
Mark Space <markspace@sbc.global.net>
Newsgroups:
comp.lang.java.programmer
Date:
Sun, 03 Aug 2008 00:01:36 -0700
Message-ID:
<xJclk.17157$mh5.7661@nlpi067.nbdc.sbc.com>
Lew wrote:
Royan wrote:
I'm trying to find potential pitfall in unsynchronized methods that
return thread-safe collections. Assume i'm [sic] designing a thread-safe
class.
Read the articles on concurrency by Brian Goetz in IBM DeveloperWorks,
and his book /Java Concurrency in Practice/.
This is the best advice. Thread safety is complicated enough that a
couple of quick posts on Usenet won't explain everything. You need
something more thorough to give you the full picture. Java Concurrency
in Practice will give an excellent understand of many thread safety and
concurrency issue.
Case in point:
>> public class ThreadSafe {
>>
>> private Vector<String> vector;
>> /** But is OK to have such method? */
>> public Vector<String> getVector() {
>> return vector;
>> }
>> }
Nope, not ok. You created an object on one thread (not shown) and then
tried to fetch it on another. Guaranteed problems. Example:
Let's say ThreadSafe has a constructor which Thread A calls:
public ThreadSafe() {
vector = new Vector<String>();
}
Now Thread B calls getVector. Oops!! It may not even see the value of
the reference (field "vector" might be null still) or thread B might see
the Vector in a partially constructed state (there's still bits of it in
Thread A's cache which haven't been written out yet). Either way, big
trouble.
>> public class ThreadSafe {
>>
private volatile Vector<String> vector;
>> /** But is OK to have such method? */
>> public Vector<String> getVector() {
>> return vector;
>> }
>> }
Now you're safe. Making getVector() "synchronized" would do the same
thing. (The JVM knows to flush objects around the synchronized "memory
barrier.") See Java Concurrency in Practice for more....
Generated by PreciseInfo ™
Mulla Nasrudin was told he would lose his phone if he did not retract
what he had said to the General Manager of the phone company in the
course of!" | http://preciseinfo.org/Convert/Articles_Java/JVM_Code/Java-JVM-Code-080803100136.html | CC-MAIN-2021-49 | refinedweb | 354 | 65.73 |
Hi, The second time I press control-c, it isn't caught -- the program exits instead. Why? (The context is, I'm writing an interactive program where calculations may take a long time. Control-c during a calculation should return the user to a prompt. As things stand, this can only be done once -- the second calculation so interrupted causes the whole program to exit.) $ ./ctrlctest ^Cuser interrupt ^C -- program exits! $ cat ctrlctest.hs module Main where import Control.Concurrent (threadDelay) import qualified Control.Exception as C main :: IO () main = do (threadDelay 1000000 >> return ()) `C.catch` (\e -> print (e::C.AsyncException)) main $ ghc --version The Glorious Glasgow Haskell Compilation System, version 7.0.3 $ uname -mrsv Darwin 11.2.0 Darwin Kernel Version 11.2.0: Tue Aug 9 20:54:00 PDT 2011; root:xnu-1699.24.8~1/RELEASE_X86_64 x86_64 $ file ctrlctest ctrlctest: Mach-O executable i386 -------------- next part -------------- An HTML attachment was scrubbed... URL: <> | http://www.haskell.org/pipermail/haskell-cafe/2011-October/096431.html | CC-MAIN-2013-20 | refinedweb | 157 | 61.93 |
# What is the difference between px, em, rem, %? The answer is here
Introduction
------------
Beginners in web-development usually use **px** as the main size unit for **HTML** elements and **text**. But this is not entirely correct. There are other useful units for the font-size in **CSS**. Let's look at the most widely-used ones and find out when and where we can use them.

Overview
--------
If you familiar with size units in CSS and want to check your knowledge you can look at [**The Full Summary Table**](#the-full-summary-table).
But if you don 't know the differences between these units, I strongly recommend that you read this article and share your opinion about it in the comments below.
---
In this article, we will discuss such **size units** as:
| [px](#px) | [em](#em) | [rem](#rem) | [%](#percent) | [vw and vh](#vw-and-vh) | [rarely used units](#rarely-used-units) |
| --- | --- | --- | --- | --- | --- |
Furthermore, we will look at obsolete and unsuitable for the web-development size units. This will help you to make the right choice and use modern development practices. Let's get started!
The most widely used size units
-------------------------------
### px
---
**px** (**pix el**ement) is a main and base absolute size unit. **The browser converts all other units in px by default.**
The main **advantage** of **px** is its accuracy. It is not hard to guess that 1px is equal to 1px of the screen. If you zoom any raster image you will see little squares. There are pixels.

But the **disadvantage** is that pixel is an absolute unit. It means that pixel doesn't set the ratio.
Let's look at the simple example.

HTML of this example:
```
Hello,
Habr Reader!
```
CSS:
```
.element1 {
font-size: 20px;
}
.element2 {
font-size: 20px;
}
```
Element with **class='element2'** is nested in parent with **class='element1'**. For the both elements **font-size** is equal to **20px**. On the image above you can see that sizes of the words '**Hello**' and '**Habr Reader**' are the same.
What can this example say about a pixel? **Pixel sets a specific text size and does not depend on the parent element.**
*Note: the full code of this and the next examples you can find [**here**](https://codepen.io/Filanovich/pen/qBdVYpK). I don't show you all styles of the element on the picture above because our theme is the size units.*
### em
---
**em** is a more powerful unit size than **px** because it is **relative**. It means that we can set a ration for it.
Let's look at our previous example to fully understand the sense of **em**. We will change **font-size** of **.element1** and **.element2** to **2em**.
```
.element1 {
font-size: 2em;
}
.element2 {
font-size: 2em;
}
```
The result:

What do we see? The size of the text 'Habr Reader!' is **2 times more** than 'Hello'.
**It means that em sets the size by looking at the size of the parent element.**
For example, we set to .element1 **font-size: 20px** and to .element2 — **2em**. If we convert 2em to px, how many pixels will be the value of the .element2?
**The answer**Congratulations if you answered **40px**!
Let's give a conclusion for the **em** unit. **em** asks the question: **How many times I bigger or less than the value of my parent element?**
### rem
---
It is easier to understand the sense of **rem** by comparing it with **em**.
**rem** asks the question: **How many times I bigger or less than the value of ?**
For example, if we set:
```
html {
font-size: 20px;
}
```
And for two elements:
```
.element1 {
font-size: 2rem;
}
.element2 {
font-size: 2rem;
}
```
The Result:

Let's convert the size of .element1 and .element2 to pixels.
**The answer**The answer is **40px**. I seem it was easy for you.
### percent
---
**%** is a another **relative** unit. But this is more **unpredictable** than **em** and **rem**. Why? Because it has a lot of side cases.
In the majority of cases, **%** takes ratio from the parent element like **em**. It works for the width, height or font-size properties. If we look at our example it will work like an example with **em**.
```
.element1 {
font-size: 20px;
}
.element2 {
font-size: 200%;
}
```
The result:

Let's conve… No, no. I'm just kidding. I'm sure you can calculate the simple ratio with percent.
**If not check it**The answer is still **40px**.
Let's look at some other cases with **%**. For the property **margin**, it takes the width of the parent element; for the **line-height** — from the current font-size. In such cases, it is better and more rational to use **em** instead.
### vw and vh
---
* **1vw** means **1% of the screen width**.
* **1vh** means **1% of the screen height**.
These units are usually used for mobile platform support.
The simple example is the block below.
```
background-color: red;
width: 50vw;
height: 5vh;
```
Check the example [**here**](https://codepen.io/Filanovich/pen/zYGPjpP).
Even if you resize the screen the block always will contain 50% of the screen width and height.
### Rarely used units
---
* **1mm** = 3.8px
* **1cm** = 38px
* **1in** (inch) = 96px
* **1pt** (Typographic point) = 4/3px ~ 1.33px
* **1pc** (typographic peak) = 16px
* **1vmin** = the lowest value from vh and vm
* **1vmax** = the highest value from vh and vm
* **1ex** = exactly the height of a lowercase letter “x”
* **1ch** = the advance measure of the character ‘0’ in a font
The Full Summary Table
======================
| Unit | Unit Type | The Parent for which the Ratio is set | Example |
| --- | --- | --- | --- |
| [px](#px) | absolute | - | |
| [em](#em) | relative | the First Parent element | |
| [rem](#rem) | relative | | |
| [%](#percent) | relative | the First Parent element \*([look at the exceptions](#percent)) | |
| [vw and vh](#vw-and-vh) | relative | the screen width and height | [CodePen](https://codepen.io/Filanovich/pen/zYGPjpP) |
Conclusion
----------
Today we discussed a lot of useful size units that can relieve your development process.
If this article was useful to you and gave you new knowledge about CSS I would be great to see **likes** or **comments** below with **feedback**.
I’ll also be glad to read some **proposals** for my articles.
My social networks
------------------
* [Twitter](https://twitter.com/8Z64Su3u8Rfe7gf)
* [Medium](https://medium.com/@maxim_filanovich)
* [GitHub](https://github.com/M-fil)
* [Telegram](https://t.me/Filan0vichMaxim)
* [VK](https://vk.com/id327021520) | https://habr.com/ru/post/491516/ | null | null | 1,104 | 68.26 |
Hello!,
Message Search
Read more Post by marco calderon 18 June 2018
Last answer 4 days ago
What would be the best way to count all Interface messages on some Business Services and Operations in Ensemble?
Read more Post by Dmitry Vaysbeyn 7 August 2017
Last answer 8 August 2017 Last comment 29 May 2018
Hello all,
Read more Post by Aron Trujillo 17 May 2018
Last comment 17 May 2018
I'm trying to get a count of specific message type with a specific entry and thought I could build the query in Message Viewer but this does not provide counts (as far as I am aware).
Read more Post by Ewan Whyte 21 February 2018
Last answer 7 March 2018
I have made a complete copy of our test namespace into a secondary test namespace. Thereby we can test with our current EHR version and our soon to be deployed EHR version simultaneously. However, we have a nu
Read more Post by Brian Porterfield 27 December 2017
Last answer 27 December 2017 Last comment 27 December 2017
I searched fror "documenting classes" from the search button with no filtering. it naturally came back with 559 responses, but to me, the responses (and therefore the search) came without context.
Read more Post by Kevin Furze 15 November 2017
Last answer 15 November 2017 Last comment 15 November 2017
suggestions to try to make the searching of the community better, more relevent
Read more Post by Kevin Furze 31 July 2017
Last answer 8 August 2017 Last comment 1 August 2017
Hi,
I've built a custom HL7 searchtable, but wish to remove some of the items.
Read more Post by Stuart Byrne 4 May 2017
Last answer 8 June 2017
Hey all! I'd like to collect some feedback regarding searching for messages using the Message Viewer.
Read more Post by Julian Samaroo 27 March 2017
Last answer 2 May 2017 Last comment 1 May 2017
Ensemble 2014.1.5
Inbound EnsLib.HTTP.GenericMessage
Read more Post by Don Rozwick 22 March 2017
Last answer 22 March 2017
We have an incoming ADT adapter and the ACK MODE is set to IMMEDIATE. This is what the docs say:
Read more Post by Scott Beeson 18 August 2016
Last answer 19 August 2016 Last comment 19 August 2016
Hello guys,
Read more Post by Murillo Braga 3 August 2016
Last answer 3 August 2016 Last comment 3 August 2016
I want to query the cache database for messages where a specific HL7 segment equals a specific value. Does Cache have a pipe to XML or hl7 segment query function?
Read more Post by Paul Riker 18 July 2016
Last answer 19 July 2016
Have you ever needed to find a record for a particular person in your inbound data stream?
Searching messages will enable you to find messages using an array of search capabilities.
Read more Post by Janine Perkins 15 March 2016
Last comment 17 March 2016 | https://community.intersystems.com/tags/message-search | CC-MAIN-2018-30 | refinedweb | 498 | 59.06 |
A Java class file is consist of 10 basic sections:
-.)
You can remember the 10 sections with some funny mnemonic: My Very Cute Animal Turns Savage In Full Moon Areas. number
Magic number is used to uniquely identify the format and to distinguish it from other formats. The first four bytes of the Class file are 0xCAFEBABE.
.”
Version of Class file
The next four byte of the class file contains major and minor version numbers. This number allows the JVM to verify and identify the class file. If the number is greater than what JVM can load, the class file will be rejected with error
java.lang.UnsupportedClassVersionError.
You can find class version of any Java class file using
javap command line utility. For example:
javap -verbose MyClass
Consider we have a sample Java class:
public class Main { public static void main(String [] args) { int my_integer = 0xFEEDED; } }
We compile this class using
javac Main.java command and create class file. Now execute following command to see the major and minor version of class file.
C:\>javap -verbose Main Compiled from "Main.java" public class Main extends java.lang.Object SourceFile: "Main.java" minor version: 0 major version: 50 ...
Below is the list of Major versions and corresponding JDK version of class file..
You can analyse the Constant Pool of any class file using
javap command. Executing javap on above Main class, we get following symbol table.
C:\>javap -verbose Main Compiled from "Main.java" public class Main extends java.lang.Object SourceFile: "Main.java" minor version: 0 major version: 50 Constant pool: const #1 = Method #4.#13; // java/lang/Object."<init>":()V const #2 = int 16707053; const #3 = class #14; // Main const #4 = class #15; // java/lang/Object const #5 = Asciz <init>; const #6 = Asciz ()V; const #7 = Asciz Code; const #8 = Asciz LineNumberTable; const #9 = Asciz main; const #10 = Asciz ([Ljava/lang/String;)V; const #11 = Asciz SourceFile; const #12 = Asciz Main.java; const #13 = NameAndType #5:#6;// "<init>":()V const #14 = Asciz Main; const #15 = Asciz java/lang/Object;
The constant pool has 15 entries in total. Entry #1 is Method
public static void main; #2 is for integer value 0xFEEDED (decimal 16707053). Also we have two entries #3 and #4 which corresponds to
this class and
super class. Rest is the symbol table storing string literals.
Access flags
Access flags follows the Constant Pool. It is a two byte entry that indicates whether the file defines a class or an interface, whether it is public or abstract or final in case it is a class. Below is a list of some of the access flags and their interpretation.
this Class
This Class is a two byte entry that points to an index in Constant Pool. In above diagram, this class has a value 0xx.
Hi Viral,
I found that there are two type of statements that involve in branching – flow control instructions and the switch instructions (table switch and lookup switch).
I am able to decompile most of the bytecode except in detecting loops. What are the rules to detect loops in the code attribute instructions for a method? I tried to identify by patterns but gave up. Every compiler can generate it’s code in different ways.
Any pointers would also be very helpful… Also, is it very math intensive?
Thanks,
Keshavan
Hi
Could some one please tell me how to get the goto branch address in java bytecode
Thanks
thx for this tutorial..
I have read some article about Java class file format. This is the only one taught me what Java class file format is . Thank you very much.
its really interesting and understandable. i really like the simple way u explained! thumbs up :)
Really hats off…..Excellent and really helpful tech notes….
really mind blowing for ur explanation it helped me a lot………. thank u
HATS OFF VIRAL!
Fantastic article. Never knew so many things about class file.
Excellent articles (both of the articles)
You have explained such a complicated thing in such an easy way. Fantastic Job.
Thanks and Best Wishes
Shahab
Very very helpful. Complicated topics in an easily understood format. thanks and best wishes.
I have some doubts.
how jvm interprets obfuscated byte codes?.
it help me a lot,thanks. | https://viralpatel.net/blogs/tutorial-java-class-file-format-revealed/ | CC-MAIN-2018-43 | refinedweb | 710 | 67.65 |
Login Form
Login Form I have 8 jsp pages.Each of them has three columns:Left... of +,on clicking which a login form appears.
Only the middle column is different for each of the page.
How to write a code for login authentication so
bank details - JSP-Servlet
bank details hi i just need a coding for bank details...
since iam... is first to set the user account details in database, and the to create a login page in which both the user and admin can login..in that admin can change any
login form - JSP-Servlet
login form Q no.1:- Creat a login form in servlets? Hi...*;
import javax.servlet.http.*;
public class Login extends HttpServlet...();
pw.println("");
pw.println("Login");
pw.println("");
pw.println
login how to create login page in jsp
Here is a jsp code that creates the login page and check whether the user is valid or not.
1)login.jsp:
<html>
<form name="form" method="post" action="check.jsp">
login form validation - JSP-Servlet
login form validation hi,
how to validate the login form that contains user name and password
using post method .
the validation should not allow user to login in the address bar
thanks
regards,
anand
Login form
Login Form with jsp
Now for your confidence with JSP syntax, following example of login
form will really help to understand jsp page. In this example we
Simple Bank Application in JSP
Simple Bank Application in JSP
In this section, we have developed a simple bank application
in jsp . In this application user can Update the User Profile, Cash
Spring alternative to Form Based Login
Spring alternative to Form Based Login print("code sample");how can we make a server to listen to login event i.e. Authenticate a user not using jsp. Using a login form we can use the jspringsecurity_check. How can we do in jsp
login in jsp i need code for login which is verify the registeration form username and password field,if it correct user enter the next and otherwise show the failed message.
JSP Login Form
1)login.jsp:
<html>
Login Form
Login Form
Login form in struts: Whenever you goes to access data from... for a
login form using struts.
UserLoginAction Class: When you download Login
login-password - Java Beginners
login-password complete code of login-password form then how to connect the bank simulation project?
Hi friend,
}
Login Application in JSP
Struts 2.1.8 Login Form
Struts 2.1.8 Login Form
... to
validate the login form using Struts 2 validator framework.
About the example:
This example will display the login form to the user. If user enters Login
Name
login form
login form sir my next form consists logout button when i click on it it showing login form but next form window is not closing but the components...()
{
setTitle("Login Form");
setLayout(null);
label1 = new JLabel
login form
login form sir my next form consists logout button when i click on it it showing login form but next form window is not closing but the components...;
LoginDemo()
{
setTitle("Login Form");
setLayout(null);
label1 = new
validate bank account number
validate bank account number how to validate bank account number in jsp
Login Form using Ajax
Login Form using Ajax
This section provides you an easy and complete
implementation of login form...;/action>
Develop a Login Form Using Ajax : The GUI of the
application
simple bank application - JSP-Servlet
simple bank application hi i got ur codings...But if we register a new user it is not updating in the database...so plz snd me the database also....
Thank you
JSP Login Page Question
JSP Login Page Question hey..i have a login page where different users first registered and then after they can login.
my question is how a user can see only his data after login where different users data are stored
Login form and registration
Login form and registration I need a complete code for ligin and new user registration form and validation
administrator login form
administrator login form Hi iam using struts frame work backend as oracle .i want code for administrator login form thanks in advance
Spring login form application
Spring login form application Hi Please give me the Spring login form application so that i can understand its flow ?
Hi please find the link of the tutorial
Spring Applications
login hello i need some help please help how can identify admin from user when logging in? please make some answer and some explanation...
Please visit the following link;
Database driven login form - Java Server Faces Questions
is code that;
will create a database driven login form where users are authenticated...Database driven login form Dear sir,madam,
Greetings!!
well, am...://
Thanks
Login form in jscript
Login form in jscript For example the html script is
<...; charset=utf-8" />
<title>:: validation form::</title>
<script...;td
<form name="form1" onsubmit
Bank
standart login form for messenger in java
standart login form for messenger in java hi
i need login from for chating messenger in java.
but its structure would like this
Home Register Login
User ID
Hi Friend - Java Beginners
login page I have one login page in jsp that is login.jsp.
Now i have validate user from database by another page validate.jsp.
but if the user...://
Form handling
Form handling I created a spring project. I created a jsp with the following code
<%@ include file="/WEB-INF/jsp/include.jsp"%>
<form:form
<
JSP - Login
JSP - Login how to disabled back button of the browser when user successfully logged
html login page with ajax
html login page with ajax hi all... i want to create a login page......
thanks in advance
Here is a jsp example that accepts username...);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded
JSP Login Form with MySQL Database Connection and back end validation
to create JSP Login form backed with
MySQL database:
The following image...Here we have created a simple login form using MySQL Database Connection... database and matched with the
input value given through the login form.
Example
JDbc Login Authentication
JDbc Login Authentication Pease Please.. Send Me one Login Authentication Using ComboBox.From Servlet and jsp with sessions
I am new to sessions Please Help Me...
Index.jsp
<form action="Clas.java" Method="post">
admin login control page - JSP-Servlet
admin login control page how to encrypted password by using jsp... adminPage.jsp? JSP Example code for encrypted passwordJSP Encrypted...>Admin login Page</H1> <form method="POST" action
JSP Login Logout Example
JSP Login Logout Example
In this section we will discuss how to create... interface i.e. login
form.
Example
I am giving here a simple login logout... Login form backed with MySQL database.
Database Table
userdetail
CREATE
login form using java bean in eclipse
login form using java bean in eclipse I have made a college community website but i need to implement beans to my login and contact us page.
how can i do
jsp form
jsp form hi sir,
one got one got in jsp form after entering the data into the form the data is not saving in the database i will send you code of two forms if dnt understand my problem
how to login form through spring dao module
how to login form through spring dao module here i want to chek user details in database through form by using spring dao module.please give me some reference example to me
jsp login page
jsp login page hi tell me how to create a login page using jsp and servlet and not using bean... please tell how to create a database in sql server... please tell with code
getting error in your login form code
getting error in your login form code i tried your code for login form but i am getting an error.the error is undefined index userid...
hi friend,
your form's input must have following :
<input type
Spring 4 MVC Login form Example with source code
Spring 4 MVC Login form Example: Learn how to make a Login form in Spring
MVC... you the code for creating the Login
form in Spring MVC. You can validate... project
Creating form class
Creating the controller class
Writing JSP
jsp
jsp how to write a servlet and jsp program for user login form application
login application how to create login application ?
Hi,
Please check the following tutorials:
Video tutorial - JSP Login Logout Example
Login Authentication using Bean and Servlet In JSP
simple code to login user
PHP MySQL Login Form
Login Form using PHP and MySQL:
In any website generally it is mandatory to have a login form to keep your
data secure. In this regard we need to have... will study how to create a login form,
connect with the database server and login
Spring MVC Login Example
page</h3>
<br/>
<form:form
commandName... directory
for validate the login form. DispatcherServlet gives a property... click on this hyperlink the application display user login form like:
Now input
Login authentication & mysql - Java Beginners
Login authentication & mysql Hi ,
Could you guide or provide... login
I need to create a user account which is the user can register...), then use it to login.
When login, the user must be a valid user, means
Login & Registration - JSP-Servlet
Login & Registration Pls tell how can create login and registration step by step in servlet.
how can show user data in servlet and how can add...://
Hope that the above links will be helpful page
login page pls say how to create a login page in jsp and mysql using netbaens
Hi Friend,
Please visit the following links:
HTTP Status 404 - /Login/userdetail.java
HTTP Status 404 - /Login/userdetail.java I using netbeans to coonect...=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form name="f1" action="userdetail.java" method="get
jsp/servlet login program
jsp/servlet login program <%@ page language="Java" import...;/TITLE></HEAD>
<BODY>
<jsp:useBean
<jsp:setProperty name="db" property="userName" value
swing login code
swing login code code for the login form
PROBLEM IN FORM VALIDTION
PROBLEM IN FORM VALIDTION i applied validation IN THIS JSP PAGE.if i... enter Login Name." );
document.loginform.userName.focus();
return false...;
}
</script>
</head>
<body>
<form name="form" method="post
jsp login code ... when username , drop down box and password is correct
jsp login code ... when username , drop down box and password is correct i need a jsp code for login.... when username password and dropdown box... false;
}
return true;
}
</script>
<form name="form" method="post" action
Login Form in SWT
Login Form in SWT
This section illustrates you how to create Login Form.
To create a login... GridLayout(2, false)) sets the layout of
the login form. The method setTextLimit(30
How To Develop Login Form In Struts
How To Develop Login Form In Struts
....
This
article will explain how to develop login form in struts. Struts adopts an
MVC architecture.
Model
Part of Login form Example:
Model
Login Project
Login Project why should get the following compile error
LoginForm log=(LoginForm)form.
this will get when compile LoginAction class please give...
{
public ActionForward execute(ActionMapping mapping,
ActionForm form...;/body>
<html>
Output:
Login Authentication form :
After
Login/Logout With Session
;}
}
Download this code.
Develop Login Form: The GUI of the application
consists of login form (Login.jsp). The "Login.jsp"...Login/Logout With Session
login and logout
login and logout >
>
> > hi,
> > I have created two pages, one is home.jsp and another is welcome.jsp. In my home.jsp code i
> created a login form and after submitting
Struts 2 Login Form Example
Struts 2 Login Form Example tutorial - Learn how to develop Login form... you can create Login form in
Struts 2 and validate the login action....
Let's start developing the Struts 2 Login Form Example
Step
multiple form with multiple function in 1 jsp - JSP-Servlet
multiple form with multiple function in 1 jsp Hi, I'm using Netbean... in triggering my jsp with 2 forms as 1 for registration and 1 for log in. I need to trigger each form to call several function when user click buttons of these forms
login page
login page hi i'm trying to create login page using jsp. i get.../html" pageEncoding="UTF-8"%>
JSP Page
<h1>Login Example!</h1>
USER NAME <input name="uname | http://www.roseindia.net/tutorialhelp/comment/100091 | CC-MAIN-2014-35 | refinedweb | 2,062 | 54.73 |
17 April 2012 15:14 [Source: ICIS news]
TORONTO (ICIS)--Canadian chemical sales fell 2.5% in February from January, to Canadian dollar (C$) $4.0bn ($4.0bn), reflecting lower volumes by a large number of producers, a statistics agency said on Tuesday.
Compared with February 2011, ?xml:namespace>
Meanwhile, sales in
Overall Canadian manufacturing sales fell 0.3% to C$49.1bn in February from January as a number of sectors - including motor vehicle assembly, vehicle parts, and food - recorded declines.
Compared with February 2011, Canadian manufacturing sales were up 6.3% year on year.
Manufacturing inventories rose 0.3% in February to C$65.8bn, the 16th gain in 17 months.
The inventory-to-sales ratio was 1.34 in February, up from 1.33 in January. The ratio measures the time, in months, that would be required to exhaust inventories if sales were to remain at their current level.
In related news, a rail industry trade group said last week that Canadian chemical railcar traffic in the period from 1 January to 7 April was down 12.9% year on year.
($1 = C$0.99) | http://www.icis.com/Articles/2012/04/17/9551180/canada-chemical-sales-fall-2.5-in-february-as-volumes-drop.html | CC-MAIN-2014-35 | refinedweb | 188 | 62.04 |
Issue #300
no word about django and flake8 in docs for dev setup
Description
There is no word about (1)django and (2)flake8 dependencies in docs [1]
(1) no django error:
There was an internal server error while trying to access the Pulp application.
One possible cause is that the database needs to be migrated to the latest
version. If this is the case, run pulp-manage-db and restart the services. More
information may be found in Apache's log.
and traceback in httpd logs:
mod_wsgi (pid=13152): Target WSGI script '/srv/pulp/webservices.wsgi' cannot be loaded as Python module.
mod_wsgi (pid=13152): Exception occurred processing WSGI script '/srv/pulp/webservices.wsgi'.
Traceback (most recent call last):
File "/srv/pulp/webservices.wsgi", line 16, in <module>
from pulp.server.webservices.application import wsgi_application
File "/home/fedora/pulp/server/pulp/server/webservices/application.py", line 39, in <module>
from pulp.server.webservices.middleware.exception import ExceptionHandlerMiddleware
File "/home/fedora/pulp/server/pulp/server/webservices/middleware/exception.py", line 20, in <module>
from django.http import HttpResponse, HttpResponseServerError
ImportError: No module named django.http
(2) no flake8:
./run-tests.py
Running flake8
Traceback (most recent call last):
File "./run-tests.py", line 69, in <module>
flake8_paths=paths_to_check)
File "/home/fedora/pulp/devel/pulp/devel/test_runner.py", line 78, in run_tests
flake8_exit_code = subprocess.call(flake8_command)27, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
[1]
History
#1
Updated by ipanova@redhat.com over 6 years ago
- Triaged changed from No to Yes
- Severity set to Low
#2
Updated by amacdona@redhat.com over 6 years ago
- Status changed from NEW to ASSIGNED
- Assignee set to amacdona@redhat.com
#3
Updated by amacdona@redhat.com over 6 years ago
- Status changed from ASSIGNED to POST
I can confirm that Django is a requirement for more than just devs. The lack of Django was a bug which has been fixed:
Flake8 is a new dep for developers, so I have added it to the docs and the dev-setup script.
#4
Updated by amacdona@redhat.com over 6 years ago
- Status changed from POST to MODIFIED
#5
Updated by bmbouter over 6 years ago
- Category deleted (
1)
- Tags Documentation added
Documentation is now a Tag not a Category.
#6
Updated by bmbouter over 6 years ago
- Severity changed from Low to 1. Low
#7
Updated by dkliban@redhat.com over 6 years ago
- Platform Release set to 2.7.0
#8
Updated by dkliban@redhat.com over 6 years ago
- Status changed from MODIFIED to 5
#9
Updated by igulina@redhat.com over 6 years ago
- File Screenshot from 2015-06-17 14_41_49.jpg Screenshot from 2015-06-17 14_41_49.jpg added
- Status changed from 5 to ASSIGNED
Please correct docs. See a pic attached.
#10
Updated by amacdona@redhat.com over 6 years ago
The sphinx syntax error that caused this issue has been fixed in other changes and works in 2.7-testing and forward.
This has been realigned to 2.7-testing, and those docs are not built anywhere so to verify, you will have to build the docs locally.
#11
Updated by amacdona@redhat.com over 6 years ago
- Status changed from ASSIGNED to 5
#12
Updated by igulina@redhat.com over 6 years ago
Does it also implies to this sphinx syntax error?
#13
Updated by amacdona@redhat.com over 6 years ago
Yes, that was fixed by a different PR. You will have to build the docs to verify.
#14
Updated by igulina@redhat.com over 6 years ago
- Status changed from 5 to 6
#15
Updated by amacdona@redhat.com almost 6 years ago
- Status changed from 6 to CLOSED - CURRENTRELEASE
#17
Updated by bmbouter over 2 years ago
- Tags Pulp 2 added
Please register to edit this issue
Also available in: Atom PDF | https://pulp.plan.io/issues/300 | CC-MAIN-2021-43 | refinedweb | 643 | 60.21 |
On Wed, Jul 21, 2010 at 7:12 PM, Terry Reedy <tjreedy at udel.edu> wrote: > On 7/21/2010 7:20 AM, Nick Coghlan wrote: > >> yield and return (at the level of the given clause itself) will need >> to be disallowed explicitly by the compiler > > Why introduce an inconsistency? > > If > > a = e1 > b = f(a) > > can be flipped to > > b = f(a) given: > a = e1 > > I would expect > > a = e1 > return f(a) > > to be flippable to > > return f(a) given > a = e1 I believe Nick meant returns/yields *within* the `given` suite (he just phrased it awkwardly), e.g. a = b given: b = 42 return c # WTF The PEP's Syntax Change section explicitly changes the grammar to allow the sort of `given`s you're talking about. Cheers, Chris | https://mail.python.org/pipermail/python-ideas/2010-July/007675.html | CC-MAIN-2021-49 | refinedweb | 132 | 58.45 |
Hi: If I understand you correctly, the first property will defin itely not work. There are two reasons for that: 1. The identity t==t_i will almost never be fulfilled because the integration routine adapts the values where f is called according to your problem and accuracy requirements. Even if it would take t_i theoretically, equality is very unlikely to be fulfilled because of possible rounding errors. In short: Never check floating point numbers for equatlity! 2. Changing state variables leads to a discontinuity in the right hand side of your problem. This will lead to a breakdown of the control structures. Most common, you will obtain stepsize underflow near t_i. You must give the code a chance to reinitialize. This is only possible with the second approach. HTH Michael Am Mittwoch 11 September 2002 22:09 schrieb Marco Antoniotti: > Hi > > I am using the LSODE solver for my research and now need to do the > following. > > At a time t_i, I need to change the value of one (or more) of the > variable(s) involved. > > I think I understand I have two avenues to follow to achieve this > goal, but, given my inexperience with Octave (and/or Matlab) I don't > know which is the best one. > > 1 - I could insert a specific test in the derivative function > > function xdot = f(x, t) > xdot = zeros(rows(x), 1); > > if (t == t_i) > ## set x(k) to M > endif > > xdot(1) = ... > ... > xdot(n) = ... > > endfunction > > > 2 - I could break down the integration into intervals and set the > variable value between integrations. > > I'd like some comments about what would be the "best" (for an > approrpiate definition of "best") way to achieve this goal. > > Thanks -- +---------------------------------------------------------------+ | Michael Hanke Royal Institute of Technology | | NADA | | S-10044 Stockholm | | Sweden | +---------------------------------------------------------------+ | Visiting address: Lindstedtsvaegen 3 | | Phone: + (46) (8) 790 6278 | | Fax: + (46) (8) 790 0930 | | Email: address@hidden | | address@hidden | +---------------------------------------------------------------+ ------------------------------------------------------------- Octave is freely available under the terms of the GNU GPL. Octave's home on the web: How to fund new projects: Subscription information: ------------------------------------------------------------- | http://lists.gnu.org/archive/html/help-octave/2002-09/msg00066.html | CC-MAIN-2018-47 | refinedweb | 336 | 61.87 |
Issue
I am using python and plotly to product interactive html report. This post gives a nice framework.
If I produce the plot(via plotly) online, and insert the url into the html file, it works but refreshing the charts takes a long time. I wonder if I could produce the chart offline and have it embedded in the html report, so that loading speed is not a problem.
I find plot offline would generate a html for the chart, but I don’t know how to embed it in another html. Anyone could help?
Solution
Option 1: Use plotly’s offline functionality in your Jupyter Notebook (I suppose you are using a Jupyter Notebook from the link you are providing). You can simply save the whole notebook as a HTML file. When I do this, the only external reference is to JQuery; plotly.js will be inlined in the HTML source.
Option 2: The best way is probably to code directly against plotly’s JavaScript library. Documentation for this can be found here:
Update: Calling an internal function has never been a good idea. I recommend to use the approach given by @Fermin Silva. In newer versions, there now is also a dedicated function for this:
plotly.io.to_html (see)
Hacky Option 3 (original version for reference only): If you really want to continue using Python, you can use some hack to extract the HTML it generates. You need some recent version of plotly (I tested it with
plotly.__version__ == '1.9.6'). Now, you can use an internal function to get the generated HTML:
from plotly.offline.offline import _plot_html data_or_figure = [{"x": [1, 2, 3], "y": [3, 1, 6]}] plot_html, plotdivid, width, height = _plot_html( data_or_figure, False, "", True, '100%', 525) print(plot_html)
You can simply paste the output somewhere in the body of your HTML document. Just make sure that you include a reference to plotly in the head:
<script src=""></script>
Alternatively, you can also reference the exact plotly version you used to generate the HTML or inline the JavaScript source (which removes any external dependencies; be aware of the legal aspects however).
You end up with some HTML code like this:
<html> <head> <script src=""></script> </head> <body> <!-- Output from the Python script above: --> <div id="7979e646-13e6-4f44-8d32-d8effc3816df" style="height: 525; width: 100%;" class="plotly-graph-div"></div><script type="text/javascript">window.PLOTLYENV=window.PLOTLYENV || {};window.PLOTLYENV.BASE_URL="";Plotly.newPlot("7979e646-13e6-4f44-8d32-d8effc3816df", [{"x": [1, 2, 3], "y": [3, 1, 6]}], {}, {"showLink": false, "linkText": ""})</script> </body> </html>
Note: The underscore at the beginning of the function’s name suggests that
_plot_html is not meant to be called from external code. So it is likely that this code will break with future versions of plotly.
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 | https://errorsfixing.com/python-save-plotly-plot-to-local-file-and-insert-into-html/ | CC-MAIN-2022-27 | refinedweb | 487 | 62.78 |
January 04, 2018 • ☕️ 3 min read
GraphQL is both a client-side query language, and a server-side runtime for fetching data from various sources.
A common misconception (at least one that I had) is that client-side GraphQL interacts with a GraphQL database, and magically brings back data. Similar to how you would use SQL to query a Postgres database.
This is not the case. GraphQL is not tied to any particular database or backend API. In fact, you can have several databases and external services working together to pull in a unified view of something (See example below).
Instead, what happens is that on the client-side, you query your GraphQL backend service using queries such as:
{ user { id name } }
and your GraphQL backend backend service would respond with JSON of the format:
{ "user": { "id": 1, "name": "Max" } }
Your GraphQL backend service (we’re using Node, running on Lambda in this example) would typically consist of a few files:
- graphql/ - - index.js // NodeJS/Lambda specific call to graphql() - - resolvers.js // This file contains the logic of how you fetch your data - - schema.graphql // This file tells GraphQL what format/types to expect the data in - - schema.js // This file imports the GraphQL schema and the resolvers, combining them into an executableSchema
The index.js file only really parses the lambda event, and sends the query off to GraphQL (Note, this example does NOT handle authentication):
import schema from './schema' exports.handler = function(event, context, callback) { const query = event.Requests[0].body.query const root = {} const context = {} const variables = {} graphql(schema, query, root, context, variables) .then(d => { callback(null, { statusCode: 200, headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(d), }) }) .catch(e => { callback({ statusCode: 500, body: 'WTF?', }) }) }
Since all requests for data from the client-side are now just going to this one
function, we only really need one endpoint -
/graphql/ or
/data/
This also saves you from having to document your hundreds of internal endpoints for particularly large projects, since everything is described in the schema file (assuming you name things clearly!)
Say you have a schema, like this:
scalar JSON type User { name: String! count: Int! somethingElse: Float! } type Query { user(id: Int!): [User], } schema { query: Query }
Your resolvers file could look similar to the file below:
import pg import aws-sdk/clients/DynamoDB as docClient resolvers: { Query: { user(root, args, context) { const { id } = args docClient.query( { TableName: 'users', Key: { ID: id, }, }, function(err, data) { return data.Items } ) }, }, User: { name(root, args, context) { pg.query('Select * from Users where id = ?', [123]).then(d => {//doStuff}) //OR fetch(context.upstream_url + '/thing/' + args.id).then(d => {//doStuff}) return root.name + '_thing' }, somethingElse(root) { return root.count + 0.002 }, },
In this example, we pull in the bulk of our User fields from the AWS DynamoDB
docClient.query call. We can then add extra fields like
name from external
sources (Postgres or an
upstream_url in this example). You can even hard code
values, as in the case of
somethingElse.
Stay tuned for part two of this article, where I’ll show you how to set up your own graphql server.
Discuss on Twitter • Edit on GitHub
Enjoyed this post? Receive the next one in your inbox! | https://maxrozen.com/2018/01/04/what-is-graphql/ | CC-MAIN-2019-13 | refinedweb | 534 | 65.12 |
Class Object
The Object class (base class) is the root parent of all java classes.
Multi level inheritance. The parent class at the highest level must be the Object class.
For example, if you want to set a parameter parameter for the test method, which class will be passed in if you are not sure about the parameter, what type will be set for the parameter of the test method?
public class Test{ public void test(Object obj){ ...... } public static void main(String[] args){ Test t = new Test(); Person p = new Person(); Student s = new Student(); t.test(p); t.test(s); t.test(new Kk()); } }
Main methods in Object class
public boolean equals(Object obj) -- object comparison (reference object)
public static void main(String[] args){ Person p = new Person(); Person e = new Person(); System.out.println(p.equal(e));//false, pointing to two different reference objects e = p; System.out.println(p.equal(e));//true
public int hashCode() -- get Hash code
Object obj = new Object(); System.out.println(obj.hasCode());//31168322,Hash
public String toString -- called when printing objects
Person p = new Person(); System.out.println(p.toString());//The memory address of the current reference object
Casting of objects
Basic type conversion:
1. Automatic type conversion: small to large (data type)
For example: long = 20; double D = 12.0f;
2. Cast: big to small (data type)
For example: float f =(float)12.0; int a = (int)1200L;
Casts on Java objects are called shapes:
The type conversion from child class to parent class can be done automatically;
The type conversion from the parent class to the child class must be implemented by modeling (cast type);
Illegal conversion between reference types without inheritance.
Example: the Student class is a subclass of the Person class.
Student s = new Student(); Person p = s; Person p = new Person(); Student s = (Student) p; String s = "hello"; Object obj = s; System.out.println(obj);//hello Object obj = "hello"; String s = (String) obj; System.out.println(s);//hello
Child class to parent class, upward transformation.
From parent class to child class, use instanceof to judge and transform downward.
public class Person(){ public void test(){ System.out.println("Person"); } } public class Student(){ public void getSchool(){ System.out.println("Student"); } } public class Test(){ public void method(Person e){ if(e instanceof Student){ Student s = (Student) e; s.getSchool(); } else{ e.test(); } }
==Operators and equals methods
== :
1. Basic type comparison value: true as long as the values of two variables are equal.
2. Reference type comparison reference (whether pointing to the same object or not): only when pointing to the same object, = = returns true.
Person p1 = new Person(); Person p2 = new Person(); System.out.println(p1 == p2);//false Person p1 = new Person(); Person p2 = p1; System.out.println(p1 == p2);//true
Note: when "= =" is used, the data types on both sides of the symbol must be compatible.
equals method
equals(): all classes inherit the Object and get the equals() method. It can also be overridden.
Only reference types can be compared. Their functions are the same as "= =" to compare whether they point to the same object.
Person p1 = new Person(); Person p2 = new Person(); System.out.println(p1.equals(p2));//false
Special case:
When using the equals() method for comparison, for the classes File, String, Date and wrapper class, it is to compare the type and content without considering whether the reference is the same object or not;
Reason: the equals() method of the Object class is overridden in these classes.
String s1 = new String("abc"); String s2 = new String("abc"); System.out.println(s1 == s2);//false System.out.println(s1.equals(s2));//true
Creating a String object
Wrapper class
For the eight basic definition of the corresponding reference type - wrapper class (wrapper class).
Most of the initials can be capitalized, special: int - integer, char - Character.
The basic data type is packaged as an instance of a wrapper class -- boxing.
//Implemented by the constructor of the wrapper class: int i = 500; Integer t = new Integer(i); //You can also construct wrapper class objects with string parameters Float f = new Float("4.56"); Long l = new Long("asdf");//NumberFormatException
Get the basic type variable of packing in the packing class object -- unpacking.
//Call the. * * Value() method of the wrapper class; Integer i = new Integer(112); int i0 = i.Value(); System.out.println(i0);//112
Automatic disassembly box
Integer i = new Integer(112); int i0 = i.intValue(); Integer i1 = 112;//Automatic boxing int i2 = i1;//Automatic dismantling boolean b = new Boolean("false");//Automatic dismantling Boolean b1 = true;//Automatic boxing
Main applications:
String to basic data type
int i = Integer.parseInt("123");
Convert basic data type to string
//Calling valueOf() method of string overload String f = String.valueOf(i); //Direct approach String in = 5 + "";
toString() method:
If the toString() method is not overridden, the memory address of the object is printed out, and m.toString() is equivalent to M.
Keyword static
public class Chinese{ //Class variables (static variables), which are not instantiated, are part of a class and can be shared by instantiated objects of this class static String country; //Instance variables, which can only be used after instantiation, are part of the instantiated object and cannot be shared String name; int age; } public class Test{ public static void main(String[] args){ Chinese.country = "China"; Chinese c = new Chinese(); c.name = "+++"; c.age = 123; } }
Design idea of class attribute and class method:
Analysis class properties do not change according to different objects. Set these properties as class properties.
Method is independent of the caller and is declared as a class method.
Tool classes usually use static methods.
Characteristics of modified members:
1. Load as class loads
2. Priority over object existence
3. Decorated member, shared by all objects
4. When the access permission is running, it can be called directly by the class without creating the object
this cannot be used inside a static method. | https://programmer.ink/think/2020.2.4-2.5-holiday-java-consolidation-review.html | CC-MAIN-2021-04 | refinedweb | 983 | 56.45 |
Data Science Skills and Business Problems
Discover what skills a data scientist benefits from learning and how the concept of a data scientist, and what businesses expect of them, has developed over time.
For years, business leaders and IT organizations have had a challenging relationship. On one hand, IT organizations struggle to keep up with rapidly changing technology, poor communication, talent gaps, and unforeseen challenges. While on the other hand, business leaders face project completion dates that seem to slide across the calendar, cost overruns, and an ever increasing appetite for technology to support and drive business.
Now, with the rise of "Data Scientists" we see the same dynamics play out--- but this time, the new "must have" tech project is people, not software or systems. The parallels are humorous and hopefully shed some light on the confusion that often arises between IT and Business.
Let's explore the development of business analytics and data science.
In 2011, McKinsey published Big Data: the next frontier for innovation, competition, and productivity and in that one report hundreds of companies put on their running shoes and joined the race for analytical talent. Although this was certainly not the first report on the subject, it served to illustrate the business value and potential opportunities that are available (and not just to technology companies).
After describing the opportunity, McKinsey highlighted their forecast that there would be a severe shortage of "Deep Analytical Talent" by 2018 and they outlined the type of professional that would be needed to implement big data initiatives.
More importantly, DJ Patil gave McKinsey's "Deep Analytical Talent" a name--- Data Scientists. Below is an excerpt from the article describing how the title came to be:
.
With title in hand, DJ Patil added some key characteristics to look for in a Data Scientist:.
For the executive looking for a "Deep Analytical Talent" this article was a welcome expansion to the job description. However, much like IT projects, it also increased the expectations for what a Data Scientist was suppose to be.
From there, the floodgates opened. Over the next few months and years, the job description expanded into what is often referred to as a "Unicorn" of skillsets.
Everyone had a few things to add. Below are just a few examples. (Sources: Drew Conway's Data Scientist Venn Diagram, Gartner, Drew Tierney's Multi-disciplinary Diagram)
With each iteration, Data Scientist began to look more and more like Unicorns and less like "Deep Analytical Talent".
Ironically, the expanded expectations of Data Scientists are a product of their own success. The ability to advise executives, understand deeply technical problems, communicate, (*INSERT ENDLESS LIST*), illustrates that business leaders see Data Scientists as a bridge that can finally align IT and Business in a much more permanent and productive manner.
Unfortunately, many technical focused professionals, see the obligation to develop business skills as a trivial and unneeded task. However, it doesn't have to be!
In an effort to bridge the gap between Business and IT, I expanded from simply looking at the Top 10 Data Analysis Tools for Business to developing a concise guide to get IT professionals and business leaders to structure the problem solving process (which can be challenging after spending a few hours data cleansing or coding) and ensure that both groups understand the strategic need for a project.
In some cases, simply structuring out the problem and working through the objectives can be enough to come to a quick and simple solution.
Essentially, this serves as a basic framework for working through business problems. Although it won't make you a strategy expert, it will help to advance the conversation, align your goals with the business, understand the expected return (which can help to prioritize between projects), or even speed up talking points for a meeting so that you can get back to the comfort of coding.
As you would expect, it flows from top to bottom. "Basics" serve as a reminder of the steps to consider with any problem. For instance, the first item "breakdown and segment" is a reminder that spans customer/ revenues/ products/ etc (ie: segment out your customer base, breakdown products by volume and profit margin, segment revenues by streams, etc).
From there, Finance, Marketing, and Operations are very simplified and loosely defined groupings that help to guide discussion. All of which leads down to the ultimate goal of any project--- the profits!
Here is a link to a downloadable PDF of the cheat sheet.
Original LinkedIn post here.
Alex Jones is a Graduate Student at U. Texas McCombs School of Business.
Related:
- Unicorn Data Scientists vs Data Science Teams
- New Poll: Data Science Skills – Individual vs Team Approach
- Top 10 Data Analysis Tools for Business | http://www.kdnuggets.com/2014/06/data-science-skills-business-problems.html | CC-MAIN-2017-17 | refinedweb | 791 | 50.57 |
Step 1: Install Node.js
The build pipeline you will be building is based in Node.js so you must ensure in the first instance that you have this installed. For instructions on how to install Node.js you can checkout the SO docs for that here
Step 2: Initialise your project as an node module
Open your project folder on the command line and use the following command:
npm init
For the purposes of this example you can feel free to take the defaults or if you'd like more info on what all this means you can check out this SO doc on setting up package configuration.
Step 3: Install necessary npm packages
Run the following command on the command line to install the packages necessary for this example:
npm install --save react react-dom
Then for the dev dependencies run this command:
npm install --save-dev babel-core babel-preset-react babel-preset-es2015 webpack babel-loader css-loader style-loader file-loader image-webpack-loader
Finally webpack and webpack-dev-server are things that are worth installing globally rather than as a dependency of your project, if you'd prefer to add it as a dependency then that will work to, I don't. Here is the command to run:
npm install --global webpack webpack-dev-server
Step 3: Add a .babelrc file to the root of your project
This will setup babel to use the presets you've just installed. Your .babelrc file should look like this:
{ "presets": ["react", "es2015"] }
Step 4: Setup project directory structure
Set yourself up a directory stucture that looks like the below in the root of your directory:
|- node_modules |- src/ |- components/ |- images/ |- styles/ |- index.html |- index.jsx |- .babelrc |- package.json
NOTE: The
node_modules,
.babelrc and
package.json should all have already been there from previous steps I just included them so you can see where they fit.
Step 5: Populate the project with the Hello World project files
This isn't really important to the process of building a pipeline so I'll just give you the code for these and you can copy paste them in:
src/components/HelloWorldComponent.jsx
import React, { Component } from 'react'; class HelloWorldComponent extends Component { constructor(props) { super(props); this.state = {name: 'Student'}; this.handleChange = this.handleChange.bind(this); } handleChange(e) { this.setState({name: e.target.value}); } render() { return ( <div> <div className="image-container"> <img src="./images/myImage.gif" /> </div> <div className="form"> <input type="text" onChange={this.handleChange} /> <div> My name is {this.state.name} and I'm a clever cloggs because I built a React build pipeline </div> </div> </div> ); } } export default HelloWorldComponent;
src/images/myImage.gif
Feel free to substitute this with any image you'd like it's simply there to prove the point that we can bundle up images as well. If you provide your own image and you name it something different then you'll have to update the
HelloWorldComponent.jsx to reflect your changes. Equally if you choose an image with a different file extension then you need to modify the
test property of the image loader in the webpack.config.js with appropriate regex to match your new file extension..
src/styles/styles.css
.form { margin: 25px; padding: 25px; border: 1px solid #ddd; background-color: #eaeaea; border-radius: 10px; } .form div { padding-top: 25px; } .image-container { display: flex; justify-content: center; }
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Learning to build a react pipeline</title> </head> <body> <div id="content"></div> <script src="app.js"></script> </body> </html>
index.jsx
import React from 'react'; import { render } from 'react-dom'; import HelloWorldComponent from './components/HelloWorldComponent.jsx'; require('./images/myImage.gif'); require('./styles/styles.css'); require('./index.html'); render(<HelloWorldComponent />, document.getElementById('content'));
Step 6: Create webpack configuration
Create a file called webpack.config.js in the root of your project and copy this code into it:
webpack.config.js
var path = require('path'); var config = { context: path.resolve(__dirname + '/src'), entry: './index.jsx', output: { filename: 'app.js', path: path.resolve(__dirname + '/dist'), }, devServer: { contentBase: path.join(__dirname + '/dist'), port: 3000, open: true, }, module: { loaders: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.css$/, loader: "style!css" }, { test: /\.gif$/, loaders: [ 'file?name=[path][name].[ext]', 'image-webpack', ] }, { test: /\.(html)$/, loader: "file?name=[path][name].[ext]" } ], }, }; module.exports = config;
Step 7: Create npm tasks for your pipeline
To do this you will need to add two properties to the scripts key of the JSON defined in the package.json file in the root of your project. Make your scripts key look like this:
"scripts": { "start": "webpack-dev-server", "build": "webpack", "test": "echo \"Error: no test specified\" && exit 1" },
The
test script will have already been there and you can choose whether to keep it or not, it's not important to this example.
Step 8: Use the pipeline
From the command line, if you are in the project root directory you should now be able to run the command:
npm run build
This will bundle up the little application you've built and place it in the
dist/ directory that it will create in the root of your project folder.
If you run the command:
npm start
Then the application you've built will be served up in your default web browser inside of a webpack dev server instance. | https://riptutorial.com/reactjs/example/21750/how-to-build-a-pipeline-for-a-customized--hello-world--with-images- | CC-MAIN-2021-49 | refinedweb | 896 | 55.95 |
LCM?
- Demonstration for LCM of two numbers
- How to find LCM......
Common multiple of 4 and 6 are 12, 24, 36....
The least common multiple is 12 so lcm(4,6)=12
What is LCM?
LCM is a smallest positive integer that exactly divides two or more numbers.
The LCM (Least Common Multiple or Lowest common multiple) of two integers is the smallest positive integer that is perfectly divisible by both numbers (without a remainder).
For example, the LCM of 72 and 120 is 360.
The Factor of 72 = 2*2*2*3*3
The Factor of 120 = 2*2*2*3*5
Then the least common factor of 72 and 120 is 2*2*2*3*3*5 = 360.
Other example,
The LCM of 12 and 64 is 360.
The Factors of 12 = 2*2*3
The Factors of 64 = 2*2*2*2*2*2
Then the least common Multiple of 72 and 120 is 2*2*2*2*2*2*3 = 192.
On the other hand the LCM of two integers a and b, usually denoted by lcm(a, b), is the smallest positive integer that is divisible by both a and b.
How to find LCM of two numbers?
- Step 1: Write the multipliers of both two numbers.
- Step 2: Take out the common as well as left factors.
- Step 3: Then to again multiply these common and left factors, which is the lcm of the given two numbers.
Demonstration for GCD of two numbers
C program to find lcm of two numbers
#include <stdio.h> int main() { int i, num1, num2, max, lcm=1; printf("Enter any two numbers to find LCM: "); scanf("%d", &num1); printf("Enter any two numbers to find LCM: "); scanf("%d", &num2); /* Find maximum between num1 and num2 */ max = (num1 > num2) ? num1 : num2; /* First multiple to be checked */ i = max; /* Run loop indefinitely till LCM is found */ while(1) { if(i%num1==0 && i%num2==0) { /*If 'i' divides both 'num1' and 'num2' * then 'i' is the LCM. */ lcm = i; /* Terminate the loop after LCM is found */ break; } /* * If LCM is not found then generate next multiple of max between both numbers */ i += max; } printf("LCM of %d and %d = %d", num1, num2, lcm); return 0; }
The output of the Program:
Conclusion:
This Program stores two integers one by one into the int datatype. After that find the least common multiple of these two numbers as shown as output. | https://www.onlineinterviewquestions.com/blog/c-program-to-find-lcm-of-two-numbers/ | CC-MAIN-2021-17 | refinedweb | 408 | 68.91 |
Testing with types
Type checking is something that is often taken for granted in statically typed languages. With type checking, type errors can be found at compile time, rather than during runtime. In some dynamic languages such as Clojure, type signatures can be declared wherever and whenever they are required, and this technique is termed as optional typing. Type checking can be done using the
core.typed library (). Using
core.typed, the type signature of a var can be checked using type annotations. Type annotations can be declared for any var, which includes values created using a
def form, a
binding form, or any other construct that creates a var. In this section, we will explore the details of this library. ...
Get Clojure: High Performance JVM Programming now with O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers. | https://www.oreilly.com/library/view/clojure-high-performance/9781787129597/ch25s04.html | CC-MAIN-2021-10 | refinedweb | 149 | 55.13 |
With Instructables you can share what you make with the world, and tap into an ever-growing community of creative experts.
Ever want to build your own RC vehicle? Now you can. Your in control of its design, and as simple to use a Legos, because it is Legos. ...
You will need: *standard NXT kit *computer with bluetooth *wiimote
This part is best explained visually. View pictures for guidance.
View pictures for guidance.
Plug left cable into port b. The picture is wrong.
Plug the right cable into port c. The picture is wrong.
download glovepie from: download the controller: After downloading extract the files.
use left and right keys until Bluetooth is centered.
Once you find the Bluetooth icon hit the orange button.
Use the right and left arrows to find On/Off
Select On if not already.
While in the Bluetooth menu find the visibility icon.
Select On if not already selected.
click on the orb or hit super on your keyboard.
Start the control panel.
double click the Bluetooth icon.
Select add device from the menu bar.
After clicking on add new device a window will open. Other devices than your brick may appear. Wait until your NXT brick is found to double click on ...
A window will open asking for the device's password.
Look at your brick. The default password is "1234." You can change the password if you want to. Once you know what password you want to use select ...
Enter pairing password from NXT.
Click connect and windows will install the drivers needed.
Wait until all the drivers have been installed and the brick has been successfully paired to move on.
Go back to the Bluetooth window. Your brick should now appear there. Select add new device.
Make sure your Wii is off. Either hold down both the 1 and 2 buttons or hit sync on the back of the controller.
After clicking on add new device a window will open. Other devices than the wiimote may appear. Wait until your wiimote is found to double click on it.
For the password option. Select pair without password.
The wiimote should pair with your computer and install drivers.
Go to the Bluetooth menu. Right click on your brick, select properties, then settings. After loading you will see which COM port the brick is using.
Double click on the controllers icon.
Enter the com port of the brick. Then click start.
Click enable keyboard in lower right corner of the program.
Double click on the glovepie icon.
Here is the program. Just copy and past if var.run == FALSE then var.run = TRUE HidePie var.hidden = TRUE endif if ((DoubleClicked(Wiimote.Home) and Wiimote.HasClassic == FALSE) or ...
hold wiimote with IR camera facing away from you and level. tilt wiimote down to go forward tilt wiimote backward to go backward tilt wiimote right to turn ...
Click run and enjoy. I am 17 and if I can do, so can you.
17 favorites
License:
Control a NXT Robot with Android and HTML5by wbeer
Lego quick and easy Spybotby michaelgohjs
Proof-of-concept Robot arm and controls (Lego nxt)by michaelgohjs
Movement and Speech Controlled Wifi Camera Bluetooth Carby searx
play lego star wars for PC with wiimoteby Pat the » | http://www.instructables.com/id/control-Lego-NXT-with-wiimote-via-bluetooth/step42/Bluetooth/ | CC-MAIN-2015-40 | refinedweb | 543 | 79.87 |
Last time I looked at implementing the Stack Data Structure in Python and C#. In this article I'll be implementing similar solutions in Python and C# using the Queue Data Structure. The Stack is a last-in, first-out data structure and the Queue is a first-in, first-out data structure.
Deque in Python
The collections module in Python has a lot of feature-rich containers, and one of them is
deque. It allows for fast appends and pops to both the left and right sides of the container, making it a great solution for both Stacks and Queues in Python. Here is an example in Python using
deque as a Queue.
from collections import deque queue = deque() queue.append(1) queue.append(2) queue.append(3) is_empty = len(queue) == 0 print(is_empty) # False print(queue.popleft()) # 1 print(queue.popleft()) # 2 print(queue.popleft()) # 3 is_empty = len(queue) == 0 print(is_empty) # True print(queue.popleft()) # IndexError: pop from an empty deque
Using Link List for Queue in Python
One can use a Link List as a Queue in Python. In order to make appends really fast I will add a tail pointer in addition to the normal head pointer. I can pop from the head of the Link List in O(1) with the head pointer, and append to the tail of the Link List in O(1) with the tail pointer.
class Node: def __init__(self, key): self.key = key self.next = None class Queue: def __init__(self): self.head = None self.tail = None def append(self, key): new_node = Node(key) # empty. add first node. if self.is_empty(): self.head = new_node self.tail = self.head return # not empty. add node to the tail. self.tail.next = new_node self.tail = new_node def pop(self): if self.is_empty(): raise IndexError('pop from an empty queue') key = self.head.key # if only 1 item in queue, otherwise... if self.head is self.tail: self.head = None self.tail = self.head else: self.head = self.head.next return key def is_empty(self): return self.head is None queue = Queue() queue.append(1) queue.append(2) queue.append(3) print(queue.is_empty()) # False print(queue.pop()) # 1 print(queue.pop()) # 2 print(queue.pop()) # 3 print(queue.is_empty()) # True print(queue.pop()) # IndexError: pop from an empty queue
Queue Class as Abstraction in Python
The custom
Queue Class used with the Link List abstracts away the details of using a Link List to handle Queue operations. In fact, it is easy to change the underlying implementation of using a Link List with
deque and preserve the operations of
pop,
append, and
is_empty. Let's do that to show that abstraction is a very useful concept in computer science. Here is the same
Queue class as above using
deque in place of a Link List.
from collections import deque class Queue: def __init__(self): self.__queue = deque() def append(self, key): self.__queue.append(key) def pop(self): return self.__queue.popleft() def is_empty(self): return len(self.__queue) == 0 queue = Queue() queue.append(1) queue.append(2) queue.append(3) print(queue.is_empty()) # False print(queue.pop()) # 1 print(queue.pop()) # 2 print(queue.pop()) # 3 print(queue.is_empty()) # True print(queue.pop()) # IndexError: pop from an empty dequeue
Using Array as Queue in C#
One can also use an Array as a Queue, but there is a fixed limit to the number of items that can be queued using an Array. I am talking about a fixed array and not a Dynamic Array.
Python does not have Arrays, so let's explore this concept in C#. Using an Array as a Queue will require a read index and a write index. The read index will point to the index in the Array for the next read. The write index will point to the index in the Array where the next value will be written. The Array can be thought of as a circular Queue, such that when the read and write index hit the end of the Array they can loop back to the beginning of the Array. When the read index is equal to the write index the Queue is empty. Note that we need an empty cell between the read index and the write index in order to differentiate between an empty Queue and a full Queue. Therefore when I initialize the Array, I tack on one extra cell for the differentiation.
Here is a rough example of using an Array as a Queue in C# to help one understand the concept.
public class Queue<T> { private readonly T[] _queue; private int _readIndex; private int _writeIndex; public Queue(int length = 20) { // Need empty cell to differentiate // between full and empty. _queue = new T[length + 1]; } public void Append(T key) { if (IsFull()) throw new IndexOutOfRangeException("append to full queue."); _queue[_writeIndex] = key; _writeIndex = (_writeIndex + 1)%_queue.Length; } public T Pop() { if (IsEmpty()) throw new IndexOutOfRangeException("pop from empty queue."); var key = _queue[_readIndex]; _readIndex = (_readIndex + 1)%_queue.Length; return key; } public bool IsEmpty() { return _readIndex == _writeIndex; } public bool IsFull() { return (_writeIndex + 1)%_queue.Length == _readIndex; } }
Here is a C# Script similar to the Python Scripts that show the Queue's API. Since the
Queue can be full in this case, I added an
IsFull Method.
var queue = new Queue<int>(3); queue.Append(1); queue.Append(2); queue.Append(3); Console.WriteLine(queue.IsEmpty()); // False Console.WriteLine(queue.IsFull()); // True Console.WriteLine(queue.Pop()); // 1 Console.WriteLine(queue.Pop()); // 2 Console.WriteLine(queue.Pop()); // 3 Console.WriteLine(queue.IsEmpty()); // True Console.WriteLine(queue.IsFull()); // False Console.WriteLine(queue.Pop()); // IndexError: pop from an empty queue
Queue Class in C# from System.Collections
There is a
Queue Class in
System.Collections and
Queue<T> Class in
System.Collections.Generic that provides a Queue Data Structure for your .NET Applications. Rather than using
append and
pop, it uses
enqueue and
dequeue to represent appending and removing items from the Queue.
var queue = new Queue<int>(3); queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); Console.WriteLine(queue.Count == 0); // False Console.WriteLine(queue.Dequeue()); // 1 Console.WriteLine(queue.Dequeue()); // 2 Console.WriteLine(queue.Dequeue()); // 3 Console.WriteLine(queue.Count == 0); // True Console.WriteLine(queue.Dequeue()); // IndexOperationException
Conclusion
Hopefully this helps explain different ways of implementing a Queue in Python and C#. There is no need to implement a Queue yourself using an Array or Link List. I just added these to help explain the concepts of how a Queue could be implemented under the covers. The
deque container in the collections module in Python and the
Queue and
Queue<T> Classes in
System.Collections and
System.Collections.Generic in C# are highly optimized solutions for implementing a Queue in your applications.
Best Wishes! | https://www.koderdojo.com/blog/queue-data-structure-in-python-and-csharp | CC-MAIN-2021-39 | refinedweb | 1,134 | 69.79 |
Code. Collaborate. Organize.
No Limits. Try it Today.
CCPUTicker
Features
This 200 MHz. The value returned is
a 64 bit integer so assuming your CPU runs at 200 MHZ, the value will take roughly
3000 years to roll over. As the value also starts counting from 0, the value returned
is the number of CPU ticks since the computer was turned on i.e. the "UP" time.
RDTSC
Because the timer is part of the CPU hardware, it is unaffected by processor activity
and workload. The class has only been tested on Intel CPU's. Feedback about its behavior
on other CPU types would be appreciated. The class can also be used on Windows NT without
any problems.
The class itself was developed originally by J.M.McGuiness
and continues to be co-developed by both authors.
The source zip file contains the CCPUTicker source code and also includes a
simple MFC message box based demonstration application which will time the accuracy of a
call to the SDK call Sleep(1000) and also report how long your machine has
been "Up".
Sleep(1000)
History
V1.0 (26 March 1996)
V1.1 (16 July 1997)
__int64
V1.2 (14 January 1999)
V1.21 (14 January 1999)
21 January 1999
27 January 1999
v1.22 (3 December 1999)
API Reference
The API is made of the following public methods of the CCPUTicker
class:
CCPUTicker()
operator=()
Measure()
GetTickCountAsSeconds()
GetTickCount()
GetCPUFrequency()
IsAvailable()
AssertValid()
Dump()
Parameters:
Remarks:
Standard constructor and copy constructor for the class which just
initialize some internal variables.
Return Value:
Usual reference to this from a C++ operator= function.
Remarks:
Standard operator= for the class.
Remarks:
Calling this function retrieves the current value of the RDTSC
counter into this CCPUTicker instance.
Return Value:
The current RDTSC counter value in seconds.
Remarks:
Calling this function retrieves the stored value of the RDTSC
counter from this instance as seconds. The number of seconds is the "Up" time of
the computer. Because the counter is stored in clock ticks, the first time this function
is called by any of your code, the processor clock frequency will be estimated using an
internal timing routine. Please note that this can appear to hang the current process for
up to 20 seconds when this is being performed. Please see the Usage
section below for important development notes regarding this function.
Return Value:
The current RDTSC counter value in clock ticks.
Remarks:
Calling this function retrieves the stored value of the RDTSC
counter from this instance as clock ticks. This function is a simple accessor on the value
which the class will have obtained on the last call to its Measure method.
Return Value:
TRUE if the CPU frequency was returned successfully, otherwise FALSE. Use
GetLastError() to determine the cause if this happens.
GetLastError()
Remarks:
This function will work out the processor clock frequency to a
specified accuracy determined by the target average deviation required. Note that the
worst average deviation of the result is less than 5MHz for a mean frequency of 90MHz. So
basically the target average deviation is supplied only if you want a more accurate
result, it won't let you get a worse one. (Units are Hz.). The average deviation is a
better and more robust measure than it's cousin the standard deviation of a quantity. The
item determined by each is essentially similar. See "Numerical Recipies",
W.Press et al for more details. This function will run for a maximum of 20 seconds by
default before giving up on trying to improve the average deviation, with the average
deviation actually achieved replacing the supplied target value. Use "max_loops"
to change this. To improve the value the function converges to increase
"interval" (which is in units of ms, default value=1000ms). Please see the Usage section below for important development notes regarding this
function.
Return value:
TRUE if this machine has the "RDTSC" instruction available for timing
otherwise FALSE.
Remarks:
Standard MFC diagnostic function.
Usage
The sample app is a simple MFC message box based demonstration which will time the
accuracy of a call to the SDK call Sleep(1000) and also report how long your
machine has been "Up".
To use CCPUTicker in your project simply include cputicker.cpp from
the test application in your application and #include "cputicker.h" in which ever
files you want to use the class.
#include "cputicker.h"
The following points should be born in mind when developing code with CCPUTicker:
Contacting the Author
PJ Naughter
Web: 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
timeGetTime()
timeBeginPeriod(1)
QueryPerformanceCounter()
QueryPerformanceFrequency()
PROCESSOR_POWER_INFORMATION
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/362/CCPUTicker-v1-22-Precision-Timing | CC-MAIN-2014-23 | refinedweb | 827 | 56.15 |
Create Tinder Style Swipe Cards with Ionic Gestures
By Josh Morony
I’ve been with my wife since around the time Tinder was created, so I’ve never had the experience of swiping left or right myself. For whatever reason, swiping caught on in a big way. The Tinder animated swipe card UI seems to have become extremely popular and something people want to implement in their own applications. Without looking too much into why this provides an effective user experience, it does seem to be a great format for prominently displaying relevant information and then having the user commit to making an instantaneous decision on what has been presented.
Creating this style of animation/gesture has always been possible in Ionic applications - you could use one of many libraries to help you, or you could have also implemented it from scratch yourself. However, now that Ionic is exposing their underlying gesture system for use by Ionic developers, it makes things significantly simpler. We have everything we need out of the box, without having to write complicated gesture tracking ourselves.
I recently released an overview of the new Gesture Controller in Ionic 5 which you can check out below:
If you are not already familiar with the way Ionic handles gestures within their components, I would recommend giving that video a watch before you complete this tutorial as it will give you a basic overview. In the video, we implement a kind of Tinder “style” gesture, but it is at a very basic level. This tutorial will aim to flesh that out a bit more, and create a more fully implemented Tinder swipe card component.
We will be using StencilJS to create this component, which means that it will be able to be exported and used as a web component with whatever framework you prefer (or if you are using StencilJS to build your Ionic application you could just build this component directly into your Ionic/StencilJS application). Although this tutorial will be written for StencilJS specifically, it should be reasonably straightforward to adapt it to other frameworks if you would prefer to build this directly in Angular, React, etc. Most of the underlying concepts will be the same, and I will try to explain the StencilJS specific stuff as we go.
NOTE: This tutorial was built using Ionic 5 which, at the time of writing this, is currently in beta..
A Brief Introduction to Ionic Gestures
As I mentioned above, it would be a good idea to watch the introduction video I did about Ionic Gesture, but I will give you a quick rundown here as well. If we are using
@ionic/core we can make the following imports:
import { Gesture, GestureConfig, createGesture } from '@ionic/core';
This provides us with the types for the
Gesture we create, and the
GestureConfig configuration options we will use to define the gesture, but most important is the
createGesture method which we can call to create our “gesture”. In StencilJS we use this directly, but if you are using Angular for example, you would instead use the
GestureController from the
@ionic/angular package which is basically just a light wrapper around the
createGesture method.
In short, the “gesture” we create with this method is basically mouse/touch movements and how we want to respond to them. In our case, we want the user to perform a swiping gesture. As the user swipes, we want the card to follow their swipe, and if they swipe far enough we want the card to fly off screen. To capture that behaviour and respond to it appropriately, we would define a gesture like this:
const options: GestureConfig = { el: this.hostElement, gestureName: 'tinder-swipe', onStart: () => { // do something as the gesture begins }, onMove: (ev) => { // do something in response to movement }, onEnd: (ev) => { // do something when the gesture ends } }; const gesture: Gesture = await createGesture(options); gesture.enable();
This is a bare-bones example of creating a gesture (there are additional configuration options that can be supplied). We pass the element we want to attach the gesture to through the
el property - this should be a reference to the native DOM node (e.g. something you would usually grab with a
querySelector or with
@ViewChild in Angular). In our case, we would pass in a reference to the card element that we want to attach this gesture to.
Then we have our three methods
onStart,
onMove, and
onEnd. The
onStart method will be triggered as soon as the user starts a gesture, the
onMove method will trigger every time there is a change (e.g. the user is dragging around on the screen), and the
onEnd method will trigger once the user releases the gesture (e.g. they let go of the mouse, or lift their finger off the screen). The data that is supplied to us through
ev can be used to determine a lot, like how far the user has moved from the origin point of the gesture, how fast they are moving, in what direction, and much more.
This allows us to capture the behaviour we want, and then we can run whatever logic we want in response to that. Once we have created the gesture, we just need to call
gesture.enable which will enable the gesture and start listening for interactions on the element it is associated with.
With this idea in mind, we are going to implement the following gesture/animation in Ionic:
1. Create the Component
You will need to create a new component, which you can do inside of a StencilJS application by running:
npm run generate
You may name the component however you wish, but I have called mine
app-tinder-card. The main thing to keep in mind is that component names must be hyphenated and generally you should prefix it with some unique identifier as Ionic does with all of their components, e.g.
<ion-some-component>.
2. Create the Card
We can apply the gesture we will create to any element, it doesn’t need to be a card or sorts. However, we are trying to replicate the Tinder style swipe card, so we will need to create some kind of card element. You could, if you wanted to, use the existing
<ion-card> element that Ionic provides. To make it so that this component is not dependent on Ionic, I will just create a basic card implementation that we will use. { render() { return ( <Host> <div class="header"> <img class="avatar" src="" /> </div> <div class="detail"> <h2>Josh Morony</h2> <p>Animator of the DOM</p> </div> </Host> ); } }
We have added a basic template for the card to our
render() method. For this tutorial, we will just be using non-customisable cards with the static content you see above. You may want to extend the functionality of this component to use slots or props so that you can inject dynamic/custom content into the card (e.g. have other names and images besides “Josh Morony”).
It is also worth noting that we have set up all of the imports we will be making use of:
import { Component, Host, Element, Event, EventEmitter, h } from '@stencil/core'; import { Gesture, GestureConfig, createGesture } from '@ionic/core';
We have our gesture imports, but as well as that we are importing
Element to allow us to get a reference to the host element (which we want to attach our gesture to). We are also importing
Event and
EventEmitter so that we can emit an event that can be listened for when the user swipes right or left. This would allow us to use our component in this manner:
<app-tinder-card onMatch={(ev) => {this.handleMatch(ev)}} />
So that our cards don’t look completely ugly, we are going to add a few styles as well.
Modify
src/components/tinder-card/tinder-card.cssto reflect the following:
app-tinder-card { display: block; width: 100%; min-height: 400px; border-radius: 10px; display: flex; flex-direction: column; box-shadow: 0 0 3px 0px #cecece; } .header { background-color: #36b3e7; border: 4px solid #fbfbfb; border-radius: 10px 10px 0 0; display: flex; justify-content: center; align-items: center; flex: 2; } .avatar { width: 200px; height: auto; } .detail { background-color: #fbfbfb; padding-left: 20px; border-radius: 0 0 10px 10px; flex: 1; }
3. Define the Gesture
Now we are getting into the core of what we are building. We will define our gesture and the behaviour that we want to trigger when that gesture happens. We will first add the code as a whole, and then we will focus on the interesting parts in detail. { @Element() hostElement: HTMLElement; @Event() match: EventEmitter; connectedCallback(){ this.initGesture(); } async initGesture(){ const style = this.hostElement.style; const windowWidth = window.innerWidth; const options: GestureConfig = { el: this.hostElement, gestureName: 'tinder-swipe', = '' } } }; const gesture: Gesture = await createGesture(options); gesture.enable(); } render() { return ( <Host> <div class="header"> <img class="avatar" src="" /> </div> <div class="detail"> <h2>Josh Morony</h2> <p>Animator of the DOM</p> </div> </Host> ); } }
At the beginning of this class, we have set up the following code:
@Element() hostElement: HTMLElement; @Event() match: EventEmitter; connectedCallback(){ this.initGesture(); }
The
@Element() decorator will provide us with a reference to the host element of this component. We also set up a
match event emitter using the
@Event() decorator which will allow us to listen for the
onMatch event to determine which direction a user swiped.
We have set up the
connectedCallback lifecycle hook to automatically trigger our
initGesture method which is what handles actually setting up the gesture. We have already discussed the basics of defining a gesture, so let’s focus on our specific implementation of the
onStart,
onMove, and
onEnd methods: = '' } }
Let’s being with the
onMove method. When the user swipes on the card, we want the card to follow the movement of that swipe. We could just detect the swipe and animate the card after the swipe has been detected, but this isn’t as interactive and won’t look as nice/smooth/intuitive. So, what we do is modify the
transform property of the elements style to modify the
translateX to match the
deltaX of the movement. The
deltaX is the distance the gesture has moved from the initial start point in the horizontal direction. The
translateX will move an element in a horizontal direction by the number of pixels we supply. If we set this
translateX to the
deltaX it will mean that the element will follow our finger, or mouse, or whatever we are using for input along the screen.
We also set the
rotate transform so that the card rotates in relation to a ratio of the horizontal movement - the further you get to the edge of the screen, the more the card will rotate. This is divided by
20 just to lessen the effect of the rotation - try setting this to a smaller number like
5 or even just use
ev.deltaX directly and you will see how ridiculous it looks.
The above gives us our basic swiping gesture, but we don’t want the card to just follow our input - we need it to do something after we let go. If the card isn’t near enough the edge of the screen it should snap back to its original position. If the card has been swiped far enough in one direction, it should fly off the screen in the direction it was swiped.
First, we set the
transition property to
0.3s ease-out so that when we reset the cards position back to
translateX(0) (if the card was no swiped far enough) it doesn’t just instantly pop back into place - instead, it will animate back smoothly. We also want the cards to animate off screen nicely, we don’t want them to just pop out of existence when the user lets go.
To determine what is “far enough”, we just check if the
deltaX is greater than half the window width, or less than half of the negative window width. If either of those conditions are satisfied, we set the appropriate
translateX such that the card goes off the screen. We also trigger the
emit method on our
EventListener so that we can detect the successful swipe when using our component. If the swipe was not “far enough” then we just reset the
transform property.
One more important thing we do is set
style.transition = "none"; in the
onStart method. The reason for this is that we only want the
translateX property to transition between values when the gesture has ended. There is no need to transition between values
onMove because these values are already very close together, and attempting to animate/transition between them with a static amount of time like
0.3s will create weird effects.
4. Use the Component
Our component is complete! Now we just need to use it, which is reasonably straight-forward with one caveat which I will get to in a moment. Using the component directly in your StencilJS application would look something like this:
import { Component, h } from '@stencil/core'; @Component({ tag: 'app-home', styleUrl: 'app-home.css' }) export class AppHome { handleMatch(ev){ if(ev.detail){ console.log("It's a match!") } else { console.log("Maybe next time"); } } render() { return [ <ion-header> <ion-toolbar <ion-title>Ionic Tinder Cards</ion-title> </ion-toolbar> </ion-header>, <ion-content <div class="tinder-container"> <app-tinder-card onMatch={(ev) => {this.handleMatch(ev)}} /> <app-tinder-card onMatch={(ev) => {this.handleMatch(ev)}} /> <app-tinder-card onMatch={(ev) => {this.handleMatch(ev)}} /> </div> </ion-content> ]; } }
We can mostly just drop our
app-tinder-card right in there, and then just hook up the
onMatch event to some handler function as we have done with the
handleMatch method above.
One thing we have not covered in this tutorial is handling a “stack” of cards, as these Tinder cards would usually be used in. What would likely be the nicer option is to create an additional
<app-tinder-card-stack> component, such that it could be used like this:
<app-tinder-card-stack> <app-tinder-card /> <app-tinder-card /> <app-tinder-card /> </app-tinder-card-stack>
and the styling for positioning the cards on top of one another would be handled automatically. However, for now, I have just added some manual styling directly in the page to position the cards directly:
.tinder-container { position: relative; } app-tinder-card { position: absolute; top: 0; left: 0; }
Which will give us something like this:
Summary
It’s pretty fantastic to be able to build what is a reasonably cool/complex looking animated gesture, all with what we are given out of the box with Ionic. The opportunities here are effectively endless, you could create any number of cool gestures/animations using the basic concept of listening for the start, movement, and end events of gestures. This is also using just the bare-bones features of Ionic’s gesture system as well, there are more advanced concepts you could make use of (like conditions in which a gesture is allowed to start).
I wanted to focus mainly on the gestures and animation aspect of this functionality, but if there is interest in covering the concept of a
<app-tinder-card-stack> component to work in conjunction with the
<app-tinder-card> component let me know in the comments. | https://www.joshmorony.com/create-tinder-style-swipe-cards-with-ionic-gestures/ | CC-MAIN-2020-10 | refinedweb | 2,554 | 57.1 |
Opened 6 years ago
Closed 6 years ago
#20640 closed Bug (fixed)
`get_deleted_objects` causes an error if there is no change view.
Description
The format_callback used for rendering the objects to be deleted on the confirmation screen doesn't attempt to fail gracefully, if there is no named URL fitting the "namespace:appname_modelname_change" - if
get_urls() is overridden on a
ModelAdmin subclass to either change, remove or replace the
change_view, the delete page will never work due to a
NoReverseMatch.
Proposed solution:
NoReverseMatch should be caught, and the format should end up the same as if
has_admin were
False.
(note: link to GitHub above is to the latest revision in master, as I write this.)
Change History (5)
comment:1 Changed 6 years ago by
comment:2 Changed 6 years ago by
comment:3 Changed 6 years ago by
Pull request:
Tests pass under postgresql and sqlite
Created a test project and verified that the bug occurs. | https://code.djangoproject.com/ticket/20640?cversion=1&cnum_hist=3 | CC-MAIN-2019-51 | refinedweb | 156 | 57.74 |
In the first installment of this two-part series on developing Android Apps with Scala and Scaloid, I explained how Scaloid simplifies and reduces the required Android code as much as possible while leveraging type safety. In this article, I explain how to utilize asynchronous task processing, the execution of methods from system services, and specific Scaloid classes and traits.
Creating a Scaloid Project Based on a Template
The easiest way to start a new Scaloid project is to use one of the available template projects as a starting point. Following the instructions on how to do this can be difficult, so I provide some details on starting a successful Scaloid project with Maven. Scaloid also works with Scala's simple build tool (sbt although there were issues in previous versions.
First, you need to fork the Hello world of Scaloid for maven project from its GitHub repository. Then, open the
pom.xml file, located in the root folder, and change the value of the target Android SDK platform from 8 to the API Level value of the Android Virtual Device you want to target. You can find the value in project -> build > plugins -> plugin -> configuration -> sdk -> platform. The following lines show the default value and the previous lines in the XML file:
... <build> <plugins> <plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>android-maven-plugin</artifactId> <version>3> <sdk> <platform>8</platform> </sdk> ...
The Android Virtual Device Manager displays the list of your existing virtual devices. Use the API level for one of your devices instead of the default 8. If you keep the 8 and you are working with a more modern API level, the build will fail. For example, Figure 1 shows a single entry in the Android Virtual Device Manager with an API Level equal to 18. In this case, it is necessary to replace 8 with 18, so both the build and deploy will work for that API Level installed in the Android SDK. Obviously, you will need to install and use the minimum API Level you want to support for your Android App.
Figure 1: The Android Virtual Device Manager displaying one virtual device with its API Level.
You can also check the minimum API Level installed in the Android SDK by checking the API value in the Android SDK Manager (see Figure 2).
Figure 2: The Android SDK Manager displaying the installed API Level, Android 4.3 (API 18).
The
AndroidManifest.xml file specifies the main Scala class for the App that extends
SActivity and the minimum required SDK version. Here again, you need to update the value for
uses-sdk
android:minSdkVersion to the minimum API Level you want to support. Notice that
activity android:name="org.scaloid.hello.HelloScaloidActivity" specifies that the main activity is
HelloScaloidActivity, located in the
org.scaloid.hello package. The following lines show the edited version of the
AndroidManifest.xml file in the Maven Scaloid template:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns: <uses-sdk android: <application android: <activity android: <intent-filter> <action android: <category android: </intent-filter> </activity> </application> </manifest>
As you might notice, the only difference with the
AndroidManifest.xml file when you develop apps in Java is that the target class for each activity you define in the XML file is a Scala class instead of a Java class.
You can use the Maven call
mvn clean package to build the project and generate the Android Application Package File, known as an APK, with the Android debug certificate. The build process runs Proguard to optimize the size of the final app.
After a successful build, you can use the
mvn android:deploy Maven call to deploy the generated APK to all the devices connected with the Android Debug bridge.
If you work with the Scala IDE for Eclipse or just Eclipse, you can generate the project files for Eclipse with the
mvn eclipse:eclipse Maven call (Figure 3).
Figure 3: The hello-scaloid-maven project structure in Eclipse, opened after Maven generated the project files for Eclipse.
Once you have the template project running on the Android device you use for debugging purposes, you can replace
HelloScaloidActivity.scala with your new Scala file indicating your main activity. Then, you can make the necessary changes to the
AndroidManifest.xml file with the activities definitions and the required permissions. This way, you can easily start a new Scaloid project.
Running Asynchronous Jobs and Notifying the UI
The Android API provides the
android.os.AsyncTask helper class around
Thread and
Handler to enable you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. Scaloid makes it easier to run a job with an asynchronous execution and notify the UI thread without using
AsyncTask. You can combine the use of the
runOnUiThread method to schedule the execution on the UI thread and
scala.concurrent.ops.spawn to evaluate an expression asynchronously. Because Scaloid handles
runOnUiThread for you in some methods (such as
alert,
toast and
spinnerDialog), the code is even easier to read and understand.
The following lines define a
runJob method that retrieves the contents of a URL and returns the first 10 lines as a string separated by
\n. The method takes some time to retrieve the contents of the URL, so it is a great candidate for an asynchronous execution.
def runJob(uri: String): String = scala.io.Source.fromURL(uri).getLines().take(10).mkString("\n")
The following lines simulate a sign-in process that takes some time when you click the Sign In button. The code requires
import scala.concurrent.ops._ because it uses
spawn to call the
runJob method with an asynchronous execution. Notice that the code is really easy to read because there aren't many different methods (which
AsyncTask usage would require). The code displays a spinner dialog while the asynchronous job is running (see Figure 4), dismisses the dialog when it finishes, and shows an alert with the result of the
runJob method (see Figure 5). There is no need to use the
runOnUiThread method because both
spinnerDialog and
alert handle the execution on the UI thread for you. The
spinnerDialog method reduces the code required to call
ProgressDialog.show because Scaloid uses the implicit context I explained in the previous article. I've excluded exception handling to simplify the code.
SButton("Sign in").onClick({ val progressDialog = spinnerDialog("Scaloid App", "Authentication in progress...") spawn { val result = runJob("") progressDialog.dismiss() alert("Welcome to the Scaloid App. Check the results:", result) } })
Figure 4: The App displaying the spinner dialog while an asynchronous job is retrieving contents from a URL.
Figure 5: The App displaying the results of the asynchronous job.
| http://www.drdobbs.com/security/the-twofish-encryption-algorithm/security/developing-android-apps-with-scala-and-s/240162204 | CC-MAIN-2015-48 | refinedweb | 1,122 | 54.52 |
React Integration
React TinyMCE component.Contribute to this page
Integration with React is easily done with our @tinymce/tinymce-react package. This how-to shows you how to setup a project using react, tinymce and Create React App.
1. Installing
create-react-app
We will use the Create React App to quickly and easily get our project up and running.
Simply run the following.
$ npm install -g create-react-app
2. Create a new project
Use
create-react-app to create a new project named
tinymce-react-demo.
$ create-react-app tinymce-react-demo
When all of the installs have finished, cd into the directory.
$ cd tinymce-react-demo
3. Setup
react-tinymce
Install the npm package and save it to your
package.json with
--save.
$ npm install --save @tinymce/tinymce-react
3.1 Loading TinyMCE
Auto-loading from TinyMCE Cloud
@tinymce/tinymce-react requires
tinymce to be globally available to work, but to make it as easy as possible it will automatically load TinyMCE Cloud if it can't find TinyMCE available when the component is mounting. To get rid of the
This domain is not registered... warning, sign up for the cloud and enter the api key like this:
<Editor apiKey='YOUR_API_KEY' init={{ /* your other settings */ }} />
You can also define what cloud channel you want to use out these three *
stable Default. The most stable and well-tested version that has passed the Tiny quality assurance process. *
testing This channel will deploy the current candidate for release to the
stable channel. *
dev The cutting edge version of TinyMCE updated daily for the daring users.
So using the
dev channel would look like this:
<Editor apiKey='YOUR_API_KEY' cloudChannel='dev' init={{ /* your other settings */ }} />
For more info on the different channels see the documentation.
To opt out of using TinyMCE cloud, you have to make TinyMCE globally available yourself. This can be done either by hosting the
tinymce.min.js file by yourself and adding a script tag to your HTML or, if you are using a module loader, installing TinyMCE with npm. For info on how to get TinyMCE working with module loaders check out this page in the documentation.
<script src=""></script>
4. Replace the App.js file
Open up the provided
App.js file located in the
src directory and replace its content with the code below.
import React from 'react'; import { Editor } from '@tinymce/tinymce-react'; class App extends React.Component { handleEditorChange = (e) => { console.log('Content was updated:', e.target.getContent()); } render() { return ( <Editor initialValue="<p>This is the initial content of the editor</p>" init={{ plugins: 'link image code', toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | code' }} onChange={this.handleEditorChange} /> ); } } export default App;
5. Start the development server
Start up the development server provided with
create-react-app.
$ npm start
6. Keep on hacking
This was just a simple guide on how to get started. For more complex configuration information, see the React. | https://www.tiny.cloud/docs-4x/integrations/react/ | CC-MAIN-2019-43 | refinedweb | 489 | 50.63 |
The module Net::XMPP::Client::GTalk is aimed at providing an easy to use wrapper around NET::XMPP class of modules for specific use with GTalk.
Although the majority of this can be achieved through Net::XMPP::Client there are several parameters that need to be fixed and it took me a good hour and half just to get the basics to work, which IMHO is too long.
Additionally Net::XMPP::Client provides call back functions which ( again IMHO ) is confusing/counter-intuitive/unnecessary in synchronous programs - And these are not just additional provisions but requirements.
There are also sections ( such as checking if a buddy is online ) that do not work and this module provides for a workaround.
Additionally Net::XMPP::Client::GTalk provides direct access to the NET::XMPP connection object, so all functions of the NET::XMPP class of modules.Example ( from module POD ):
This example connects to GTalk and waits for a chat message from someone. It replies to that person with the chat message that it received. Additionally it will dump online buddies at regular intervals along with the contents of the message it receives.
You can quit this program by sending it the chat message 'exit'.
I have contacted the author of Net::XMPP as I am adding to his/her namespaceI have contacted the author of Net::XMPP as I am adding to his/her namespaceuse Net::XMPP::Client::GTalk ; use Data::Dump qw( dump ) ; my $username ; # = '' ; Set GTalk username here [ WITHOUT '@gmail. +com' ]. my $password ; # = '' ; Set GTalk password here. unless( defined( $username ) and defined( $password ) ) { die( "SET YOUR GTALK USERNAME AND PASSWORD ABOVE!\n" ) ; } my $ob = new Net::XMPP::Client::GTalk( USERNAME => $username , PASSWORD => $password , ); my $require_run = 1 ; my $iteration = 1 ; while( $require_run ) { my $message = $ob->wait_for_message( 60 ) ; unless( $message ) { print "GOT NO MESSAGE - waiting longer\n" ; } if( $message->{ error } ) { print "ERROR \n" ; next ; } else { dump( $message ) ; } if( $message->{ message } eq 'exit' ) { print "Asked to exit by " . $message->{ from } . "\n" ; $message->{ message } = 'Exiting ... ' ; $require_run = 0 ; } $ob->send_message( $message->{ from }, $message->{ message } ) ; if( int( $iteration / 3 ) == ( $iteration / 3 ) ) { my @online_buddies = @{ $ob->get_online_buddies() } ; dump( \@online_buddies ) ; } $iteration++ ; } exit() ;
Would greatly appreciate any kind of feedback!
Update: This module is now on CPAN here | http://www.perlmonks.org/bare/?node_id=1014043 | CC-MAIN-2014-42 | refinedweb | 368 | 50.26 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.