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 |
|---|---|---|---|---|---|
, raising integers to high powers
[2]
Luckily, we can reuse the efficient algorithms developed in the previous article, with very few modifications to perform modular exponentiation as well. This is possible because of some convenient properties of modular arithmetic.
Modular multiplication
Given two numbers, a and b, their product modulo n is
. Consider the number x < n, such that
. Such a number always exists, and we usually call it the remainder of dividing a by n. Similarly, there is a y < b, such that
. It follows from basic rules of modular arithmetic that
[3]
Therefore, if we want to know the product of a and b modulo n, we just have to keep their remainders when divided by n. Note: a and b may be arbitrarily large, but x and y are always smaller than n.
A naive algorithm
What is the most naive way you can think of for raising computing
? Raise a to the power b, and then reduce modulo n. Right?
Indeed, this is a very unsophisticated and slow method, because raising a to the power b can result in a really huge number that takes long to compute.
For any useful number, this algorithm is so slow that I'm not even going to run it in the tests.
Using the properties of modular multiplication
As we've learned above, modular multiplication allows us to just keep the intermediate result
at each step. Here's the implementation of a simple repeated multiplication algorithm for computing modular exponents this way:
def modexp_mul(a, b, n): r = 1 for i in xrange(b): r = r * a % n return r
It's much better than the naive algorithm, but as we saw in the previous article it's quite slow, requiring b multiplications (and reductions modulo n).
We can apply the same modular reduction rule to the more efficient exponentiation algorithms we've studied before.
Modular exponentiation by squaring
Here's the right-to-left method with modular reductions at each step.
def modexp_rl(a, b, n): r = 1 while 1: if b % 2 == 1: r = r * a % n b /= 2 if b == 0: break a = a * a % n return r
We use exactly the same algorithm, but reduce every multiplication
. So the numbers we deal with here are never very large.
Similarly, here's the left-to-right method:
def modexp_lr(a, b, n): r = 1 for bit in reversed(_bits_of_n(b)): r = r * r % n if bit == 1: r = r * a % n return r
With _bits_of_n being, as before:
def _bits_of_n(n): """ Return the list of the bits in the binary representation of n, from LSB to MSB """ bits = [] while n: bits.append(n % 2) n /= 2 return bits
Relative performance
As I've noted in the previous article, the RL method does a worse job of keeping its multiplicands low than the LR method. And indeed, for smaller n, RL is somewhat faster than LR. For larger n, RL is somewhat slower.
What's obvious is that now the built-in pow is superior to both hand-coded methods [4]. My tests show it's anywhere from twice to 10 times as fast.
Why is pow so much faster? Is it only the efficiency of C versus Python? Not really. In fact, pow uses an even more sophisticated algorithm for large exponents [5]. Indeed, for small exponents the runtime of pow is similar to the runtime of the implementations I presented above.
The k-ary LR method
It turns out that the LR method of repeated squaring can be generalized. Instead of breaking the exponent into bits of its base-2 representation, we can break it into larger pieces, and save some computations this way.
I'll present the k-ary LR method that breaks the exponent into its "digits" in base
for some integer k. The exponent can be written as:
Where
are the digits of b in base m.
is then:
We compute this iteratively as follows [6]:
Raise
to the m-th power and multiply by
. We get
. Next, raise
to the m-th power and multiply by
, obtaining
. If we continue with this, we'll eventually get
.
This translates into the following code:
def modexp_lr_k_ary(a, b, n, k=5): """ Compute a ** b (mod n) K-ary LR method, with a customizable 'k'. """ base = 2 << (k - 1) # Precompute the table of exponents table = [1] * base for i in xrange(1, base): table[i] = table[i - 1] * a % n # Just like the binary LR method, just with a # different base # r = 1 for digit in reversed(_digits_of_n(b, base)): for i in xrange(k): r = r * r % n if digit: r = r * table[digit] % n return r
Note that we save some time by pre-computing the powers of a for exponents that can be digits in base m. Also, the _digits_of_n is the following generalization of _bits_of_n:
def _digits_of_n(n, b): """ Return the list of the digits in the base 'b' representation of n, from LSB to MSB """ digits = [] while n: digits.append(n % b) n /= b return digits
Performance of the k-ary method
In my tests, the k-ary LR method with k = 5 is about 25% faster than the binary LR method, and is within 20% of the built-in pow function.
Experimenting with the value of k affects these results, but 5 seems to be a good value that produces the best performance in most cases. This is probably why it's also used as the value of k in the implementation of pow.
Python's built-in pow
I've mentioned Python's pow function several times in this article. The Python version I'm talking about is 2.5, though I doubt this functionality has changed in 2.6 or 3.0. The pow I'm interested in is implemented in the long_pow function in objects/longobject.c in the Python source code distribution. As mentioned in [5], it uses the binary LR method for small exponents, and the k-ary LR method for large exponents.
These implementations follow closely algorithms 14.79 and 14.82 in the excellent Handbook of Applied Cryptography, which is freely available online.
Summary
As we've seen, exponentiation and modular exponentiation are one of those applications in which an efficient algorithm is required for feasibility. Using the trivial/naive algorithms is possible only for small cases which aren't very interesting. To process realistically large numbers (such as the ones required for cryptographic algorithms), one needs powerful methods in his toolbox.
| https://eli.thegreenplace.net/2009/03/28/efficient-modular-exponentiation-algorithms | CC-MAIN-2019-22 | refinedweb | 1,091 | 60.75 |
So far I have a very basic application that can read simple arguments such as -t or -s. What I want to do is when the program picks up on the argument it will run a function. The two things I am not sure of though is how to read anything after the first argument and then what to store that second argument as to pass it to the function.
So, what I want to happen is the following pseudo code:
Terminal: app-name -t userEnteredText
Application then sees that "-t" was used and then passes "userEnteredText" to argumentT() and then argumentT() returns the results and then the application couts the info.
All I really need is to know how to read the text entered after -t.
Below is the code I have so far:
Code:#include <iostream> using namespace std; //This is where we are going to initialize our functions. //int x and int y are just space holders for now. int argumentT(int x, int y); int argumentS(int x, int y); int main(int argc, char *argv[]) { //Check to see if the user entered any arguments //if argc does not equal 2 then they did not. if(argc != 2) { printf("You did not tell me what to do!\n"); } else { //Assuming that argc does equal 2 then we see what //the user entered and then pass that info on to //the corresponding function. if(strcmp(argv[1],"-t")==0) { //This was just a test to see if the argument could be read. int x = 1; int y = 2; cout << argumentT(x, y) <<"\n"; } if(strcmp(argv[1],"-s")==0) { //This was just a test to see if the argument could be read. int x = 1; int y = 2; cout << argumentS(x, y) <<"\n"; } } } //This is the function for the -t argument. int argumentT(int x, int y) { return x + y ; } //This is the function for the -s argument. int argumentS(int x, int y) { return x * y; } | http://cboard.cprogramming.com/cplusplus-programming/107710-reading-terminal-arguments.html | CC-MAIN-2015-32 | refinedweb | 330 | 76.05 |
FULL PRODUCT VERSION : java version "1.7.0" Java(TM) SE Runtime Environment (build 1.7.0-b147) Java HotSpot(TM) 64-Bit Server VM (build 21.0-b17, mixed mode) ADDITIONAL OS VERSION INFORMATION : Microsoft Windows [Version 6.1.7601] A DESCRIPTION OF THE PROBLEM : When an JComboBox is showing its dropdown list in an Applet in a browser, pressing the browser's scrollbar arrow / moving the browser's scrollbar does not update the dropdown list location. It stays still on the screen which makes the dropdown list seems to be "detached" from its JComboBox. STEPS TO FOLLOW TO REPRODUCE THE PROBLEM : Prepare an Applet to display a JComboBox and a HTML file, jnlp...etc for standard applet deployment. In the HTML, it should contain some spacing, eg. <br/>, in the <body> part. Open an Applet with any browser, resizes height of the browser / input more space in html file so that the browser's vertical scrollbar appears. Click on the JComboBox to show its dropdown list, then press the browser's scrollbar arrow or drag the browser's scrollbar to perform scrolling. The dropdown list of the JComboBox is detached from its parent instead of scrolling along with the JComboBox. EXPECTED VERSUS ACTUAL BEHAVIOR : EXPECTED - Location of the dropdown list should be updated with its JComboBox. ACTUAL - Location is not updated. REPRODUCIBILITY : This bug can be reproduced always. ---------- BEGIN SOURCE ---------- package test.applet; import java.awt.*; import javax.swing.*; public class TestApplet extends JApplet { public void init() { super.init(); String[] comboBoxModel = new String[] {"This is Choice 1.", "This is Choice 2."}; JComboBox comboBox = new JComboBox(comboBoxModel); getContentPane().add(comboBox); setSize(300, 100); } } ---------- END SOURCE ---------- | https://bugs.java.com/bugdatabase/view_bug.do?bug_id=7094099 | CC-MAIN-2020-24 | refinedweb | 276 | 68.87 |
Could be a timing thing. I have a script that does basically the same thing (but inventories running services that are using my FGDB so only those are stopped/started) and I've had to put in a bunch of "sleep" times in to let the file system, etc catch up. I have to play with the time needed, but in most cases 5-10 secs has been plenty...but for some, up to 30 secs.
import time def mySleep(secs): arcpy.AddMessage(" zzz...sleeping {0} seconds to allow network file status to catch up....".format(secs)) time.sleep(secs) # stop your service mySleep(5) # start your service
Is this on Windows or Linux? Do you see any errors within the logs about service startup timing out? Is this a single or multi-machine site? If it's a multi-machine site, do you see the SOC process start up on each machine? Enable the Command Line field in Task Manager on Windows and take a look at top on Linux.
Dave:
Can you perform a truncate and append of your data instead copying over the data which requires stopping the service? I update many different sets of data for AGS using the truncate and append method, which has eliminated the need to stop services and thereby reduces the number of issues that I am faced with.
Has this script run successfully in your environment in the past against an older AGS version (e.g. 10.3.1) and you are now trying to run this script against an upgraded environment (10.4.1), but it's failing?
Michael,
if you could please explain this process a little more, it would be greatly appreciated.
thanks
dave
Dave:
Truncate and append is pretty simple and it's a fast process. You are deleting all records, but the database schema is left intact and you are then appending in the new records.
env.workspace = "Destination geodatabase"
fcs = arcpy.ListFeatureClasses()
for fc in fcs:
arcpy.DeleteFeatures_management(fc)
arcpy.Append_management("Data source feature class, fc, "TEST", "", "")
This is the working part of the script so you can see not much code is involved.
all,
Windows VM (2012 R2)
Only errors in logs is:
"Unable to process request. Error handling service request :Could not find a service with the name '####/MapServer/Support' in the configured clusters. Service may be stopped or ArcGIS Server may not be running." (I watch the service in server manager just sit there in "starting" status and never come back to "started")
Single Machine Site
during the script process we can watch the the SOCs come and go. even after the data is copied over and the service is started back up with the see the SOCs come back in the task manager as up and running but the server manager is stuck at "starting"
hope this helps
dave
Michael Volz has a good suggestion; the schema doesn't sound like it's changing so you can just update the data within the feature class without needing to stop and start the service.
In regards to the problem, what do the Configured and Real-time state show within the Admin API when clicking on the Status of the service? That should show you which one isn't being updated. Once both are "Started" or both are "Stopped", Manager will reflect that status. | https://community.esri.com/t5/arcgis-enterprise-questions/10-4-1-token-response/td-p/10340 | CC-MAIN-2022-21 | refinedweb | 561 | 70.53 |
** Changed in: zorba Status: New => In Progress -- You received this bug notification because you are a member of Zorba Coders, which is the registrant for Zorba.
Advertising
Title: file:read-text-lines() blocking Status in Zorba - The XQuery Processor: In Progress Bug description: I wrote the following query: import module namespace file =""; for $line at $i in file:read-text-lines("doc.xml") return if($i lt 1104869) then () else concat($line, " ") Where doc.xml is a large document. The result of the query seems to never end and its memory footprint is huge. To manage notifications about this bug go to: -- Mailing list: Post to : zorba-coders@lists.launchpad.net Unsubscribe : More help : | https://www.mail-archive.com/zorba-coders@lists.launchpad.net/msg07495.html | CC-MAIN-2016-44 | refinedweb | 114 | 57.16 |
One you want a more useful toString() implementation. In the end you might have 100 lines of code that could be rewritten with 10 lines of Scala or Groovy code. Java IDEs like Eclipse or IntelliJ try to reduce this problem by providing various types of code generation functionality. However, even if you do not have to write the code yourself, you always see it (and get distracted by it) if you open such a file in your IDE.
Project Lombok (don't be frightened by the ugly web page) is a small Java library that can help reducing the amount of Boilerplate Code in Java Applications. Project Lombok provides a set of annotations that are processed at development time to inject code into your Java application. The injected code is immediately available in your development environment.
Lets have a look at the following Eclipse Screenshot:
The defined class is annotated with Lombok's @Data annotation and does not contain any more than three private fields. @Data automatically injects getters, setters (for non final fields), equals(), hashCode(), toString() and a constructor for initializing the final dateOfBirth field. As you can see the generated methods are directly available in Eclipse and shown in the Outline view.
Setup
To set up Lombok for your application you have to put lombok.jar to your classpath. If you are using Maven you just have to add to following dependency to your pom.xml:
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.14.8</version> <scope>provided</scope> </dependency>
You also need to set up Lombok in the IDE you are using:
- NetBeans users just have to enable the Enable Annotation Processing in Editor option in their project properties (see: NetBeans instructions).
- Eclipse users can install Lombok by double clicking lombok.jar and following a quick installation wizard.
- For IntelliJ a Lombok Plugin is available.
Getting started with Lombok
The @Data annotation shown in the introduction is actually a shortcut for various other Lombok annotations. Sometimes @Data does too much. In this case, you can fall back to more specific Lombok annotations that give you more flexibility.
Generating only getters and setters can be achieved with @Getter and @Setter:
@Getter @Setter public class Person { private final LocalDate birthday; private String firstName; private String lastName; public Person(LocalDate birthday) { this.birthday = birthday; } }
Note that getter methods for boolean fields are prefixed with is instead of get (e.g. isFoo() instead of getFoo()). If you only want to generate getters and setters for specific fields you can annotate these fields instead of the class.
Generating equals(), hashCode() and toString():
@EqualsAndHashCode @ToString public class Person { ... }
@EqualsAndHashCode and @ToString also have various properties that can be used to customize their behaviour:
@EqualsAndHashCode(exclude = {"firstName"}) @ToString(callSuper = true, of = {"firstName", "lastName"}) public class Person { ... }
Here the field firstName will not be considered by equals() and hashCode(). toString() will call super.toString() first and only consider firstName and lastName.
For constructor generation multiple annotations are available:
- @NoArgsConstructor generates a constructor that takes no arguments (default constructor).
- @RequiredArgsConstructor generates a constructor with one parameter for all non-initialized final fields.
- @AllArgsConstructor generates a constructor with one parameter for all fields in the class.
The @Data annotation is actually an often used shortcut for @ToString, @EqualsAndHashCode, @Getter, @Setter and @RequiredArgsConstructor.
If you prefer immutable classes you can use @Value instead of @Data:
@Value public class Person { LocalDate birthday; String firstName; String lastName; }
@Value is a shortcut for @ToString, @EqualsAndHashCode, @AllArgsConstructor, @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) and @Getter.
So, with @Value you get toString(), equals(), hashCode(), getters and a constructor with one parameter for each field. It also makes all fields private and final by default, so you do not have to add private or final modifiers.
Looking into Lombok's experimental features
Besides the well supported annotations shown so far, Lombok has a couple of experimental features that can be found on the Experimental Features page.
One of these features I like in particular is the @Builder annotation, which provides an implementation of the Builder Pattern.
@Builder public class Person { private final LocalDate birthday; private String firstName; private String lastName; }
@Builder generates a static builder() method that returns a builder instance. This builder instance can be used to build an object of the class annotated with @Builder (here Person):
Person p = Person.builder() .birthday(LocalDate.of(1980, 10, 5)) .firstName("John") .lastName("Smith") .build();
By the way, if you wonder what this LocalDate class is, you should have a look at my blog post about the Java 8 date and time API ;-)
Conclusion
Project Lombok injects generated methods, like getters and setters, based on annotations. It provides an easy way to significantly reduce the amount of Boilerplate code in Java applications.
Be aware that there is a downside: According to reddit comments (including a comment of the project author), Lombok has to rely on various hacks to get the job done. So, there is a chance that future JDK or IDE releases will break the functionality of project Lombok. On the other hand, these comments where made 5 years ago and Project Lombok is still actively maintained.
You can find the source of Project Lombok on GitHub.
Mieleton - Monday, 22 September, 2014
I wouldn't promote the use of 1.14.* series yet, it has MAJOR performance problem:
1.12.6 is previous version without performance related problems, 1.14.8 is the next best (but still slower than 1.12.6)
Michael Scharhag - Tuesday, 23 September, 2014
Hi Mieleton,
thanks for the info, I didn't know this.
I updated the Maven dependency to 1.12.6.
Michael Scharhag - Sunday, 12 October, 2014
In the DZone comments for this article a lombok developer suggested to use version 1.14.8.
So I updated the version to 1.14.8.
Morten Christensen - Wednesday, 22 October, 2014, integrates with all java tools and is extremely customisable. You can check it out at "". Let me know what you think? | https://www.mscharhag.com/java/reduce-boilerplate-code-in-java-with-project-lombok | CC-MAIN-2019-18 | refinedweb | 997 | 55.64 |
/* $OpenBSD: ftree.c,v 1.28 2008/05/06 06:54:28 henning Exp $ */ /* $NetBSD: ftree.c,v 1.4 1995/03/21 09:07:21 const char sccsid[] = "@(#)ftree.c 8.2 (Berkeley) 4/18/94"; #else static const char rcsid[] = "$OpenBSD: ftree.c,v 1.28 2008/05/06 06:54:28 henning Exp $"; #endif #endif /* not lint */ #include <sys/types.h> #include <sys/time.h> #include <sys/stat.h> #include <sys/param.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <fts.h> #include "pax.h" #include "ftree.h" #include "extern.h" /* * routines to interface with the fts library function. * * file args supplied to pax are stored on a single linked list (of type FTREE) * and given to fts to be processed one at a time. pax "selects" files from * the expansion of each arg into the corresponding file tree (if the arg is a * directory, otherwise the node itself is just passed to pax). The selection * is modified by the -n and -u flags. The user is informed when a specific * file arg does not generate any selected files. -n keeps expanding the file * tree arg until one of its files is selected, then skips to the next file * arg. when the user does not supply the file trees as command line args to * pax, they are read from stdin */ static FTS *ftsp = NULL; /* current FTS handle */ static int ftsopts; /* options to be used on fts_open */ static char *farray[2]; /* array for passing each arg to fts */ static FTREE *fthead = NULL; /* head of linked list of file args */ static FTREE *fttail = NULL; /* tail of linked list of file args */ static FTREE *ftcur = NULL; /* current file arg being processed */ static FTSENT *ftent = NULL; /* current file tree entry */ static int ftree_skip; /* when set skip to next file arg */ static int ftree_arg(void); static char *getpathname(char *, int); /* * ftree_start() * initialize the options passed to fts_open() during this run of pax * options are based on the selection of pax options by the user * fts_start() also calls fts_arg() to open the first valid file arg. We * also attempt to reset directory access times when -t (tflag) is set. * Return: * 0 if there is at least one valid file arg to process, -1 otherwise */ int ftree_start(void) { /* * set up the operation mode of fts, open the first file arg. We must * use FTS_NOCHDIR, as the user may have to open multiple archives and * if fts did a chdir off into the boondocks, we may create an archive * volume in an place where the user did not expect to. */ ftsopts = FTS_NOCHDIR; /* * optional user flags that effect file traversal * -H command line symlink follow only (half follow) * -L follow sylinks (logical) * -P do not follow sylinks (physical). This is the default. * -X do not cross over mount points * -t preserve access times on files read. * -n select only the first member of a file tree when a match is found * -d do not extract subtrees rooted at a directory arg. */ if (Lflag) ftsopts |= FTS_LOGICAL; else ftsopts |= FTS_PHYSICAL; if (Hflag) ftsopts |= FTS_COMFOLLOW; if (Xflag) ftsopts |= FTS_XDEV; if ((fthead == NULL) && ((farray[0] = malloc(PAXPATHLEN+2)) == NULL)) { paxwarn(1, "Unable to allocate memory for file name buffer"); return(-1); } if (ftree_arg() < 0) return(-1); if (tflag && (atdir_start() < 0)) return(-1); return(0); } /* * ftree_add() * add the arg to the linked list of files to process. Each will be * processed by fts one at a time * Return: * 0 if added to the linked list, -1 if failed */ int ftree_add(char *str, int chflg) { FTREE *ft; int len; /* * simple check for bad args */ if ((str == NULL) || (*str == '\0')) { paxwarn(0, "Invalid file name argument"); return(-1); } /* * allocate FTREE node and add to the end of the linked list (args are * processed in the same order they were passed to pax). Get rid of any * trailing / the user may pass us. (watch out for / by itself). */ if ((ft = (FTREE *)malloc(sizeof(FTREE))) == NULL) { paxwarn(0, "Unable to allocate memory for filename"); return(-1); } if (((len = strlen(str) - 1) > 0) && (str[len] == '/')) str[len] = '\0'; ft->fname = str; ft->refcnt = 0; ft->newercnt = 0; ft->chflg = chflg; ft->fow = NULL; if (fthead == NULL) { fttail = fthead = ft; return(0); } fttail->fow = ft; fttail = ft; return(0); } /* * ftree_sel() * this entry has been selected by pax. bump up reference count and handle * -n and -d processing. */ void ftree_sel(ARCHD *arcn) { /* * set reference bit for this pattern. This linked list is only used * when file trees are supplied pax as args. The list is not used when * the trees are read from stdin. */ if (ftcur != NULL) ftcur->refcnt = 1; /* * if -n we are done with this arg, force a skip to the next arg when * pax asks for the next file in next_file(). * if -d we tell fts only to match the directory (if the arg is a dir) * and not the entire file tree rooted at that point. */ if (nflag) ftree_skip = 1; if (!dflag || (arcn->type != PAX_DIR)) return; if (ftent != NULL) (void)fts_set(ftsp, ftent, FTS_SKIP); } /* * ftree_notsel() * this entry has not been selected by pax. */ void ftree_notsel() { if (ftent != NULL) (void)fts_set(ftsp, ftent, FTS_SKIP); } /* * ftree_skipped_newer() * file has been skipped because a newer file exists and -u/-D given */ void ftree_skipped_newer(ARCHD *arcn) { /* skipped due to -u/-D, mark accordingly */ if (ftcur != NULL) ftcur->newercnt = 1; } /* * ftree_chk() * called at end on pax execution. Prints all those file args that did not * have a selected member (reference count still 0) */ void ftree_chk(void) { FTREE *ft; int wban = 0; /* * make sure all dir access times were reset. */ if (tflag) atdir_end(); /* * walk down list and check reference count. Print out those members * that never had a match */ for (ft = fthead; ft != NULL; ft = ft->fow) { if ((ft->refcnt > 0) || ft->newercnt > 0 || ft->chflg) continue; if (wban == 0) { paxwarn(1,"WARNING! These file names were not selected:"); ++wban; } (void)fprintf(stderr, "%s\n", ft->fname); } } /* * ftree_arg() * Get the next file arg for fts to process. Can be from either the linked * list or read from stdin when the user did not them as args to pax. Each * arg is processed until the first successful fts_open(). * Return: * 0 when the next arg is ready to go, -1 if out of file args (or EOF on * stdin). */ static int ftree_arg(void) { /* * close off the current file tree */ if (ftsp != NULL) { (void)fts_close(ftsp); ftsp = NULL; } /* * keep looping until we get a valid file tree to process. Stop when we * reach the end of the list (or get an eof on stdin) */ for (;;) { if (fthead == NULL) { /* * the user didn't supply any args, get the file trees * to process from stdin; */ if (getpathname(farray[0], PAXPATHLEN+1) == NULL) return(-1); } else { /* * the user supplied the file args as arguments to pax */ if (ftcur == NULL) ftcur = fthead; else if ((ftcur = ftcur->fow) == NULL) return(-1); if (ftcur->chflg) { /* First fchdir() back... */ if (fdochdir(cwdfd) < 0) { syswarn(1, errno, "Can't fchdir to starting directory"); return(-1); } if (dochdir(ftcur->fname) < 0) { syswarn(1, errno, "Can't chdir to %s", ftcur->fname); return(-1); } continue; } else farray[0] = ftcur->fname; } /* * watch it, fts wants the file arg stored in a array of char * ptrs, with the last one a null. we use a two element array * and set farray[0] to point at the buffer with the file name * in it. We cannot pass all the file args to fts at one shot * as we need to keep a handle on which file arg generates what * files (the -n and -d flags need this). If the open is * successful, return a 0. */ if ((ftsp = fts_open(farray, ftsopts, NULL)) != NULL) break; } return(0); } /* * next_file() * supplies the next file to process in the supplied archd structure. * Return: * 0 when contents of arcn have been set with the next file, -1 when done. */ int next_file(ARCHD *arcn) { int cnt; time_t atime; time_t mtime; /* * ftree_sel() might have set the ftree_skip flag if the user has the * -n option and a file was selected from this file arg tree. (-n says * only one member is matched for each pattern) ftree_skip being 1 * forces us to go to the next arg now. */ if (ftree_skip) { /* * clear and go to next arg */ ftree_skip = 0; if (ftree_arg() < 0) return(-1); } /* * loop until we get a valid file to process */ for (;;) { if ((ftent = fts_read(ftsp)) == NULL) { if (errno) syswarn(1, errno, "next_file"); /* * out of files in this tree, go to next arg, if none * we are done */ if (ftree_arg() < 0) return(-1); continue; } /* * handle each type of fts_read() flag */ switch (ftent->fts_info) { case FTS_D: case FTS_DEFAULT: case FTS_F: case FTS_SL: /* * these are all ok */ break; case FTS_SLNONE: /* was same as above cases except Unix conformance requires this error check */ if (Hflag || Lflag) { /* -H or -L was specified */ if (ftent->fts_errno) paxwarn(1, "%s: %s", ftent->fts_name, strerror(ftent->fts_errno)); } break; case FTS_DP: /* * already saw this directory. If the user wants file * access times reset, we use this to restore the * access time for this directory since this is the * last time we will see it in this file subtree * remember to force the time (this is -t on a read * directory, not a created directory). */ if (!tflag || (get_atdir(ftent->fts_statp->st_dev, ftent->fts_statp->st_ino, &mtime, &atime) < 0)) continue; set_ftime(ftent->fts_path, mtime, atime, 1); continue; case FTS_DC: /* * fts claims a file system cycle */ paxwarn(1,"File system cycle found at %s",ftent->fts_path); continue; case FTS_DNR: syswarn(1, ftent->fts_errno, "Unable to read directory %s", ftent->fts_path); continue; case FTS_ERR: syswarn(1, ftent->fts_errno, "File system traversal error"); continue; case FTS_NS: case FTS_NSOK: syswarn(1, ftent->fts_errno, "Unable to access %s", ftent->fts_path); continue; } /* * ok got a file tree node to process. copy info into arcn * structure (initialize as required) */ arcn->skip = 0; arcn->pad = 0; arcn->ln_nlen = 0; arcn->ln_name[0] = '\0'; memcpy(&arcn->sb, ftent->fts_statp, sizeof(arcn->sb)); /* * file type based set up and copy into the arcn struct * SIDE NOTE: * we try to reset the access time on all files and directories * we may read when the -t flag is specified. files are reset * when we close them after copying. we reset the directories * when we are done with their file tree (we also clean up at * end in case we cut short a file tree traversal). However * there is no way to reset access times on symlinks. */ switch (S_IFMT & arcn->sb.st_mode) { case S_IFDIR: arcn->type = PAX_DIR; if (!tflag) break; add_atdir(ftent->fts_path, arcn->sb.st_dev, arcn->sb.st_ino, arcn->sb.st_mtime, arcn->sb.st_atime); break; case S_IFCHR: arcn->type = PAX_CHR; break; case S_IFBLK: arcn->type = PAX_BLK; break; case S_IFREG: /* * only regular files with have data to store on the * archive. all others will store a zero length skip. * the skip field is used by pax for actual data it has * to read (or skip over). */ arcn->type = PAX_REG; arcn->skip = arcn->sb.st_size; break; case S_IFLNK: arcn->type = PAX_SLK; /* * have to read the symlink path from the file */ if ((cnt = readlink(ftent->fts_path, arcn->ln_name, PAXPATHLEN)) < 0) { syswarn(1, errno, "Unable to read symlink %s", ftent->fts_path); continue; } /* * set link name length, watch out readlink does not * always NUL terminate the link path */ arcn->ln_name[cnt] = '\0'; arcn->ln_nlen = cnt; break; case S_IFSOCK: /* * under BSD storing a socket is senseless but we will * let the format specific write function make the * decision of what to do with it. */ arcn->type = PAX_SCK; break; case S_IFIFO: arcn->type = PAX_FIF; break; } break; } /* * copy file name, set file name length */ arcn->nlen = strlcpy(arcn->name, ftent->fts_path, sizeof(arcn->name)); if (arcn->nlen >= sizeof(arcn->name)) arcn->nlen = sizeof(arcn->name) - 1; /* XXX truncate? */ arcn->org_name = ftent->fts_path; return(0); } /* * getpathname() * Reads a pathname from stdin, handling NUL- or newline-termination. * Return: * NULL at end of file, otherwise the NUL-terminated buffer. */ static char * getpathname(char *buf, int buflen) { char *bp, *ep; int ch, term; if (zeroflag) { /* * Read a NUL-terminated pathname, being especially * paranoid about proper termination and pathname length. */ for (bp = buf, ep = buf + buflen; bp < ep; bp++) { if ((ch = getchar()) == EOF) { if (bp != buf) paxwarn(1, "Ignoring unterminated " "pathname at EOF"); return(NULL); } if ((*bp = ch) == '\0') return(buf); } /* Too long - skip this path */ *--bp = '\0'; term = '\0'; } else { if (fgets(buf, buflen, stdin) == NULL) return(NULL); if ((bp = strchr(buf, '\n')) != NULL || feof(stdin)) { if (bp != NULL) *bp = '\0'; return(buf); } /* Too long - skip this path */ term = '\n'; } while ((ch = getchar()) != term && ch != EOF) ; paxwarn(1, "Ignoring too-long pathname: %s", buf); return(NULL); } | http://opensource.apple.com//source/file_cmds/file_cmds-220.7/pax/ftree.c | CC-MAIN-2016-40 | refinedweb | 2,085 | 67.59 |
Windows Communication Foundation From the Inside
Since I did the survey question on extensibility, I thought I'd do this followup on configuration. The two are often talked about together but have very different needs.
Question:
What's the one thing you would change about how configuration is done for WCF applications?
Pick anything you want about the configuration format, tooling, integration with service code, or other topics as you'd like, but try to keep in mind that this is for an application that uses WCF. It's ok if the details of the change have to do with IIS or other products though.
Make it a lot easier (I can see you're going to get a lot of those types of response).
By the time you've configured the endpoint, forgotten the MEX, added it, set the behaviour, futzed around getting authentication to work your config file has swollen to 3x the size it was before.
I know the configuration application is supposed to make it easier (although I end up just doing the XML by hand from previous applications I know work)
Having some sort of common profile ("User/password protected", "HTTP no authenication", "Weird ass federated identity which may well kick off cardspace") type scenarios would be useful when configuring a service for the first time. As would an MSI custom action to reserve namespaces.
And a pony. I want a pony.
Make it easy to avoid an Excel.exe.config file
This is almost like a feature ask for the standard .NET configuration system more than anything, but I definitley wouldn't complain if the WCF took it upon themselves to provide a custom way to do this...
Enable the <system.serviceModel> and every custom section under that to be loaded from an external file rather than from the app/web.config itself. Meaning I'd like to be able to define some resuable custom bindings in a standalone file called MyCustomBindings.config and then be able to do something like:
<bindings href="MyCustomBindings.config" />
Today I'd have either copy/paste across several .configs or write an actual binding of my own. Certainly I'd do the latter if I really was going to reuse it across many projects, but if I just want to share the bindings with my unit test project and my host application project I have to copy/paste today. This, in turn, leads to updates being made to one, but not the other and naturally you run into problems because what you tested isn't what you deployed.
Cheers,
Drew
It would be great to be able to remotely configure any WCF service out of the box. I'm basicly thinking a standard web type interface that talks to an administrative endpoint that allows WCF Configuration Editor functionality.
Thanks,
James
Yes, external config files (so my class library can have its own .config file instead of making me put it in the parent).
Please make programmatic configuration provision and inspection easier. I'm mostly talking about self-hosted services now.
I mean, would it be possible to
a) provide a small set of classes specifically to do programmatic configuration, to make the code more readable :) For example, kind of Builder pattern when use give us some coarse bricks, from which we at first build the host "surface", and then ask them to build the ServiceHost instance and continue with additional tuning...
b) provide API to dump host information without having to manually go through endpoints, channels etc. For instance, you could provide us with a kind of iterator class, which would go through all the elements of a given ServiceHost, giving a chance to dump/read specific information ourselves.
I would like something what MEF guys has done. Simple Imports and Exports in code ... though, it is not 100% possible in WCF, but something like this will add more easy way of configuring it
external files - I second that opinion.
and provide a way to refresh the configuration at runtime. I know that there will be some limitations, but switching the trace level for example would be a nice feature.
A configuration "flow" is required for the SvcConfigEditor.
For example when you choose to use "certificate" as the client authentication token then fields like "service expected spn identity" and "UsernamePasswordValidationMode" are irrelevant. "clientCertificate" on the other hand is required (although can be specified from code). Totally irrelevant fields should not appear - this is really confusing for people who are not web services experts.
Actually I disagree with external configuration files. Not that I think that externalizing the configuration is bad. It isn't and really needs to be a scenario we allow. Instead I'd state that being able to supply the configuration as an XNode is what is actually required. There's already existing APIs to allow us to open an external XML document from a file Uri that exist TODAY in the framework. Make the configuration system do one thing and one thing only: CONFIGURE WCF. This is inline with the SRP. If it instead starts futzing around in the file system it's now doing TWO things: configuration AND locating. Instead an abstract WcfConfigResourceBase collaborator should be used. Create two out of the box: a ConfigurationElementResource (preserving the legacy approach we have today) and an XmlResource (use the same XML schema, just externalized and allowed via an XmlReader). The community will step in and create all sorts of wonderful niche specific implementations and chains for specialty purpose systems. I can think of one right now: SqlServerConfiguration =D
Basically take a look at the approach the Castle Project has taken with Windsor when it comes to configuration. A very good solution indeed. A programmatic API to actually do the configuration (we have this in WCF today). A builder that leverages an abstract resource that actually reifies the configuration into calls to the API (e.g. channel/client/binding/etc for WCF). And finally the set of concrete resource representations that work between a storage system (Configs, external files, UDDI, a SQL schema, etc) and the resource interface (an adapter at work).
jimmyzATmicrosoft.com
I agree with Jimmy, just be able to supply the servicemodel node would be great, then you can figure out for yourslef where to get that from, file, DB or service. (I commented that on the other post hadn't seen this one yet) | http://blogs.msdn.com/drnick/archive/2008/11/12/1-question-survey-on-configuration.aspx | crawl-002 | refinedweb | 1,071 | 53.71 |
In this post, we’re going to explain Kubernetes, also known as K8s. In this introduction, we’ll cover:
- What Kubernetes is
- What it can’t do
- The problems it solves
- K8s architectural components
- Installation
- Alternative options
This article assumes you are new to Kubernetes and want to get a solid understanding of its concepts and building blocks.
(This article is part of our Kubernetes Guide. Use the right-hand menu to navigate.)
What is Kubernetes?
To begin to understand the usefulness of Kubernetes, we have to first understand two concepts: immutable infrastructure and containers.
- Immutable infrastructure is a practice where servers, once deployed, are never modified. If something needs to be changed, you never do so directly on the server. Instead, you’ll build a new server from a base image, that have all your needed changes baked in. This way we can simply replace the old server with the new one without any additional modification.
- Containers offer a way to package code, runtime, system tools, system libraries, and configs altogether. This shipment is a lightweight, standalone executable. This way, your application will behave the same every time no matter where it runs (e.g, Ubuntu, Windows, etc.). Containerization is not a new concept, but it has gained immense popularity with the rise of microservices and Docker.
Armed with those concepts, we can now define Kubernetes as a container or microservice platform that orchestrates computing, networking, and storage infrastructure workloads. Because it doesn’t limit the types of apps you can deploy (any language works), Kubernetes extends how we scale containerized applications so that we can enjoy all the benefits of a truly immutable infrastructure. The general rule of thumb for K8S: if your app fits in a container, Kubernetes will deploy it.
By the way, if you’re wondering where the name “Kubernetes” came from, it is a Greek word, meaning helmsman or pilot. The abbreviation K8s is derived by replacing the eight letters of “ubernete” with the digit 8.
The Kubernetes Project was open-sourced by Google in 2014 after using it to run production workloads at scale for more than a decade. Kubernetes provides the ability to run dynamically scaling, containerised applications, and utilising an API for management. Kubernetes is a vendor-agnostic container management tool, minifying cloud computing costs whilst simplifying the running of resilient and scalable applications.
Kubernetes has become the standard for running containerised applications in the cloud, with the main Cloud Providers (AWS, Azure, GCE, IBM and Oracle) now offering managed Kubernetes services.
Kubernetes basic terms and definitions
To begin understanding how to use K8S, we must understand the objects in the API. Basic K8S objects and several higher-level abstractions are known as controllers. These are the building block of your application lifecycle.
Basic objects include:
- Pod. A group of one or more containers.
- Service. An abstraction that defines a logical set of pods as well as the policy for accessing them.
- Volume. An abstraction that lets us persist data. (This is necessary because containers are ephemeral—meaning data is deleted when the container is deleted.)
- Namespace. A segment of the cluster dedicated to a certain purpose, for example a certain project or team of devs.
Controllers, or higher-level abstractions, include:
- ReplicaSet (RS). Ensures the desired amount of pod is what’s running.
- Deployment. Offers declarative updates for pods an RS.
- StatefulSet. A workload API object that manages stateful applications, such as databases.
- DaemonSet. Ensures that all or some worker nodes run a copy of a pod. This is useful for daemon applications like Fluentd.
- Job. Creates one or more pods, runs a certain task(s) to completion, then deletes the pod(s).
Micro Service
A specific part of a previously monolithic application. A traditional micro-service based architecture would have multiple services making up one, or more, end products. Micro services are typically shared between applications and makes the task of Continuous Integration and Continuous Delivery easier to manage. Explore the difference between monolithic and microservices architecture.
Images
Typically a docker container image – an executable image containing everything you need to run your application; application code, libraries, a runtime, environment variables and configuration files. At runtime, a container image becomes a container which runs everything that is packaged into that image.
Pods
A single or group of containers that share storage and network with a Kubernetes configuration, telling those containers how to behave. Pods share IP and port address space and can communicate with each other over localhost networking. Each pod is assigned an IP address on which it can be accessed by other pods within a cluster. Applications within a pod have access to shared volumes – helpful for when you need data to persist beyond the lifetime of a pod. Learn more about Kubernetes Pods.
Namespaces
Namespaces are a way to create multiple virtual Kubernetes clusters within a single cluster. Namespaces are normally used for wide scale deployments where there are many users, teams and projects.
Replica Set
A Kubernetes replica set ensures that the specified number of pods in a replica set are running at all times. If one pod dies or crashes, the replica set configuration will ensure a new one is created in its place. You would normally use a Deployment to manage this in place of a Replica Set. Learn more about Kubernetes ReplicaSets.
Deployments
A way to define the desired state of pods or a replica set. Deployments are used to define HA policies to your containers by defining policies around how many of each container must be running at any one time.
Services
Coupling of a set of pods to a policy by which to access them. Services are used to expose containerised applications to origins from outside the cluster. Learn more about Kubernetes Services.
Nodes
A (normally) Virtual host(s) on which containers/pods are run.
Kubernetes architecture and components
A K8S cluster is made of a master node, which exposes the API, schedules deployments, and generally manages the cluster. Multiple worker nodes can be responsible for container runtime, like Docker or rkt, along with an agent that communicates with the master.
Master components
These master components comprise a master node:
- Kube-apiserver. Exposes the API.
- Etcd. Key value stores all cluster data. (Can be run on the same server as a master node or on a dedicated cluster.)
- Kube-scheduler. Schedules new pods on worker nodes.
- Kube-controller-manager. Runs the controllers.
- Cloud-controller-manager. Talks to cloud providers.
Node components
- Kubelet. Agent that ensures containers in a pod are running.
- Kube-proxy. Keeps network rules and perform forwarding.
- Container runtime. Runs containers.
What benefits does Kubernetes offer?
Out of the box, K8S provides several key features that allow us to run immutable infrastructure. Containers can be killed, replaced, and self-heal automatically, and the new container gets access to those support volumes, secrets, configurations, etc., that make it function.
These key K8S features make your containerized application scale efficiently:
- Horizontal scaling.Scale your application as needed from command line or UI.
- Automated rollouts and rollbacks.Roll out changes that monitor the health of your application—ensuring all instances don’t fail or go down simultaneously. If something goes wrong, K8S automatically rolls back the change.
- Service discovery and load balancing.Containers get their own IP so you can put a set of containers behind a single DNS name for load balancing.
- Storage orchestration.Automatically mount local or public cloud or a network storage.
- Secret and configuration management.Create and update secrets and configs without rebuilding your image.
- Self-healing.The platform heals many problems: restarting failed containers, replacing and rescheduling containers as nodes die, killing containers that don’t respond to your user-defined health check, and waiting to advertise containers to clients until they’re ready.
- Batch execution.Manage your batch and Continuous Integration workloads and replace failed containers.
- Automatic binpacking.Automatically schedules containers based on resource requirements and other constraints.
What won’t Kubernetes do?
Kubernetes can do a lot of cool, useful things. But it’s just as important to consider what Kubernetes isn’t capable of:
- It does not replace tools like Jenkins—so it will not build your application for you.
- It is not middleware—so it will not perform tasks that a middleware performs, such as message bus or caching, to name a few.
- It does not care which logging solution is used. Have your app log to stdout, then you can collect the logs with whatever you want.
- It does not care about your config language (e.g., JSON).
K8s is not opinionated with these things simply to allow us to build our app the way we want, expose any type of information and collect that information however we want.
Kubernetes competitors
Of course, Kubernetes isn’t the only tool on the market. There are a variety, including:
- Docker Compose—good for staging but not production-ready.
- Nomad—allows for cluster management and scheduling but it does not solve secret and config management, service discover, and monitoring needs.
- Titus—Netflix’s open-source orchestration platform doesn’t have enough people using it in production.
Overall, Kubernetes offers the best out-of-the-box features along with countless third-party add-ons to easily extend its functionality.
Getting Started with Kubernetes
Typically, you would install Kubernetes on either on premise hardware or one of the major cloud providers. Many cloud providers and third parties are now offering Managed Kubernetes services however, for a testing/learning experience this is both costly and not required. The easiest and quickest way to get started with Kubernetes in an isolated development/test environment is minikube.
How to install Kubernetes
Installing K8S locally is simple and straightforward. You need two things to get up and running: Kubectl and Minikube.
- Kubectl is a CLI tool that makes it possible to interact with the cluster.
- Minikube is a binary that deploys a cluster locally on your development machine.
With these, you can start deploying your containerized apps to a cluster locally within just a few minutes. For a production-grade cluster that is highly available, you can use tools such as:
Minikube allows you to run a single-node cluster inside a Virtual Machine (typically running inside VirtaulBox). Follow the official Kubernetes documentation to install minikube on your machine..
With minikube installed you are now ready to run a virtualised single-node cluster on your local machine. You can start your minikube cluster with;
$ minikube start
Interacting with Kubernetes clusters is mostly done via the kubectl CLI or the Kubernetes Dashboard. The kubectl CLI also supports bash autocompletion which saves a lot of typing (and memory). Install the kubectl CLI on your machine by using the official installation instructions.
To interact with your Kubernetes clusters you will need to set your kubectl CLI context. A Kubernetes context is a group of access parameters that defines which users have access to namespaces within a cluster. When starting minikube the context is automatically switched to minikube by default. There are a number of kubectl CLI commands used to define which Kubernetes cluster the commands execute against.
$ kubectl config get-context $ kubectl config set-context <context-name>
$ Kubectl config delete-context <context-name>
Deploying your first containerised application to Minikube
So far you should have a local single-node Kubernetes cluster running on your local machine. The rest of this tutorial is going to outline the steps required to deploy a simple Hello World containerised application, inside a pod, with an exposed endpoint on the minikube node IP address. Create the Kubernetes deployment with;
$ kubectl run hello-minikube --image=k8s.gcr.io/
echoserver:1.4 --port=8080
We can see that our deployment was successful so we can view the deployment with;
$ kubectl get deployments
Our deployment should have created a Kubernetes Pod. We can view the pods running in our cluster with;
$ kubectl get pods
Before we can hit our Hello World application with a HTTP request from an origin from outside our cluster (i.e. our development machine) we need to expose the pod as a Kubernetes service. By default, pods are only accessible on their internal IP address which has no access from outside the cluster.
$ kubectl expose deployment hello-minikube --
type=NodePort
Exposing a deployment creates a Kubernetes service. We can view the service with:
$ kubectl get services
When using a cloud provider you would normally set —type=loadbalancer to allocate the service with either a private or public IP address outside of the ClusterIP range. minikube doesn’t support load balancers, being a local development/testing environment and therefore —type=NodePort uses the minikube host IP for the service endpoint. To find out the URL used to access your containerised application type;
$ minikube service hello-minikube -—url
Curl the response from your terminal to test that our exposed service is reaching our pod.
$ curl http://<minikube-ip>:<port>
Now we have made a HTTP request to our pod via the Kubernetes service, we can confirm that everything is working as expected. Checking the the pod logs we should see our HTTP request.
$ kubectl logs hello-minikube-c8b6b4fdc-sz67z
To conclude, we are now running a simple containerised application inside a single-node Kubernetes cluster, with an exposed endpoint via a Kubernetes service.
Minikube for learning
Minikube is great for getting to grips with Kubernetes and learning the concepts of container orchestration at scale, but you wouldn’t want to run your production workloads from your local machine. Following the above you should now have a functioning Kubernetes pod, service and deployment running a simple Hello World application.
From here, if you are looking to start using Kubernetes for your containerized applications, you would be best positioned looking into building a Kubernetes Cluster or comparing the many Managed Kubernetes offerings from the popular cloud providers.
Additional resources
For more on Kubernetes, explore these resources:
- Kubernetes Guide, with 20+ articles and tutorials
- BMC DevOps Blog
- The State of Kubernetes in 2020 | https://www.bmc.com/blogs/what-is-kubernetes | CC-MAIN-2021-49 | refinedweb | 2,331 | 55.34 |
Truncating Long File Names and Displaying an Ellipses
This function truncates a file path to fit within a given pixel width by replacing path components with ellipses.
BOOL PathCompactPath( HDC hDC, LPTSTR lpszPath, UINT dx );
- Returns TRUE if successful, or FALSE otherwise.
- hDC
- Handle to the device context used for font metrics.
- lpszPath
- Address of the string to be modified.
- dx
- Width, in pixels, that the string will be forced to fit within.
This function uses the font currently selected in hDC to calculate the width of the text. This function will not compact the path beyond the base file name preceded by ellipses.
Example
#include <windows.h> #include <iostream.h> #include "Shlwapi.h" HDC hdc; /* display DC handle for current font metrics */ void main( void ) { // String path name 1. char buffer_1[] = "C:\\path1\\path2\\sample.txt"; char *lpStr1; lpStr1 = buffer_1; // String path name 2. char buffer_2[] = "C:\\path1\\path2\\sample.txt"; char *lpStr2; lpStr2 = buffer_2; // String path name 3. char buffer_3[] = "C:\\path1\\path2\\sample.txt"; char *lpStr3; lpStr3 = buffer_3; // String path name 4. char buffer_4[] = of ExampleThe un-truncated path is C:\path1\path2\sample.txt
The truncated path at 125 pixels is : C:\path1\...\sample.txt
The truncated path at 120 pixels is : C:\pat...\sample.txt
The truncated path at 110 pixels is : C:\p...\sample.txt
The truncated path at 25 pixels is : ...\sample.txt
long path toolPosted by derikogay on 01/28/2014 05:47am
Well, you can use Long Path Tool for such problems,it works good I will say.Reply
Same can be done without shlwapi.dllPosted by Legacy on 03/14/2000 12:00am
Originally posted by: Peter Ritchie
Both DrawText and DrawTextEx support the DT_PATH_ELLIPSIS flag that allows truncation of a path to fit a specific width (or rectangle) in much the same was a described in this article.Reply
am i missing something here ?Posted by Legacy on 08/02/1999 12:00am
Originally posted by: Gunnar Bolle
or isn't that just the help article for PathCompactPath from the MSDN Library ?Reply
IMO submitting KB or help articles from MSDN library isn't very helpfull - especially if you forget to mention that this function only works with ie 4 installed. (95/NT) | http://www.codeguru.com/cpp/misc/misc/fileanddirectorynaming/article.php/c339/Truncating-Long-File-Names-and-Displaying-an-Ellipses.htm | CC-MAIN-2015-32 | refinedweb | 374 | 68.06 |
Today's lab will focus on open data, using main(), and using Python from the command line.
Software tools needed: web browser and Python IDLE programming environment with the pandas and matplotlib packages installed.
See Lab 1 for details on using Python, Gradescope, and Blackboard.
Much of the data collected by city agencies is publicly available at NYC Open Data. Let's use pandas to plot some data from NYC OpenData. Below is a graph of the total number of individuals in New York City's shelter system from 2010 to 2016:
We'll start by downloading data that has the daily number of families and individuals residing in the Department of Homeless Services (DHS) shelter system:
Click on the "Explore Data/View Data" button. To keep the data set from being very large (and avoid some missing values in 2014), we are going filter the data to be all counts after January 1, 2017. To do this:
Move your CSV file to the directory that you save your programs. Open with Calc (the built-in spreadsheet program for Ubuntu Linux running on the lab machines), Excel, or your favorite spreadsheet program to make sure it downloaded correctly. Look at the names of the columns since those will correspond to series we can plot.
Now, we can write a (short) program to display daily counts:
import pandas as pd import matplotlib.pyplot as plt homeless = pd.read_csv("DHS_Daily_Report.csv") homeless.plot(x = "Date of Census", y = "Total Individuals in Shelter") plt.show()The program above assumes that you saved you data as DHS_Daily_Report.csv. If you saved the data under a different name, alter the program above to use that file. Save your program and try on your dataset.
Once you have completed the above, see the Programming Problem List.
Python allows you to write programs as scripts: basically, a list of commands that are executed one after the other. You can also organize the programs in functions, which groups commands together that can be reused. Many programming languages (like C++ or Java) require that your programs be organized in functions.
To define function in Python, we use the def command, which has the basic form:
def myFunction(input1, input2, ...): command1 command2 ...Note that everything indented below the def line is considered part of the function. When you type the function name (followed by parenthesis), it calls (or "invokes") the function, which means it executes all the commands, one after another, that are part of the function.
Let's rewrite our first program, using functions. By tradition (and since it matches the naming protoccol of C & C++), we will call our function main() (see Section 6.7: Using a Main Function):
#Name: your name here #Date: October 2017 #This program, uses functions, says hello to the world! def main(): print("Hello, World!") if __name__ == "__main__": main()In Python, we have the option of running our programs as a standalone program, or included as module as part of another program. Since it's common to do either, we include the last two lines of the file, which say if the program is being run directly (which we can test to see if the variable __name__ that is set by Python is __main__), then we call main(). If it's not, then the file is being included in something else, and leaves it to that program to call it.
Save your program and try running it in IDLE.
Now, at the prompt (the window with the lines beginning with >>>), type main(). This calls the function directly. Note that calling the function either way results in the same actions: the commands inside main() are executed.
When you have a running version, see the Programming Problem List.
In addition to IDLE (and other development environments with graphical interfaces), Python can also be used directly from the command line. In fact, this is what the grading scripts do to evaluate your programs, since Gradescope uses a remote cloud server and does not have a graphics window.
To start, we need a command line interface (aka a terminal window). To launch the terminal, click on the terminal window icon in the left menu, or go to search option in the upper left corner and type and then open terminal.
In Lab 1, we launched IDLE from the terminal by typing:
$ idle3
We can use Python in a similar fashion. In a terminal window, change directories to where you stored your hello program above (see Lab 4 for changing directories at the command line).
Let's run your hello program from the command line. If your program is called hello.py, you would type at the command line:
$ python3 hello.pyNotice that the output goes directly to the terminal window. Try running other programs you have written. | https://stjohn.github.io/teaching/csci127/s19/lab7.html | CC-MAIN-2021-43 | refinedweb | 800 | 62.88 |
The C (and C++) preprocessor is a powerful but dangerous tool. For sure, it helps with a number of problems, from conditional code inclusion to explicit code generation, but it has a few problems. In fact, more than a few. It is evil.
The C preprocessor (hereafter CPP) should be used with extreme care. For one thing, the CPP doesn’t know about the language it is applied on, it merely proceeds to the translation of the input using very simple rules, and this can leads to tons of hard to detect—and to fix—problems.
There are at least two problems I can think of that renders the use of macros as function dangerous and annoying. The first is that since the CPP is basically a big find-and-replace machine, it is not particularly smart on how macros are expanded. The second is that since the CPP is basically a big find-and-replace machine, it’s not particularly smart on when macros are expanded.
Macro used as function are declared like this:
#define function(arg1,arg2) ...stuff with arg1 and arg2...
(and the number of arguments can vary, but two is a good example) and are invoked:
y = function(x+3,4);
As would be a normal function most of the times. The problem is, they’re not functions, they’re merely textual substitution patterns. The above will textually replace the values for arg1 and arg2 in the macro body and paste it at invocation point. The expansion is so basic that in most case, you will need to use extra parentheses to make sure that operation precedence is respected. For example:
#define function(arg1,arg2) arg1 + arg2 ... x=function(x << 3, 5)
will result in bad behaviour: the operator<< has a lower priority than +, so you’ll end up with x << (3+5) rather than the expected (x<<3)+5. The correct way is to define:
#define function(arg1,arg2) ( (arg1) + (arg) )
So to force the correct precedence of evaluation in the final expression.
This is a somewhat simple case and any programmer that had his fingers bitten once by that kind of bug knows to put parentheses and that’s about it. However, if adding extra parentheses helps with operator precedence, it has another problem. Consider:
#define max(a,b) ( (a) > (b) ? (a) : (b) ) ... x=max(a[i++],b[j++])
In this code, you cannot easily predict how many times i++ or j++ are executed. Inspecting the macro expansion, we see that the code is now:
x=( (a[i++])>(b[j++]) ? (a[i++]) : (b[j++]) )
Which isn’t the desired result at all! In short, macro used as functions are evil. Because macro expansion is dumb, arguments may be evaluated any number of times. Because macro expansion is dumb, arguments may be evaluated in any order and maybe their expressions will be merged with another expression to yield an unexpected result—as in the shift example above.
*
* *
The other major problem with the CPP is that it doesn’t understand scoping or namespaces. For example, the following code spews compilation errors:
... #define max(a,b) ... ... class A { private: int a,b; ... public: int max() const { ... } // clearly a member function ... }
Because max() looks like a function, the CPP tries to match it with a macro and the compiler complains that macro.cpp:19:12: error: macro "max" requires 3 arguments, but only 1 given (why one and not zero? I don’t know! That’s what G++ returns). Even a non-function macro can be worth a lot of problems:
#define shift 3 int function( int a, int b) { int shift=0; // clearly a local variable ...more code... } ...
This time, it complains with:
macro.cpp:28: error: expected unqualified-id before numeric constant
Which is somewhat cryptic.
The same happens with namespaces. Qualifying a symbol with an explicit namespace doesn’t stop the CPP to expand macros whenever there’s something that looks like a match:
#include <algorithm> #include <iostream> #define max(a,b,c) ...stuff... // ...lot more code goes here... int main() { int a=0; int b=3; std::cout << std::max(a,b) // clearly NOT the macro << std::min(a,b) << std::endl; }
The CPP replaces the macro max( ) but the compiler encounters errors:
macro.cpp:12:28: error: macro "max" requires 3 arguments, but only 2 given macro.cpp: In function ‘int main()’: macro.cpp:12: error: no match for ‘operator<<’ in ‘std::cout << std::max’ -- follows 20 more lines of error --
*
* *
The first solution is to avoid macro as much as possible. In C++, prefer template and inline functions to macros used as functions. The first advantage of using a true function is that the arguments are evaluated only once. For example, if the macro arguments contains code that has a side effect (like i++, for example) it is not easy to predict how many times it will be executed in the expanded statement.
Inline functions (available in C++ and C99, and in C as a compiler-specific extension) solve all problems of macro as functions. First, they ensure that the parameters are evaluated only once. Second, they offer the complete function semantics which aren’t all available with macros. For example, you can’t build a local scope and return a value with a macro in a clean way. Third, they are always syntactically safe, yet another thing that is not ensured by macros, especially when used in compound statements.
The fact that inline functions are functions and may require an actual function call if the compiler can’t inline the functions should really not stop you from using them. First, if the function is big enough so that the compiler can’t (or wont) inline it, you certainly don’t want it as a macro. Second, the time for a function call is dominated by the time it takes to evaluate the arguments, so it is eventually negligible.
*
* *
Since not all code bases seems to be aware of the problem inherent to the CPP, you may have to deal with stupid macro names—even include guards. Paradoxically, a macro named max is a lot more stupid than a macro named my_max_macro, as it more likely to interfere with user code than the latter. The defencive solution to this problem is to undefine macros known to cause problems:
#include <some-header> #ifdef max #warning 'max' is defined as a macro. Undefining. #undef max #endif ...more code...
Or you can simply #undef it quietly. I do prefer warnings, because it informs the programmer/maintainer that this was deliberate and that he should not expect the macro max to be available in this translation unit.
The proactive solution is to use smarter names for macros. You can of course use BIG_UGLY_CAPS for macros, but you can also use the underscore to specify that this is a compiler- or library-specific symbol, as suggested by the standards. The macro _max is already much better than just max, even though it may still interfere with some naming conventions. Note that double underscores are
reserved recommended mandatory for compiler-specific extensions such as __attribute__ and the like. A macro named __max__ would imply that the macro is somehow special and compiler-specific.
*
* *
So, basically, the CPP is a good tool for testing the environment, check for defined macros, and for conditional compilation but a very, very, very bad tool for code generation. I can understand that it is tempting to use macros in C (and C99) as a weak substitute for meta-programming as there are really no facilities provided by the language.
In C++, however, we have all the tools needed: function and operator overloading, and powerful meta-programming through templates. The careful use of C++ meta-programming can lead to very efficient, compile-time optimized code.
Well, double underscores are actually reserved.
ISO/IEC 9899:1999 states, § 6.10.8 ¶ 4 :
Which states the rule in one direction (if predefined) then (has underscores), and not “if, and only if”. Elsewhere, § 7.1.3 ¶ 1 enumerates the uses of _ (followed by a capital letter) or __ : they can be used as part of an identifier, as long as they are used as would-be reserved symbols; the gist of which is explained in note 157, at the foot of p.181. The way I understand it is that a symbol that begins by _ or __ should be a reserved-looking symbol, at least in some compiler- or library-specific way. This includes, I would guess, include guards and library extensions such as _strdup.
§ 7.1.4 explains how to use and short-cut macros (namely the use of parenthesis around problematic symbols; in our example, we would have to write (max)(a,b) everywhere, which is still cumbersome).
Annex J.2 states that undefining a macro beginning in _ or __ may result in undefined behavior (p. 510).
Annex J.5.2 states (p.511), again, that compiler- or library-specific extensions (such as new keywords, pragma-looking directives, etc.) should begin by at least one underscore. Something similar is found in annex J.5.12 as well (p. 512)
So my interpretation is that compiler- and library-specific macros must be implementation-specific looking by begining by _ or __; that undefining an implementation-specific looking symbol begining by _ or __ is risky and may result in implementation-specific behavior (i.e., “undefined behavior”). And, lastly, the rule is rather one way: you may define yourself implementation-specific looking symbols using _ or __; and if you do define such symbols, you MUST use _ or __.
Even though we’re also using the CPP in C++, the rules are somewhat a bit different for names, see the following section of 14882:2003
17.4.3.1.2 Global names [lib.
Nice article, thanks :)
There’s also ISO/IEC 14882:2003 § 17.4.3.1.3 ¶ 1 that’s new to me:
Each name having two consecutive underscores (2.11) is reserved to the implementation for use as a name with both extern "C" and extern "C++" linkage.
However, does it mean my__function or __my_function? both?
Probably both, despite the fact that only second will be reserved in C. Yet another example of C++’s “compatibility” with C.
Don’t blame me for my English, I’m Polish ;)
Oh, your English is quite good.
Yes, the fact that C and C++ are somewhat compatible (and, contrary to what many people think, C++ is not a superset of C, C has new stuff that isn’t in C++) is still a (small) source of problems. g++, for example, has a number of extensions to accommodate C99 constructs that haven’t made their way into the C++ standard.
[…] the CPP Evil?. Yes. Worse, it still doesn’t solve the problem! Consider the following code […]
[…] are EVIL (part II) In a previous post I discussed some aspects of the C preprocessor (hereafter the CPP) that are evil. Turns out that […] | https://hbfs.wordpress.com/2009/11/17/defines-are-evil/ | CC-MAIN-2017-22 | refinedweb | 1,836 | 63.09 |
Bit twiddling: Simple O(1) membership test
Disclaimer
Bit twiddling is fun. Plus, it has several advantages:
It gives you a greater understanding of the nuances of the (C) language. As we all know, learning C is important. If you're a computer engineer and have weak C-fu, then it is time, grasshopper.
Bit twiddling is important to know if you're ever going to write software in the field of computer engineering. Without a good understanding of how to slice-and-dice primitive data types, your simulations will be significantly more prone to error. Trust me, you don't want to use gdb for hours only to find that your shift value was off by one. Not that I've ever done that.
It makes you feel smart, like when you're the only person who knows the secret to your party trick. I don't know what that's like personally, of course, because I spend all my party time bit bashing, but I hear it's similar.
You have to understand, though, that clever tricks without appropriate documentation will make people want to break your face. [*] Always bit bash responsibly: appoint a designated code-reader to make sure you're clear enough, and leave your keys at the door.
The Problem
Let's say you wanted to know whether a number was a valid PCI Express link width in terms of number of lanes. We know that valid widths are x1, x2, x4, x8, x12, x16, or x32, and want to construct a function of the following form:
#include <stdbool.h> #include <stdint.h> #include <assert.h> /** * :return: Whether the lane count is valid. */ bool is_valid_link_width(uint8_t lane_count); /** * Unit test for ``is_valid_link_width``. */ int main(int argc, char **argv) { assert(!is_valid_link_width(0)); assert(is_valid_link_width(1)); assert(is_valid_link_width(2)); assert(!is_valid_link_width(3)); assert(is_valid_link_width(32)); assert(!is_valid_link_width(33)); assert(!is_valid_link_width(33)); assert(!is_valid_link_width(0xff)); return 0; }
Note that the uint8_t has a width of exactly 8 bits. [†]
How would you write it?
Less Interesting Solution
If you were thinking switch statement, that will work. You could use a switch statement with intentional fall-throughs and hope that the compiler optimizes a branch table for you. (For values this small and dense it probably will, as mentioned in the referenced article.) If the compiler doesn't write the branch table for you, but instead generates the equivalent of a big if/else if ladder, your solution doesn't satisfy the O(1) constraint: in that case, the worst case control flow hits every rung of the ladder (the else if guards), making it O(n).
bool is_valid_link_width(uint8_t lane_count) { switch (lane_count) { case 1: case 2: case 4: case 8: case 12: case 16: case 32: return true; } return false; }
An implementation that I like better, which doesn't put as much faith in the compiler, is as follows:
bool is_valid_link_width(uint8_t lane_count) { return 0x100011116ULL & (1ULL << lane_count); }
How cool is that?
The Neat Trick
The clever insight here is that we can encode all of our target "true" values in binary form, like so:
32 16 12 8 4 1 0b__0001__0000__0000__0000__0001__0001__0001__0001__0110
Now, if we were to take a 1 value and move it over a number of binary slots equal to the lane count, it will line up with a 1 value in this long binary number we've constructed. Take the bitwise-AND of those two values, and we wind up with:
A non-zero (true) value if they line up, OR
A zero value if they don't
This is exactly what we were looking for.
This long binary number we've created must be converted from binary into a hexadecimal value, so that we can represent it as an integer literal in our C program. Encoding each binary 4-tuple into hex from right to left, we get the value 0x100011116.
There's an issue with this value, however. Unless we specify a suffix for our integer literal, the compiler is allowed to truncate the value to its native word size, [‡] which would cause serious problems. For x86 systems with 16 bit words, our value could be truncated to 0x1116, which would only allow lane sizes of 1, 2, 4, 8, and 12 — the allowed values of 16 and 32 would be cut off!
To solve this, as you can see in the function definition, we add the ULL integer suffix, which explicitly marks the integer literal as an unsigned long long. (The long long integer data type was added to the C language in the C99 standard.) This data type is required to be at least 64 bits wide, so it can definitely hold our 33 relevant bits (32 plus the zero bit which is there for the 1ULL << 0 case). The long data type is too small to hold this value, as long can potentially be only 32 bits wide per the C standard (and it is 32 bits wide on most modern machines).
Readability Counts
Note that there's a more readable version of the same trick in the following:
bool is_valid_link_width(uint8_t lane_count) { const uint64_t set = 1ULL << 1 | 1ULL << 2 | 1ULL << 4 | 1ULL << 8 | 1ULL << 12 | 1ULL << 16 | 1ULL << 32; return set & (1ULL << lane_count); }
Here we make the construction of the big integer more explicit and make the code less prone to our errors in encoding the literal binary value into hex. Any compiler worth its salt will fold out the const calculation at compile time, so no overhead will be incurred for writing it this way.
I demonstrated the other way of doing it first to: a) blow your mind a little bit, and b) demonstrate an idiom you might see in other people's (overly) clever code. Now there's a chance you can recognize and decipher it without adequate documentation. Huzzah! | http://blog.cdleary.com/2009/04/bit-twiddling-simple-o1-membership-test/ | CC-MAIN-2017-30 | refinedweb | 971 | 66.78 |
Ticket #469 (closed Bugs: fixed)
multitoken broken
Description
Due to the changes in the parser, multitoken is broken in program_options [boost 1.33]. Looking at the code it is relatively clear why - the parser is too "greedy" and eats up all the options following the multitoken one without checking when to stop (for example, it should stop once it encounters another option/switch). If this functionality is to be deprecated as hinted in some mails on the mailing list, it should be removed from the public interface. If not, I guess it should be fixed :) The way to test it is to have a multitoken switch appear _in the middle_ of the command line (definitely not at the end) which should then simply eat all options to the right of it.
Attachments
Change History
comment:2 Changed 10 years ago by vladimir_prus
- Summary changed from multitoken broken in program_options 1.33 to multitoken broken
- Severity set to Problem
- Milestone set to Boost 1.35.0
Confirmed as a problem. The solution to be decided.
comment:3 Changed 10 years ago by anonymous
Given the following program_options description:
std::vector<std::string> multiItems; program_description desc; desc.add_options() ("multi", value<>(&multiItems)->multitoken(), "..."); ....
Would we expect the command line: "myProgram --multi foo bar" to add two entries (foo and bar) into 'multiItems'?
It currently (1.34) doesn't; bar gets lost. I can understand that this could be tricky, especially if positional options are also being used.
If multitoken was never designed for this purpose, then currently the way to achieve the desired effect is to overload 'validate'. However, this is only necessary because of the use of 'lexical_cast' in the current validate implementations.
To illustrate:
typedef std::pair<int int> PairOfInts; PairOfInts pairOfInts; program_description desc; desc.add_options() ("pair", value<>(&pairOfInts), "..."); ....
With command line: "myProgram --pair 1 2":
The current 'validate' code will stream (via lexical_cast) the string "1 2" into lexical_stream, then stream it out to the value type, i.e. the std::pair.
The problem there is that the stream-out of the string will only take the "1" part, so when it attempts to stream it back in, only one value is presented.
If we had provided a stream operator for our pair:
std::istream& operator>>(std::istream &a_istr, PairOfInts &a_pair) { a_istr >> a_pair.first >> a_pair.second; return a_istr; }
Then an exception would fire trying to get the second value.
The 'validate' code has a vector of strings, but only the first entry is filled.
If the current (detail/value_semantic.hpp) validate code:
template<class T, class charT> void validate(boost::any& v, const std::vector< std::basic_string<charT> >& xs, T*, long) { validators::check_first_occurrence(v); std::basic_string<charT> s(validators::get_single_string(xs)); try { v = any(lexical_cast<T>(s)); } catch(const bad_lexical_cast&) { boost::throw_exception(invalid_option_value(s)); } }
Was adjusted to not use lexical_cast, e.g.:
template<class T, class charT> void validate(boost::any& v, const std::vector< std::basic_string<charT> >& xs, T*, long) { validators::check_first_occurrence(v); std::basic_string<charT> s(validators::get_single_string(xs)); std::istringstream istr(s); T value; if (!(istr >> value) { boost::throw_exception(invalid_option_value(s)); } v = value; }
Then more complex types could be supported just by providing the stream-in operator, rather than overloaded 'validate's (that seem to have to go in namespace boost, too).
comment:4 Changed 8 years ago by anonymous
- Status changed from assigned to new
- Version changed from None to Boost 1.38.0
- Component changed from config to program_options
- Severity changed from Problem to Showstopper
- Milestone changed from Boost 1.36.0 to To Be Determined
This multitoken bug has been broken and reported as a bug for 4 years now and not addressed. Is the author/supported not planning on ever fixing it? I'm stuck on boost 1.32 just because of this one bug.
comment:5 Changed 8 years ago by vladimir_prus
- Status changed from new to closed
- Resolution changed from None to fixed | https://svn.boost.org/trac/boost/ticket/469 | CC-MAIN-2017-09 | refinedweb | 652 | 54.32 |
import "github.com/elves/elvish/pkg/cli/apptest"
Package apptest provides utilities for testing cli.App.
Initial size of fake TTY.
var Styles = ui.RuneStylesheet{ '_': ui.Underlined, '*': ui.Stylings(ui.Bold, ui.FgWhite, ui.BgMagenta), '+': ui.Inverse, '/': ui.FgBlue, '#': ui.Stylings(ui.Inverse, ui.FgBlue), '!': ui.FgRed, '?': ui.BgRed, '-': ui.FgMagenta, 'X': ui.Stylings(ui.Inverse, ui.FgMagenta), 'v': ui.FgGreen, 'V': ui.Stylings(ui.Underlined, ui.FgGreen), '$': ui.FgMagenta, }
Common stylesheet.
StartReadCode starts the given function asynchronously. It returns two channels; when the function returns, the return values will be delivered on those two channels and the two channels will be closed.
WithSpec takes a function that operates on *cli.AppSpec, and wraps it into a form suitable for passing to Setup.
WithTTY takes a function that operates on TTYCtrl, and wraps it to a form suitable for passing to Setup.
Fixture is a test fixture.
Setup sets up a test fixture. It contains an App whose ReadCode method has been started asynchronously.
MakeBuffer is a helper for building a buffer. It is equivalent to term.NewBufferBuilder(width of terminal).MarkLines(args...).Buffer().
Stop stops ReadCode and waits for it to finish. If ReadCode has already been stopped, it is a no-op.
TestTTY is equivalent to f.TTY.TestBuffer(f.MakeBuffer(args...)).
TestTTYNotes is equivalent to f.TTY.TestNotesBuffer(f.MakeBuffer(args...)).
Wait waits for ReaCode to finish, and returns its return values.
TTYCtrl is an interface for controlling a fake terminal.
GetTTYCtrl takes a TTY and returns a TTYCtrl and true, if the TTY is a fake terminal. Otherwise it returns an invalid TTYCtrl and false.
NewFakeTTY creates a new FakeTTY and a handle for controlling it. The initial size of the terminal is FakeTTYHeight and FakeTTYWidth.
Returns the last recorded buffer.
BufferHistory returns a slice of all buffers that have appeared.
EventCh returns the underlying channel for delivering events.
Inject injects events to the fake terminal.
InjectSignal injects signals.
LastBuffer returns the last buffer that has appeared.
NotesBufferHistory returns a slice of all notes buffers that have appeared.
RawInput returns the argument in the last call to the SetRawInput method of the TTY.
Returns next event from t.eventCh.
Records a nil buffer.
Records the argument.
SetSetup sets the return values of the Setup method of the fake terminal.
SetSize sets the size of the fake terminal.
Delegates to the setup function specified using the SetSetup method of TTYCtrl, or return a nop function and a nil error.
Returns the size specified by using the SetSize method of TTYCtrl.
Closes eventCh.
TestBuffer verifies that a buffer will appear within the timeout of 4 seconds, and fails the test if it doesn't
TestNotesBuffer verifies that a notes buffer will appear within the timeout of 4 seconds, and fails the test if it doesn't
UpdateBuffer records a new pair of buffers, i.e. sending them to their respective channels and appending them to their respective slices.
Package apptest imports 8 packages (graph). Updated 2020-02-22. Refresh now. Tools for package owners. | https://godoc.org/github.com/elves/elvish/pkg/cli/apptest | CC-MAIN-2020-16 | refinedweb | 507 | 61.93 |
Code covered by the BSD License
4.96
by
James Tursa
30 Nov 2009
(Updated
23 Feb 2011)
Beats MATLAB 300% - 400% in some cases ... really!
|
Watch this File
MTIMESX is a fast general purpose matrix and scalar multiply routine that has the following features:
- Supports multi-dimensional (nD, n>2) arrays directly
- Supports Transpose, Conjugate Transpose, and Conjugate pre-operations
- Supports singleton expansion
- Utilizes BLAS calls, custom C loop code, or OpenMP multi-threaded C loop code
- Can match MATLAB results exactly or approximately as desired
- Can meet or beat MATLAB for speed in most cases
MTIMESX has six basic operating modes:
- BLAS: Always uses BLAS library calls
- LOOPS: Always uses C loops if available
- LOOPSOMP: Always uses OpenMP multi-threaded C loops if available
- MATLAB: Fastest BLAS or LOOPS method that matches MATLAB exactly (default)
- SPEED: Fastest BLAS or LOOPS method even if it doesn't match MATLAB exactly
- SPEEDOMP: Fastest BLAS, LOOPS, or LOOPOMP method even if it doesn't match MATLAB exactly
MTIMESX inputs can be:
single
double
double sparse
The general syntax is (arguments in brackets [ ] are optional):
mtimesx( [directive] )
mtimesx( A [,transa] ,B [,transb] [,directive] )
Where transa, transb, and directive are the optional inputs:
transa = A character indicating a pre-operation on A:
transb = A character indicating a pre-operation on B:
The pre-operation can be any of:
'N' or 'n' = No pre-operation (the default if trans_ is missing)
'T' or 't' = Transpose
'C' or 'c' = Conjugate Transpose
'G' or 'g' = Conjugate (no transpose)
directive = One of the modes listed above, or other directives
Examples:
C = mtimesx(A,B) % performs the calculation C = A * B
C = mtimesx(A,'T',B) % performs the calculation C = A.' * B
C = mtimesx(A,B,'g') % performs the calculation C = A * conj(B)
C = mtimesx(A,'c',B,'C') % performs the calculation C = A' * B'
mtimesx('SPEEDOMP','OMP_SET_NUM_THREADS(4)') % sets SPEEDOMP mode with number of threads = 4
For nD cases, the first two dimensions specify the matrix multiply involved. The remaining dimensions are duplicated and specify the number of individual matrix multiplies to perform for the result. i.e., MTIMESX treats these cases as arrays of 2D matrices and performs the operation on the associated parings. For example:
If A is (2,3,4,5) and B is (3,6,4,5), then
mtimesx(A,B) would result in C(2,6,4,5), where C(:,:,i,j) = A(:,:,i,j) * B(:,:,i,j), i=1:4, j=1:5
which would be equivalent to the MATLAB m-code:
C = zeros(2,6,4,5);
for m=1:4
for n=1:5
C(:,:,m,n) = A(:,:,m,n) * B(:,:,m,n);
end
end
The first two dimensions must conform using the standard matrix multiply rules taking the transa and transb pre-operations into account, and dimensions 3:end must match exactly or be singleton (equal to 1). If a dimension is singleton then it is virtually expanded to the required size (i.e., equivalent to a repmat operation to get it to a conforming size but without the actual data copy). This is equivalent to a bsxfun capability for matrix multiplication.
This file inspired Mmx Multithreaded Matrix Operations On N D Matrices, Small Size Linear Solver, Frontal, and Merton Structural Credit Model (Matrixwise Solver).
From my understanding, the file "mex_C_win64.xml" replaces "mexopts.bat".
"Error using mtimesx_build (line 169)
A C/C++ compiler has not been selected with mex -setup". I replaced line 169 by : mexopts = [prefdir '\mex_C_win64.xml'];. It did work with a few warnings...
Thanks, James. This thread describes where the information has moved to
I can post those xml files somewhere, if you like. However, is there no way to get mtimesx to compile simply with the "mex" command, maybe with a small sacrifice in performance?
Hmmm ... Well, I don't have access to R2014 so I will have to code in the blind on this. My understanding is that MATLAB will in real time make a guess as to the correct compiler to use based on source code extension. So the information that was in mexopts.bat (user had already selected a compiler) is no longer available for my automatic build stuff. I will put out an update shortly, but may have to ask for info direct from the user for compiler stuff. I will try to get it out there sometime next week.
Thought I'd ping again. It doesn't look like mtimesx_build is compatible with R2014, since it looks for mexopts.bat, which is now gone. Can we hope to get a version that supports R2014? James?
I have the same problem as Safdar in R2014a. Even after running mex -setup, it appears as though mtimesx_build cannot find mexopts.bat. Possibly, the locations of relevant files/directories may have shifted?
Sorry for the multiple posts. It seems something went wrong when submitting the post. Sorry
I got the following message
... Build routine for mtimesx
... Checking for PC
... Finding path of mtimesx C source code files
... Found file mtimesx.c in D:\Documents\Projects\mtimesx_20110223\mtimesx.c
... Found file mtimesx_RealTimesReal.c in D:\Documents\Projects\mtimesx_20110223\mtimesx_RealTimesReal.c
Error using mtimesx_build (line 169)
A C/C++ compiler has not been selected with mex -setup
Error in mtimesx (line 271)
mtimesx_build;
Hi James,
I unzipped the file in my working folder and tries to use mtimesx, I got the following message
Hi James,
I unzipped the folder in my working path and then tried to used mtimesx, I got the following error
@Evan: have you tired blas_lib = 'lmwblas'?
I would like to second Matthieu's question. For blas_lib, I've tried both
blas_lib = '/Applications/MATLAB_R2013b.app/bin/maci64/lapack.spec';
and
blas_lib = '/Applications/MATLAB_R2013b.app/bin/maci64/blas.spec';
With both, I get:
ld: warning: ignoring file /Applications/MATLAB_R2013b.app/bin/maci64/blas.spec, file was built for unsupported file format
Anyone have any ideas?
Works well for me on Linux.
If it can helps, I have installed the library libblas.so in my home following the version "shared library" of this page:
Then I have compiled the mex file with the command return by the mtimesx routine when the automatic installation failed:
blas_lib = 'the_actual_path_and_name_of_your_systems_BLAS_library';
mex('-DDEFINEUNIX','-largeArrayDims','mtimesx.c',blas_lib)
Gained a factor 2 in speed for my 3D matrices multiplications, and a clearer matlab code :)
Hi all,
I tried to locate compliers via mex -setup, but got the answer => No supported SDK or compiler was found on this computer.
I installed Microsoft Windows SDK 7.1 but still not able to work. Does somebody know the path and install directory or what the problem is?
thanks for help
I don't know why, I did the test again in the linux cluster and the windows one, it works in the parallel computation now. So strange!
James, by the way, what version of matlab last time you test this package? I place it in my labtop (windows 64) and linux cluster running matlab 2013, only few operations that mtimesx will beat matlab and it only beat is for less than 10%. I saw that this package was uploaded in 2011 so just wonder if matlab 2013 made lots of change to boost the performance.
@WK: I don't have the parallel toolbox, so am unable to give much advice here. My understanding is that each worker in the parallel environment is a separate process, which I would expect would mean that MTIMESX could be used. But since I don't have the toolbox I can't verify this. Have you actually run some tests and gotten wrong results?
I just get it compiled and installed in my 64-bit matlab with windows SDK7 as well as the unix cluster. I find that it doesn't work in spmd, doesn't it?
Thanks for the great library. I have two questions. Do I have to compile it to get library? So it means the library is really depending on the machine, right? Also, our lab has a multi-node cluster, each node are equipped with 8 cores. I think this library is based on multi-threading, if I run the matlab code in spmd and in each core, I run your library so will it conflict? Sorry, I didn't have any experience in compiling mex before, I tried but I don't have MSVC installed, I only have mingw.
How about announce another function for fast matrix inverse with multi-dimensional support? I wrote a version but I think your version will far fast than mine. :P
Hello,
I'm trying to use mtimesx on mac OS 10.8 with matlab R2011b but I don't understand how to compile it.
I tryed several solutions described in comments but none worked.
blas_lib = '/Applications/MATLAB_R2011b.app/bin/maci64'
blas_lib =
/Applications/MATLAB_R2011b.app/bin/maci64
>> mex('-DDEFINEUNIX','mtimesx.c',blas_lib)
mtimesx.c: In function 'mexFunction':
mtimesx.c:592: warning: assignment discards qualifiers from pointer target type
ld: can't map file, errno=22 for architecture x86_64
collect2: ld returned 1 exit status
mex: link of ' "mtimesx.mexmaci64"' failed.
Error using mex (line 206)
Unable to complete successfully.
Can you help me ?
@Agustin: It looks like you put the files in the lcc compiler directory. I would advise that you put the files in a work directory instead (not any of the "official" sys or bin etc directories that are installed with MATLAB) and try again. Make sure this work directory is on the MATLAB path. As a side note, in general it is *not* a good idea to put your own files into any of the "official" directories that are installed with MATLAB ... doing so risks breaking built-in MATLAB functions and capabilities.
thanks james but i have this problem
Build routine for mtimesx
... Checking for PC
... Finding path of mtimesx C source code files
... Found file mtimesx.c in C:\Program Files\MATLAB\R2008a\sys\lcc\mtimesx\mtimesx.c
... Found file mtimesx_RealTimesReal.c in C:\Program Files\MATLAB\R2008a\sys\lcc\mtimesx\mtimesx_RealTimesReal.c
... Opened the mexopts.bat file in C:\Users\Gusa\AppData\Roaming\MathWorks\MATLAB\R2008a\mexopts.bat
... Reading the mexopts.bat file to find the compiler and options used.
... LCC is the selected compiler
... OpenMP compiler not detected ... you may want to check this website:
... Using BLAS library lib_blas = 'C:\Program Files\MATLAB\R2008a\extern\lib\win32\lcc\libmwblas.lib'
... Now attempting to compile ...
mex('C:\Program Files\MATLAB\R2008a\sys\lcc\mtimesx\mtimesx.c',lib_blas,'-DCOMPILER=LCC')
it can´t find C:\Program Files\MATLAB\R2008a\sys\lcc\mtimesx\mtimesx.exp
it cant´find C:\Program Files\MATLAB\R2008a\sys\lcc\mtimesx\mtimesx.lib
... mex mtimesx.c build completed ... you may now use mtimesx.
then i introduce:
C = mtimesx(a,b)
??? Undefined function or method 'mtimesx' for input arguments of type 'double'.
what can i do?
@Agustin: For Windows, generally you just put all the files in a directory on the MATLAB path and then type mtimesx at the prompt. For other systems, see other posts below.
Hi
How can i introduce this "function" in matlab??
I tried it but i have errors
Sorry for my ignorance
@Tonio: No, MTIMESX does not do this. But from your description it sounds like something like this might work for you:
a = cell array of matrices
b = cell array of vectors
c = cellfun(@mtimes,a,b,'UniformOutput',false)
Can I used that for multiplying an (m,n,k) * (n,k) = (m,k) where each k 'slice' needs to be multiplied together and they may contain variables number of elements, i.e. 'm' can vary in each slice? In my code each slice is stored in a cell in matlab.
@Robert: Yes, MTIMESX is CPU based, not GPU.
Hello James,
nice work. A basically like to multiply n matrices B (400,400) with one Matrix A (400,400). I used arrayfun before, but your code is about 2.5 times faster. Soon I will get a Tesla NVidia graphic card and I would like to ask, is there any possibility to run the calculation on the GPU instead on the CPU?
I tried to call mtimesx with tww GPU Arrays but as my computation times is still fast (on my slow GPU) I guess he was not using my GPU right now.
Perhaps I also missed this, but to my understanding mtimesx is using the CPU only, or??
Thanks
Robert
@Michael Thanks, that did it.
@Sebastian Thanks for the response. I think I wasn't linking to the right file. Now, I seem to be linking to the blas library, but I'm getting a new error. I am using the code "mex -DEFINEUNIX 'mtimesx.c' -lmwblas" but I get an error that reads "mtimesx.c:592: warning: assignment discards qualifiers from pointer target type ". I saw that someone else had gotten this error before and the code was fixed, so I downloaded the files again but I still am getting the error. When I tried to use mtimesx in my code I get an error and matlab crashes. I haven't had any problems with other mex files, so it seems to be specific to mtimesx.
Any help is appreciated. Thanks in advance.
@Charles: under Unix, the BLAS library linked to is normally mwblas , not blas_lib.
This program is great. Really useful. I am having great success with it on my PC. However, I cannot seem to create the mex file on a UNIX computer. I am defining the BLAS library as blas_lib. Then I enter the code "mex('-DDEFINEUNIX','mtimesx.c',blas_lib)". However, I get a string of errors that are all similar to "mtimesx.c;(.text+0x76a1)undefined reference to `saxpy_'". It says this for saxpy, sger, sdot, daxpy, dger, ddot, sgemv,ssyrk, ssyr2k, sgemm, dgemv, dsyrk and dgemm. Can anyone please help me with creating the .mexa64 file? Thanks.
@KSIDHU: Why can't you use .* and ./ directly? What are the exact dimensions of your two matrices? If the matrices need singleton expansion, then look at the function bsxfun. What is the overall operation you are trying to do?
Hi
How can I perform elementwise multiplication and division of two matrices?
I have looked through the manual but cannot find any information on it.
Is there a way to check if BLAS multi-threading is available? Is this better than OpenMP multi-thread
I need to perform .*, ./ on matrices with numel ~3000x100,000 so any tips would be great, and also is there a multi threaded sum function for large matrices (along dim 1 or 2).
MATLAB 2010a
Thanks in advance
KS
I like the reasoning you both have spelled out. I will make logical*other conform to the other, and make logical*logical output a double by default but have an option to do logical AND/OR operations and output a logical instead. Thanks for your inputs.
I like Michael's reasoning and I think he is right about the 'double' result. So in general I think that the double should be the default. However, given that i enjoy being efficient with data, I would appreciate a 'logical' option.
Damn, the E-Mail notification stopped to work, so I didn't know you replied to my message.
My spontaneous thought was that (logical matrix) * (logical matrix) should *of course* result in a double output, since matrix multiplication involves a sum, so we should expect to get results different than 0 or 1.
So, as you already guessed, I would like to have an auto-adjust-precision feature.
This is what I would expect:
[inputA] * [inputB] ==> [output]
------------------------------------------
logical | logical | double
logical | single | single
logical | double | double
single | logical | single
double | logical | double
(I hope it does not get formatted too ugly...)
I also like John's idea to make the behaviour more optional.....
@John: OK, that's two votes. Automatic logical conversion goes into the next version.
Q: Should a (logical matrix) * (logical matrix) give a double matrix result (ala MATLAB), or a logical matrix result (i.e., essentially treating the * - operations as AND OR operations)?
Excellent code!
I experienced the same 'error' as Michael Völker, so I think automatically converting the logical/sparse data to double might be a good idea as an enhancement!
Nevertheless, great work! Saved me a lot of time/coding.
@Michael Völker: The error message you are getting is not a bug. As stated in the doc, using arguments that are not double or single will cause MTIMESX to invoke the built-in mtimes function to do the matrix multiply. If MATLAB will do it then great ... you get that result. But if MATLAB will not do it then you will get whatever error message MATLAB puts out. This is the intended behavior. You can convert the logical to double first, of course, to avoid the error message. If you would like MTIMESX to do this automatically for logical inputs then I can take that as an enhancement request (seems reasonable to me).
James,
I found a bug with logical input.
Try:
foo = mtimesx( true(2,2), randn(1,1,5) );
And you probably get this error message:
Error using *
Inputs must be 2-D, or at least one input must be scalar.
To compute elementwise TIMES, use TIMES (.*) instead.
Error in mtimesx_sparse (line 47)
result = a * b;
James:
I would like to thank you for coming up with such a brilliant piece of work. An excellent and well written code!!
Lately, I have been trying to use MTIMESX code to multiply two big n-dimensional matrices (A = 400x400x400 and B = 400x200). But for simplistic purposes, consider the following example:
A = 3 x 3 x 3
B = 3 x 2
and C = A*B;
such that dimension of C = 3 x 3 x 2
where C(i, j, l) = A(i, j, k) * B(k, l);
i.e.
C(:, :, 1) = A(:, :, k) * B(k, 1);
C(:, :, 2) = A(:, :, k) * B(k, 2);
Now, if I use mtimesx(A, B), then resultant matrix is (3 x 2 x 3) as compared (3 x 3 x 2).
This is because first two dimensions specify the matrix multiply involved. In this case it becomes 1st and 2nd dimension of matrix A while it should ideally be 2nd and 3rd dimension of matrix A to get the desired result.
I am wondering if there is a way around it? I look forward to hearing from you.
Thanks for your help.
@Sam T: I don't think I get it yet. In your example you have:
C(:, :, 1) = A(:, :, k) * B(k, 1);
A(:,:,k) is 3x3
B(k,1) is 1x1
Are you trying to do an nD scalar*matrix multiply here? MTIMESX can do that (with some modifications of the inputs), but I am not quite sure that is really what you want. Can you clarify? Maybe write out an explicit for loop showing how C is to be filled in its entirety?
mtimesx is an awesome code. Besides speeding up my structural dynamics and signal processing applications, it is much easier to apply than using loops. I'm also using a multi-D matrix inverter called multinv that can be downloaded from this forum. The two codes together allow me to operate on matrices of functions as easily as matrices of single values.
@ James Tursa: Thanks James! I greatly appreciate it!
@ Clay Fulcher: Some options to possibly get more speed:
1) NDFUN by Peter Boettcher. E.g., see this thread:
2) FEX submissions. E.g., see this submission:
3) Wait a couple of months for the next MTIMESX submission, when this capability will be included (along with in-place operations and nD matrix multiply versions of PROD and CUMPROD).
James, I need to invert a 3D array of function values. I have to step through each slice of the array in a loop, inverting each slice. Do you know of any way to do this more efficiently?
@ James
The array sizes I'm working with are much larger what I posted. The size of A is 100x33x3. The size of B is 33x1x3x5000x5. That might be why you had trouble recreating it. I'm running on Windows 7, 64 bit, MATLAB 2011b, compiler is cl. If it makes a difference, some of the values in the first matrix are -inf.
@ Jonathan: Yes, weird indeed. For slices 100x100 in size, MTIMESX will always use BLAS dgemm calls regardless of the method setting (you can verify this by using the 'DEBUG' setting). That is, the exact same code path gets executed ragardless of whether 'MATLAB', 'SPEED', or 'SPEEDOMP' is set. That setting should have had no effect on this particular outcome. Also, I have been unable to reproduce this error on a 32-bit WinXP system. Can you provide me some specifics on your MATLAB version, machine OS, compiler used, etc? Does it crash if you restart MATLAB and immediatly try the example?
@ James
So the problem, at least in part, is caused by using the 'SPEEDOMP' flag. I removed the flag, and now it works. Weird, huh?
@ Jonathan Sullivan: Your first example without repmat should have worked. Looks like I introduced a bug in the latest release. I will look into this right away ...
Fantastic code. It has come in handy. It is well documented, incredibly fast, and extremely useful, especially for N-D arrays.
For the N-D case, this code would be even more powerful if the singleton dimension capability were expanded. Currently, all the dimensions from 3:end must be either the same size (A to B), or must all be singleton for one of the variables.
For example
A = rand(100,100,3);
B = rand(100,100,3,5);
C = mtimesx(A,B); % Does not work. Crashes MATLAB.
You can get around this by using repmat:
A = rand(100,100,3);
B = rand(100,100,3,5);
C = mtimesx(repmat(A,[1 1 1 5]),B); % Works, but slow
Unfortunately, explicitly expanding out large arrays has overhead which is more than I'd like.
Overall code. A+.
James, thank you for your hint to using 'lapack' from the FEX.
Indeed it produces the desired result, by calling
lapack('D=DSDOT(i,s,i,s,i)', length(A), A, 1, A, 1)
with 'A' from my example above. Unfortunately, this is ~5 times slower than calling mtimesx() with double input.
On double input, calling the equivalent 'DDOT' routine from the lapack-package takes more than 10 times longer than your mtimesx (wow, by the way...) to compute the very same result.
The difference appears to be even worse for complex input.
So I am still hoping that you might somehow get this feature in your code and maintain the speed...
@ Michael Völker: FYI, another way to use the DSDOT routine is to use this submission:
Not sure if it works on 64-bit systems, but you might give it a try.
@ Michael Völker: Thanks for the comments. I will look into your request. There is a BLAS routine called DSDOT that does what you request. I will look into how easily I can incorporate this into MTIMESX for BLAS specific results. For the SPEED modes MTIMESX sometimes uses custom code to calculate the dot product (e.g., see function RealKindDotProduct), and in fact the accumulation is done in double precision regardless of input type (calculations themselves are single for single inputs), so it might not be too difficult to adapt this to return the double precision output if requested instead of always converting back to single for single inputs. Thanks for the suggestion.
Incredibly great work. Thank you for the elaborate code, the very useful features, the intuitive syntax and behaviour and the docu..
After using mtimesx for a while I currently miss only one feature, which is to define the precision of the output independently from the input variables.
This would be useful when calculating the sum of squares of a huge single-precision vector where the correct result exceeds realmax('single') and prior casting takes a lot of time.
Example:
>> A = randn( 1e8, 1,'single'); % plenty of sane values
>> A(1) = 1e20; % only few outliers
>> sos = A' * A % or sos = mtimesx( A, 'C', A )
sos =
Inf
Doing A = double(A) beforehand solves the problem:
>> sos = A' * A
1.000000040081755e+40
but
>> tic, A = double(A); toc
Elapsed time is 0.472007 seconds.
In fact, that casting to double takes much more time than the actual computation in mtimesx. Since I do this repeatedly in an iteration, the overhead sums up to minutes.
So my wish would be like this:
C = mtimesx( A, B, 'double' ); % C is double even if A or B are single
Nevertheless, thank you so much for this code.
@Gary: Follow-up, ndfun as I recall only works for real variables. If you have complex variables then the only efficient option I could suggest would be a custom mex routine.
@Gary: For this type of matrix product you should be using something like ndfun('mprod',a) by Peter Boettcher. You can find the source code here:
If you need a 64-bit version of this you can see the hack I posted on this thread:
Using ndfun will avoid all the array slice copies you are doing in the above example code.
Thanks for the answer, but I think you misunderstood my problem or me your answer.
I have eg 10000 matrices and want to calculate the product. By dividing into 2*5000 I can use the advantage of your nD multiply. Here is the code:
a=rand(n,n,L)
tic
b=a(:,:,1);
for i=2:L
b=a(:,:,i)*b;
end
toc
c=a;
tic
while(L~=1)
L2=floor(L/2)*2;
d=c(:,:,end);
c = mtimesx(c(:,:,2:2:L2),c(:,:,1:2:L2-1));
if(L2~=L)
c(:,:,end+1) = d;
end
L=size(c,3);
end
toc
So will this never be faster than normal multiplies?
@Gary: MTIMESX is generally not going to be any faster at generic matrix multiplies than MATLAB since it is calling exactly the same BLAS routines as MATLAB. The exceptions are small (4x4 or less) multiplies, dot products, outer products, and some matrix-vector multiplies since they can sometimes be done faster with inline code which MTIMESX uses in the SPEED or LOOP modes. Also, the nD multiply case is almost always faster with MTIMESX than the equivalent loop(s) in MATLAB for any size since array slice copies are avoided.
Hi,
I am trying to compute the product of many matrices (M1*M2*...). I used mtimesx to multiply half of all matrices by the other half until the result(e.g. a=M1*M2, b=M3*M4, a*b). It works very well when the matrix have small size like 4x4 but when for larger size it becomes slower than Matlab. Is that expected?
Was a bit to fast, sorry. Someone already asked this! It works fine now!
Great job!
Great submission! Find it VERY useful for my work!
Also, I think you can change
"Beats MATLAB 300% - 400% in some cases ... really!"
in the title, and multiply the numbers with at least a factor of 25 (based on the results from mtimesx_test_nd).
@ Dan Scholnik: Have you tried running the mtimesx_test_nd file yet? That should invoke small OpenMP test cases. For larger test cases it may in fact be the case that later and/or 64-bit versions of MATLAB are hard to improve on for speed. Alas, I don't have a 64-bit system to tinker with.
At the moment I am working on incorporating in-place operations in MTIMESX and that will be in the next major release, but I will put your dense triangular suggestion on the list of potential future improvements.
Compiled for Matlab 2011a on Fedora 14 x86_64 using
mex CFLAGS='$CFLAGS -fopenmp' LDFLAGS='$LDFLAGS -fopenmp' -largeArrayDims -O -DUNIX mtimesx.c -lmwblas
Not sure all of that was needed, but it works. Compiler was gcc 4.5.1.
mtimesx('OPENMP') returns 1 and mtimesx('OMP_GET_NUM_PROCS') returns 4 (I have a dual-core i7 w/ hyperthreadding), however mtimesx never reports using anything but the BLAS no matter which flags I pass in. Best I can tell the flags have no effect. The matlab-provided mwblas is multithreaded, so perhaps there's no improving on it. Speeds were generally not much different than the matlab multiply, except (as mentioned previously) for cases where the matlab transpose or conjugate operations themselves consumed significant portions of the total time.
I also tried using the fedora-provided BLAS via "-lblas" but it appears to be single-threaded and very slow. Here again mtimesx never used multiple processors that I could tell.
A possible feature suggestion, albeit one that deviates from the general-purpose nature of the current code: How about routines for dense triangular-matrix multiplication? Matlab doesn't seem to have any optimizations for this case (although it does for back-substitution, which is common with triangular matrices).
@ wahyoe Unggul: Did you get the build process to work?
@ wahyoe Unggol: The error message is telling you that you need to select a C compiler first. So do this:
mex -setup
(Then press Enter)
(Then enter the number of a C compiler such as lcc)
(Then press Enter again)
Once this is done, try running mtimesx again and see if it builds OK.
To answer your specific question I would need to know the dimensions of each variable. I.e., what is the size of RT and Ex??
@ Daniel Lyddy: Confirmed typo in the prototypes for these functions. Change the int * to mwSignedIndex *. So
void xSYRK(char *, char *, mwSignedIndex *, mwSignedIndex *, RealKind *, RealKind *,
mwSignedIndex *, RealKind *, RealKind *, int*);
void xSYR2K(char *, char *, int*, mwSignedIndex *, RealKind *, RealKind *, mwSignedIndex *,
RealKind *, mwSignedIndex *, RealKind *, RealKind *, mwSignedIndex *);
becomes
void xSYRK(char *, char *, mwSignedIndex *, mwSignedIndex *, RealKind *, RealKind *,
mwSignedIndex *, RealKind *, RealKind *, mwSignedIndex *);
void xSYR2K(char *, char *, mwSignedIndex *, mwSignedIndex *, RealKind *, RealKind *, mwSignedIndex *,
RealKind *, mwSignedIndex *, RealKind *, RealKind *, mwSignedIndex *);
Thanks for pointing this out. That being said, these typos in all likelihood should not affect the actual results since in both cases 64-bit pointers were being passed and the underlying data is in fact mwSignedIndex in spite of the prototype. I will upload fixed files soon.
I am getting some warnings about incompatible pointer types when compiling on a 64-bit Centos Linux 5.5 system. For example, in line 4909 referred to below, argument 10 is 'LDC' which is #defined to &ldc which is a pointer to mwSignedIndex. In the blas/lapack dsyrk function, argument 10 is also called 'LDC', but it is an integer. Pointers on 64-bit systems are typically larger than 32 bit ints ... maybe these blas/lapack arguments need to be cast to something else?
mex('-DDEFINEUNIX','-largeArrayDims','mtimesx.c',blas_lib)
mtimesx.c: In function ‘mexFunction’:
mtimesx.c:592: warning: assignment discards qualifiers from pointer target type
In file included from mtimesx.c:1303:
mtimesx_RealTimesReal.c: In function ‘DoubleTimesDouble’:
mtimesx_RealTimesReal.c:4209: warning: passing argument 10 of ‘dsyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4211: warning: passing argument 10 of ‘dsyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4212: warning: passing argument 3 of ‘dsyr2k_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4225: warning: passing argument 10 of ‘dsyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4227: warning: passing argument 10 of ‘dsyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4228: warning: passing argument 3 of ‘dsyr2k_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4241: warning: passing argument 10 of ‘dsyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4243: warning: passing argument 10 of ‘dsyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4257: warning: passing argument 10 of ‘dsyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4259: warning: passing argument 10 of ‘dsyrk_’ from incompatible pointer type
In file included from mtimesx.c:1481:
mtimesx_RealTimesReal.c: In function ‘FloatTimesFloat’:
mtimesx_RealTimesReal.c:4209: warning: passing argument 10 of ‘ssyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4211: warning: passing argument 10 of ‘ssyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4212: warning: passing argument 3 of ‘ssyr2k_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4225: warning: passing argument 10 of ‘ssyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4227: warning: passing argument 10 of ‘ssyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4228: warning: passing argument 3 of ‘ssyr2k_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4241: warning: passing argument 10 of ‘ssyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4243: warning: passing argument 10 of ‘ssyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4257: warning: passing argument 10 of ‘ssyrk_’ from incompatible pointer type
mtimesx_RealTimesReal.c:4259: warning: passing argument 10 of ‘ssyrk_’ from incompatible pointer type
I'm not using deploytool, just MCC command.
@ Bruno Luong: Sorry I am not going to be much help here since I do not have a Windows 7 platform to test with. Are you using deploytool, and then the result can't use mtimesx?
There is an annoying compatibility issue with deploying MTIMESX on Window7 platform, The MCR issues an error message "mex file in incorrect". It works fine under Matlab or other OS. I just can't use it when the issue is not resolved.
@ Matt J: Issue mtimesx without any arguments to find out what the current calculation mode is. If you enter any of the OpenMP directives but mtimesx was not compiled with an OpenMP enabled compiler then mtimesx will revert to the nearest functionality. So SPEEDOMP will revert to SPEED, LOOPSOMP will revert to LOOPS, and the omp_etc functions will revert to substitute functions instead of the actual OpenMP functions. Your above example looks like what would happen if mtimesx was not compiled with an OpenMP enabled compiler. To see how mtimesx thinks it was compiled, issue the mtimesx('OPENMP') command and it will return a 1 (yes OpenMP) or 0 (No OpenMP).
James, the latest version of mtimesx doesn't display at the command line any of the new modes (so of course I don't know if they're being used).
>> mtimesx SPEEDOMP
ans =
SPEED
Thanks James! See this thread for applying MTIMESX to calculate a fast 2-norm for the matrix along a specified dimension:
@Matt J: I will look into it. Rather than pre-converting I may be able to fake out a call back to MATLAB with a pointer to the interior of the nD array and fudged up dimensions. Highly against the mex rules, but it might work. I should have taken advantage of the simple reshape method you use for the non-transposed cases (I didn't recognize it at the time I was updating the code) and that should not be too hard to implement. But the transpose cases for the 2D slices and the case for the sparse matrix being the right operand is going to be tricky to avoid a data copy. Guess I have a weekend project now ...
James - I appreciate you taking my comments into account in the latest rev, but I'm still seeing weird stuff. From the manual:
"If you combine sparse inputs with full nD (n > 2) inputs, MTIMESX will convert the sparse input to full since MATLAB does not
support a sparse nD result."
Pre-converting the input from sparse to full leads to very slow performance, certainly slower than regular MATLAB as the comparison below shows. Is it really the only convenient solution? Also, MATLAB not supporting sparse nD is again not the issue, since even for n=2, sparse*full is always full in regular MATLAB.
%fake data
N=300;M=200;
A=speye(N);
B=rand(N,N,M);
Bs=single(B);
mtimesx SPEED;
tic;
ans1=mtimesx(A,B);
toc;
%Elapsed time is 0.681635 seconds.
tic;
ans2=reshape( A*reshape(B,N,[]) , size(B) );
toc;
%Elapsed time is 0.159543 seconds.
isequal(ans1,ans2)%1
"If you combine double sparse and single inputs, MTIMESX will convert the single input to double since MATLAB does not support a single sparse result."
As above, even if MATLAB did support sparse*fullsingle you would expect the result to be full single, not sparse single. And also, this feature is showing very slow behavior as compared to regular MATLAB, for some reason
tic;
ans3=mtimesx(A,Bs);
toc;
%Elapsed time is 0.817832 seconds.
tic;
ans4=single( reshape( A*reshape(double(Bs),N,[]) ,size(B)) );
toc;
%Elapsed time is 0.402111 seconds.
isequal(ans3,ans4),%1
@Matt J: Thanks for the comments. I will get to work on the suggested changes right away.
Just a couple more remarks regarding some of the limitations mentioned in the user manual,
"You cannot combine double sparse and single inputs, since MATLAB does not support a single sparse result."
It would be worthwhile to silently cast the single input to double prior to the matrix multiply. I've never understood why MATLAB doesn't implement the same. It only forces the user to do it manually.
"You also cannot combine sparse inputs with full nD (n > 2) inputs, since MATLAB does not support a sparse nD result."
Don't understand that. Native MATLAB produces a full result when combining sparse matrix multiplicands with full ones. No reason why you couldn't do the same for nD, as far as I can see...
I like it. The only thing I find a little peculiar is that the output of
mtimesx('MODE') reports the previous mode rather than the current one.
Something like A(A<1e-8) = 0 should automatically remove small numbers from the sparsity pattern.
If this is too slow, have a look at spfun; it may be faster.
However, if you mean if you can remove small elements from the output matrix, you should write something of your own, partially multiplying the matrix and removing small elements. As a tip, use full column vectors of the matrix, this will make the multiplication much faster than square blocks, since sparse matrices are stored by columns. E.g.:
C = spalloc(size(A,1), size(B,2), 0);
for j=1:size(B,2)
R = A*B(:,j);
R(R<1e-8) = 0;
C(:,j) = R;
end
is (probably) a fast implementation. Try to take multiple columns for speed of course.
Thanks Sebastiaan, I never thought to check the density of the resulting matrix and you are absolutely right: the memory blew up! By the way, is there any way to define an “operational zero” for sparse matrices operations in order to automatically make MATLAB assume a zero for numbers say < than 1e-8?
Thank you again.
Could it not be possible that you are really out of memory? Your result is a 460191 by 460191 matrix, which is not necessarily sparse. If the sparsity pattern is poor, the result may even be a dense matrix. Storing a full matrix this size requires 1578GiB of memory, so you have to be sure that the result is ~2% sparse. If neither of the input matrices are <1% sparse, this is likely your problem.
Thanks for your prompt reply. “mtimes” at the MATLAB prompt gives exactly the same error so, nothing wrong with “mtimesx”. Is it possible that this is a repetition of the “outer-product” problem? I am going to try partition the matrix “cb” in several chunks and then concatenate the results. Maybe it will work this way.
Thanks again.
@ Julio: MTIMESX does not do generic sparse matrix multiplies internally, it just calls the MATLAB built-in function mtimes. i.e., it does the same thing as if you had just typed c21 * cb at the MATLAB prompt. Can you verify that c21 * cb works at the MATLAB prompt but mtimesx(c21,cb) does not work? Be sure that you start them both from the same state (e.g., clear all other big variables including ans before attempting the calculation). That would be surprising to me since it would indicate some type of mex limitation that I am currently unaware of.
Hi, I am new using mtimesx but, so far, I think is great. Meanwile, I am trting to multiply 2 large sparse matrices "ci=mtimesx(c21,cb)". c21 is 460191 by 5579 and cb is 5579 by 460191. After several minutes I got a error message (similar to mtimes):
======================
??? Error using ==> mtimes
Out of memory. Type HELP MEMORY for your options.
Error in ==> mtimesx_sparse at 47
result = a * b;
Error in ==> mtimesx at 277
[varargout{1:nargout}] = mtimesx(varargin{:});
======================
I don't think that the problem is lack of memory (I have a 64 bit system with 8 GB of RAM and the memory usage never went above 5 GB). Couls you please comment on this.
Thanks in advance.
Julio
Also in today's release that I forgot to mention below: Added custom inline code for small matrix multiplies where all of the first two dimensions are <= 4 (in 'SPEED' mode).
Thanks! I am seeing about a 3.25x improvement in speed for my application.
@ D Sen: In addition, you would need to reshape audio_dft to be 32 x 1 x 4097.
@ D Sen: The E array slicing is not set up the way mtimesx needs. mtimesx needs the array slices to be contiguous in memory (a requirement for the underlying BLAS calls). So your E array would need to be a 25 x 32 x 4097 array, making the 25 x 32 slices contiguous in memory (the 2D slices need to be the first two dimensions). The way you currently have it set up, all of your 25 x 32 array slices of E are individually scattered throughout memory and are not the first two dimensions, and mtimesx cannot use them that way.
I have been trying to use this to multiply a 3D matrix with a 2D matrix.
The matlab code which works is as follows:
C = zeros ( 25, 4097 );
for( i_ = 1:4097 )
C(:, i_) = squeeze( E( i_, :, : ) ) * audio_dft( :, i_ );
end
Here E and audio_dft have the following sizes:
size(E)
ans =
4097 25 32
size( audio_dft)
ans =
32 4097
I get:
mtimesx( E, audio_dft )
??? Error using ==> mtimesx
Inner matrix dimensions must agree.
Never mind, I found my problem. I have not successfully built mtimesx on Snow Leopard 10.6 with 64 bit MATLAB.
To do so I edited
/Applications/MATLAB_R2009b.app/bin/gccopts.sh
In the section for "maci64" I changed "SDKROOT" and "MACOSX_DEPLOYMENT_TARGET" to reflect a change in OS from 10.5 to 10.6.
Then I selected this opts file with
mex -setup
selecting "1" at the prompt.
Then I compiled everything with:
mex -v -DDEFINEUNIX -largeArrayDims mtimesx.c -lmwblas -lmwlapack
(look out for the 2 D's in -DDEFINEUNIX - that was my error)
I'm trying to compile on 64bit MATLAB on Mac OSX 10.6 without success. The only changes I've made to the default have been to modify the MATLABROOT/bin/gccopts.sh file such that the SDK and OS Version are set to the 10.6 variety. (and then ran mex -setup)
It seems the linker cannot find the linear algebra packages, but it is not clear to me why. The output is below and I would be thankful for ideas on what to try next.
thanks
---------------snip------------
-> gcc-4.0 -O -Wl,-twolevel_namespace -undefined error -arch x86_64 -Wl,-syslibroot,/Developer/SDKs/MacOSX10.6.sdk -mmacosx-version-min=10.6 -bundle -Wl,-exported_symbols_list,/Applications/MATLAB_R2009b.app/extern/lib/maci64/mexFunction.map -o "mtimesx.mexmaci64" mtimesx.o -L/Applications/MATLAB_R2009b.app/bin/maci64 -lmx -lmex -lmat -lstdc++
Undefined symbols:
"_dsyr2k", referenced from:
_DoubleTimesDouble in mtimesx.o
_DoubleTimesDouble in mtimesx.o
"_dgem
"_dgemgemgem
"_dsyrsyrsyr2k", referenced from:
_FloatTimesFloat in mtimesx.o
_FloatTimesFloat in mtimesx.o
"_sdot", referenced from:
_floatcomplexdotproduct in mtimesx.o
_floatcomplexdotproduct in mtimesx.o
_floatcomplexdotproduct in mtimesx.o
_floatcomplexdotproduct in mtimesx.o
_floatcomplexdotproduct in mtimesx.o
"_ddot", referenced from:
_doublecomplexdotproduct in mtimesx.o
_doublecomplexdotproduct in mtimesx.o
_doublecomplexdotproduct in mtimesx.o
_doublecomplexdotproduct in mtimesx.o
_doublecomplexdotproduct in mtimesx.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
mex: link of ' "mtimesx.mexmaci64"' failed.
The code is suprisingly fast for multiplication of a sparse matrix by a skalar. I really wonder why Matlab is so slow in this (very simple) case.
James,
This is code is proving to be a FANTASTIC speed up to my work. I am so grateful that I thought I would post and comment.
First, I am working on R2008b on an intel mac. I compiled your code with
mex -DEFINEUNIX mtimesx.c
and although I received a handful of warnings about redefined pointers, it compiled fine without error. I also tried compiling the code with a few extra optimizations, out of curiosity:
mex -DEFINEUNIX CFLAGS = '$CFLAGS -O3 -funroll-loops -fexpensive-optimizations -ffast-math' mtimesx.c
The result wasn't significantly faster than the original on my own processing test (I did not take the time to run it through your tests, however.).
I did run mtimesx_test_ddspeed initially to compare with MATLAB native routines, and while I didn't capture the results, I found that most things native MATLAB could do as fast or faster than mtimesx, with the notable exception of math involving complex conjugates, in which mtimesx was far, far faster.
However, the fantastic benefit for me was the native handling of 4D matrices by mtimesx. In my own code in which I am rotating several (8.3) million 3D vectors through a 3x3 rotation matrices, mtimesx increased the speed of my calculations 2100%!
Thanks so much for your time and effort. It is most gratefully appreciated.
-Val
@ veltz: Thanks for your comments. Regarding openMP, I think the short answer is no. I will give my reasons shortly, but please be advised I don't do any openMP stuff myself so my comments might not be correct.
The basic loop for nd stuff is this loop:
for( ip=0; ip<p; ip++ ) {
However, this is just the loop for the blocks in the C result. The blocks from the A and B arrays are calculated inside the loop based on the singleton expansion code (which depends on the dimensions of A and B) and are not known ahead of time ... at the end of one iteration the calculation for the A and B blocks for the next iteration takes place (the C block pointer just advances by the same amount each time). So it is not set up for a parallel loop. I would have to change the code and create three new arrays of pointers so that ahead of time all of the individual block starting points are known. *Then* maybe it could be put in a parallel loop.
But I don't think this would do much good. The multi-threaded stuff in MATLAB seems to happen at the BLAS/LAPACK level, so mtimesx is already getting the benefit of multi-threading for those calls without doing anything special in the mtimesx code itself to get it. For example, if you compare a simple matrix multiply timing at the MATLAB prompt using two large matrices, you can see about a 1.6x improvement with 2 threads vs 1 thread. If I code up a very simple mex routine that calls dgemm and does nothing else (no pragma omp etc) I see the exact same timing benefit when switching the number of threads used. So the c-mex code gets the multi-threaded benefit by virtue of the BLAS/LAPACK routines used. Wrapping another layer of threading on top of that will likely not result in any timing benefit, and may (speaking from ignorance here) in fact conflict with the multi-threading that is already going on inside the BLAS/LAPACK routines themselves.
First, thank you for this marvellous code :)
Is there a way to use openMP in your code ? For example, when doing
C = zeros(2,6,4,5);
for m=1:4
for n=1:5
C(:,:,m,n) = A(:,:,m,n) * B(:,:,m,n);
end
end
we could call un pragma omp parallel for. As the code is pretty big, where does such loop appear in your code ?
Debian 64-bit compiled right with:
mex CFLAGS="\$CFLAGS -std=c99" -DDEFINEUNIX -largeArrayDims -lmwblas mtimesx.c
(the functional syntax of mex did not parse the arguments properly)
The GCC -ansi switch included by the default mexopts apparently refers to C89 (which does not recognize // -- C++ style comments). I wonder what is wrong with C99 as a default in mexopts?
Very useful code. Good work.
The following snippet may be useful to those compiling on Ubuntu:
libblas='/usr/lib/libblas.so';
if exist(libblas,'file')~=2
system('sudo aptitude install libblas-dev');
end
% This will compile the code on linux
mex('CFLAGS=-std=c99 -fPIC','-DDEFINEUNIX','-largeArrayDims','-lmwblas','mtimesx.c');
@Fabio: Thanks very much for the 64-bit info. I was unaware that gcc did not like the // commenting style, which I prefer over the /* */. However, I will create additional files with changed comments and upload them in the next week or so. I would be very interested in seeing the details of what you had to change to get it to compile and the results of any benchmark tests you happen to run. Feel free to e-mail me at the address listed in the pdf file. Thanks!
Great job!
Thanks to mtimesx I changed a huge for loop to 3D matrix computation, reducing script execution time from 14 s to 1.5 s!
Tested and compiled on Gentoo Linux (64bit) 2.6.33 on amd64 system. Compiling with gcc 4.3.* (not the deprecated 4.2 as suggested by Mathworks) I had to delete all quotes from C code files. Probably "//" sequence is not friendly to newer gcc compiler, maybe you can replace it with " /*quote*/ " wich is correctly ignored. Also to successfully compile I had to use:
mex('-DDEFINEUNIX','-largeArrayDims', '-lmwblas','mtimesx.c')
wich is something different from default. Both '-lmwlapack', '-lmwblas' are the options suggested for compiling in UNIX systems (see "Building MEX-Files" in doc), but that was enough. I can say it works correctly, but I didn't run the benchmarks files.
Hope this helps!
Feel free to ask if some testing on LINUX 64bit is needed. I'm going to run tests soon.
Thanks for the quick fix!
Confirmed bug. The bug happens during the following conditions in MATLAB mode:
(row vector) * (non-square matrix)
(non-square matrix transposed) * (column vector)
Sorry about that! This was not caught in testing because I only used square matrices for these particular tests. The bug occurs because the BLAS routines DGEMV and SGEMV do not switch the dimension arguments when a transpose is involved. I had erroneously assumed that they did because that is how the BLAS routines DGEMM and SGEMM arguments work for general matrix multiplies. I have no idea why the interface for these routines is not set up the same. In any event, I will upload a fix tonight. In the meantime, you can manually put the fix in as follows:
Edit the mtimesx_RealTimesReal.c file.
Global replace the following text:
xGEMV(PTRANSA, M, K
with this text:
xGEMV(PTRANSA, &m1, &n1
And then also global replace the following text:
xGEMV(PTRANSB, N, K
with this:
xGEMV(PTRANSB, &m2, &n2
Those replacements will force the DGEMV and SGEMV calls to use the original dimensions of the first matrix argument instead of the switched dimensions.
Thanks! Also, FYI: I am running R2009a...
I will look into it.
Hi I running matlab on a 32-bit windows machine and I am getting incorrect (all 0) results when i perform some simple 3D matrix multiplication in "matlab' mode only ('speed' mode seeps yield the correct results in all the cases i have tested so far). i.e.
>> % define a and b
>> a=2*ones(1,2,2)
a(:,:,1) =
2 2
a(:,:,2) =
2 2
>> b=3*ones(2,3,2)
b(:,:,1) =
3 3 3
3 3 3
b(:,:,2) =
3 3 3
3 3 3
>>
>> % verify result using normal matrix multiply
>> a(:,:,1)*b(:,:,1)
ans =
12 12 12
>> mtimes(a(:,:,1),b(:,:,1))
ans =
12 12 12
>>
>> % test results using mtimesx
>> mtimesx(a(:,:,1),b(:,:,1),'matlab')
ans =
0 0 0
>> mtimesx(a(:,:,1),b(:,:,1),'speed')
ans =
12 12 12
I just downloaded and installed the package yesterday, so I believe the outer-product bug discussed about should be fixed. Does anyone have any idea what is causing this error? Thanks!
-eric
@newpolaris: Thanks for the input! It's hard for me to debug the 64-bit stuff since I don't have a system to test with, so comments like yours are very much appreciated. I have uploaded a new set of files with the largearraydims typo in the build routine fixed.
grate! but mis-typing exist on mtimesx_build.m for 64bit Windows
on line 247 -> largearraydims = '-largearraydims';
it cause error like,
Warning: MEX could not find the library "argearraydims"
specified with -l option on the path specified
with the -L option.
... mex mtimesx.c build completed ... you may now use mtimesx.
so it muse be replace by "largearraydims = '-largeArrayDims';"
in my case, result is all zero matrix :)
Cannot thank you enough for this. Got a huge speed improvement (10 seconds down to 0.6) for a script using this. I'm staggered it's not in the core of Matlab.
It must have some gut to tackle what Matlab pretends to do the best: matrix computation.
The package is nicely presented. This is no doubt a professional quality code using the junk of state-of-art BLAS, an accompaniment PDF document to explain the “why” and the “how” in great detail.
As with any well written MEX-based package, there is an installation file to make conveniently the compilation before the package can be used. Just type the name and the job is done. The main path (no subfolders) of the package is left to user to add to Matlab preference.
Obviously there are 8 separate files that can be used to benchmark with Matlab. Their names tell something that not obvious for new comers, but for those who are familiar with Matlab, there is no doubt: It tests all 4 combination of double/single and one for equality test, another for speed test. I choose the “dd” one (double/double) likely the most used combination, and run the “equal” test. It crashes. Too bad, then despite of the crash I took my chance to run the speed test. Well, a bunch of tests are tic/toc against Matlab, with clear outputs indicating if it’s slower or faster than Matlab and how much in percent the runtimes are comparable. Something strange happened: in some cases, the MTIMESX show few hundred times faster than Matlab. I told: “It cannot be true; why Matlab performs so poorly?”. I decided to go step-by-step the speed-test function, and discovered there may be another bug. I contacted the author, and bingo, I get his explanation and solution few hours later. The bug (just one line missing) is due to last minute change before submission. Followed James’s instruction, I modified the code, rebuilt the Mex file, and run the test code. The results look much more reasonable. And I rerun the “equal” test, there is no longer crash.
One more word on my setup before reading the next: Windows Vista 32-bit, 2009B, and an old loyal VS C++ 6.0. It is important because MTIMESX performance will depend greatly on the setup, and this is clearly stated by the author.
The main function MTIMESX can operate on two modes: “MATLAB” (default) and “SPEED”. The first one tries to be as much as compatible with Matlab, and the second one is all about – as the name suggests - speed oriented. In all my first two tests I run “MATLAB” modes, the last one will compare two modes.
PERTINENT:
I. 2D Arrays
Speed tests run with all possible combination of cases: complex/real; normal, transposed, conjugate, conjugate-transposed; then combinations of matrix/vector/scalar; all that apply for first or second matrix arguments. Each argument might have then 2*4*3=24 states, not counting a vector can be column or row. Combine both, the test run probably no less than 24^2=576 cases, and for 2D arrays only (ND arrays supported, we’ll be back on that).
Most of the time, MTIMESX (in Matlab mode) seems to perform more or less a comparable speed with Matlab, except for few cases where speed advantage is clearly significant. Here is one typical of such case:
>> n=2000;
>> A=rand(n)+1i*rand(n);
>> B=rand(1,n)+1i*rand(1,n);
>> tic; C=conj(A)*B.'; toc
Elapsed time is 0.094847 seconds.
>> tic; C=mtimesx(A,'G',B,'T'); toc
Elapsed time is 0.034242 seconds.
That about 3 times faster than Matlab. Taking a closer look, it seems Matlab is penalized by carrying out explicitly the transpose and conjugate before the product as show in the next
>> A1=conj(A);
>> B1=B.';
>> tic; C=A1*B1; toc
Elapsed time is 0.030122 seconds.
whereas MTIMESX performs those operations *on-the-fly* during the product. Very good. But I would argue that the speed gain is less in practice. In fact if the product is to be carried out once, careful developers usually manage to build conj(A) and B.’ and not A and B. In this case all the speed gain of MTIMESX is irrelevant. If A and conj(A) are used to perform product once each, then there is speed gain is about 1.5 (3/2). If they are used many times, then the developer might perform CONJ once and store it somewhere before product function MTIMES is invoked, and the speed gain get even closer to 1. Still there is clearly an advantage in MTIMEX, for speed and it avoid storing extra matrix conj(A).
My impression is this is the only (and significant) factor that contributes to the speed gain: performing CONJUGATE on the fly. Recent Matlab (2008A, i.e., v.7.6) benefits smart TRANSPOSE on the fly, according to Tim-Davies.
II. ND-arrays
The nicest feature of MTIMESX is the capability to perform multiple matrix products ranged in a ND-array. Previously there is such function available on Matlab File Exchange coded by Peter Boettcher also using BLAS, but it seems this package has now a minimum support, and users has trouble to compile it on 64-platform. So this new feature is very welcome.
When a Matlab developer wants to make product of multiple matrix of the same size, up to date he has 4 alternatives
1. Use for-loop
2. use a product based on sparse diagonal block (for example function SliceMultiProd available in
3. Use the package MULTIPROD where the element-wise product and sum are carried out,
4. Use BLAS based, such as Peter Boettcher’s ndfun, and now James Tursa’s MTIMESX
Here is a code I use to benchmark the four approaches. Note that in small matrix size (of less than said 5) are often encountered in practice.
function mprodbench(m,n)
% Bench mark four approaches of product of n (m x m) matrices
A=rand(m,m,n);
B=rand(m,m,n);
C=zeros(size(A,1),size(B,2),size(B,3));
tic
for k=1:size(B,3)
C(:,:,k) = A(:,:,k)*B(:,:,k);
end
t1=toc;
tic
C=SliceMultiProd(A,B);
t2=toc;
tic
C=multiprod(A,B);
t3=toc;
tic
C=mtimesx(A,B);
t4=toc;
fprintf('Matrix size=%d, number matrices=%d\n', m, n);
fprintf('\tfor-loop = %f, rel speed gain = (%f)\n', t1, t1/t1);
fprintf('\tSliceMultiProd = %f, rel speed gain = (%f)\n', t2, t1/t2);
fprintf('\tmultiprod = %f, rel speed gain = (%f)\n', t3, t1/t3);
fprintf('\tmtimesx
end
And here is the results:
> mprodbench(3,1e4)
Matrix size=3, number matrices=10000
for-loop = 0.055119, rel speed gain = (1.000000)
SliceMultiProd = 0.014130, rel speed gain = (3.900815)
multiprod = 0.007815, rel speed gain = (7.052806)
mtimesx = 0.006185, rel speed gain = (8.911272)
>> mprodbench(10,1e4)
Matrix size=10, number matrices=10000
for-loop = 0.074665, rel speed gain = (1.000000)
SliceMultiProd = 0.146336, rel speed gain = (0.510228)
multiprod = 0.151051, rel speed gain = (0.494303)
mtimesx = 0.022569, rel speed gain = (3.308258)
That shows MTIMESX is the best and consistent approach of multiple same-size matrix product. It supports inputs with any multiple-trailing dimensions.
III. SPEED VS MATLAB MODES
From my test, speed mode is faster about 30-50% typically for tensorial product (column vector multiplied row vector). Beside that case, the speed gain is probably not spectacular.
CONCLUSION:
- For whom? Developers who are interested in optimizing speed and want to take advantage the last ounce of performance from their computers. I have not tested in older version of Matlab but MTIMES, but it will be more surely pertinent as Matlab makes constant progress such as smart matrix transposition. Those who run on latest Matlab (from 2008A) has limited benefits besides saving extra conjugate and transpose operations of their matrices. The syntax of MTIMESX is simple, though quite not lean as Matlab operator is the price to pay.
- MTIMESX is clearly a best approach for multiple-product of matrices. Go for it!
Fully justified, until Mathlab catching up.
Bruno
As a workaround prior to Monday you can make this change to the mtimesx_RealTimesReal.c file near line 222:
scalarmultiply = 0; // <-- add this line
if( m1 == 1 && n1 == 1 ) {
scalarmultiply = 1;
There is a bug in the outer product code. Will be fixed as soon as TMW posts updated version. Probably Monday Dec 7.
Fixed bug for (scalar) * (sparse) when the scalar contains an inf or NaN (in which case the zeros do not stay zero). Slight update to pdf doc.
Fixed bug in scalar multiply code that was causing incorrect results & crashes.
Added singleton expansion capability for multi-dimensional matrix multiplies.
Fixed a bug for empty transa or transb inputs. Now treats these the same as 'N'. Also simplified the nD singleton expansion code a bit.
Added the multi-dimensional test routine mtimesx_test_nd.m for speed and equality tests. Added its description to the pdf file.
Fixed a typo in the build routine for 64-bit systems, changed -largearraydims to -largeArrayDims
Fixed a bug for some of the (row vector) * (matrix) and (matrix transposed) * (column vector) operations in MATLAB mode that involved incorrect dimensions in the dgemv and sgemv calls.
Added capability for nD scalar multiplies (i.e., 1x1xN * MxKxN).
Replaced the buggy mxRealloc API routine with custom code.
Updated mtimesx_test_nd.m file.
Added OpenMP support for custom code
Expanded sparse * single and sparse * nD support
Fixed (nD complex scalar)C * (nD array) bug
Fixed typos in the dsyrk, dsyr2k, ssyrk, and ssyr2k BLAS function prototypes. (These typo fixes should not change any results) | http://www.mathworks.com/matlabcentral/fileexchange/25977-mtimesx-fast-matrix-multiply-with-multi-dimensional-support | CC-MAIN-2014-42 | refinedweb | 10,478 | 64.81 |
Opened 10 years ago
Closed 8 years ago
#10445 closed enhancement (fixed)
A Polyhedron should have a "is_simplicial" method.
Description
Presently, one can not ask if a polytope is simplicial (cf. for the definition).
I would like to have something like:
sage: p = polytopes.n_cube(3) sage: p.is_simplicial() <------------- False <------------------------------- sage: q = polytopes.n_simplex(5) sage: q.is_simplicial() <------------- True <--------------------------------
Attachments (1)
Change History (12)
comment:1 Changed 10 years ago by
- Summary changed from A Polyhedron should have a "is_simplicial" to A Polyhedron should have a "is_simplicial" method.
comment:2 Changed 10 years ago by
- Cc novoselt added
comment:3 follow-up: ↓ 5 Changed 10 years ago by
comment:4 Changed 10 years ago by
Oops, sorry, went a little too fast there. Here's one that might actually work:
def is_simplicial(pq): """ Tests if a polytope is simplicial, i.e. every facet is a simplex. EXAMPLES:: sage: p = Polyhedron([[0,0,0],[1,0,0],[0,1,0],[0,0,1]]) sage: p.is_simplicial() True sage: p2 = Polyhedron([[1, 1, 1], [-1, 1, 1], [1, -1, 1], [-1, -1, 1], [1, 1, -1]]) sage: p2.is_simplicial() False """ for f in pq.facial_incidences(): if len(f[1]) != pq.dim(): return False return True
comment:5 in reply to: ↑ 3 Changed 10 years ago by
Should non-compact polyhedra be simplicial if they have simplicial facets?
What exactly do you mean by facets here? Do you include unbounded ones?
There is a standard notion of a simplicial cone which means that its dimension is equal to the number of edges. I think
is_simplicial for arbitrary polyhedra should either adhere to this or raise
NotImplementedError for all unbounded polyhedra. I guess the right generalization is to say that it is simplicial in the projective space.
comment:6 Changed 8 years ago by
- Status changed from new to needs_review
comment:7 Changed 8 years ago by
- Status changed from needs_review to needs_work
- Work issues set to unbounded case
I think my 2-year old comment still has to be taken into account.
Changed 8 years ago by
comment:8 Changed 8 years ago by
- Status changed from needs_work to needs_review
I have added a NotImplementedError? for unbounded polyhedra
comment:9 Changed 8 years ago by
- Reviewers set to Andrey Novoseltsev
- Status changed from needs_review to positive_review
comment:10 Changed 8 years ago by
- Work issues unbounded case deleted
comment:11 Changed 8 years ago by
- Merged in set to sage-5.7.beta3
- Resolution set to fixed
- Status changed from positive_review to closed
Wow, I thought we had already done that at some point. Here's a first attempt:
Should non-compact polyhedra be simplicial if they have simplicial facets? | https://trac.sagemath.org/ticket/10445 | CC-MAIN-2021-21 | refinedweb | 447 | 64.3 |
User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8b2) Gecko/20050501 Firefox/1.0+
Build Identifier: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8b2) Gecko/20050501 Firefox/1.0+
Mozilla will not build on Mac OS X "Tiger" 10.4, even using the "legacy" GCC 3.3
compiler bundled with the system's Xcode/Developer Tools 2. Several aspects of
the system have changed:
Native build issues:
1. The system library now includes FSLockRange and FSUnlockRange functions that
conflict with the ones in xpcom/MoreFiles/MoreFilesX.c. MoreFilesX comes from
Apple, so they broke their own API. Mozilla does not use FSLockRange or
FSUnlockRange, so these functions can be unconditionally renamed or removed.
This was first reported in bug 292266.
2. The sdp tool, used to prepare resources, has moved. It was in
/Developer/Tools in former releases. It is now in /usr/bin. The Makefile in
xpfe/bootstrap/appleevents has a hardcoded path and needs to be updated.
configure should check for the location of sdp.
3. The linker is being finicky when linking xpicleanup in xpinstall/cleanup,
treating the multiple definitions of strdup as a hard error. It was formerly
treated as a warning. strdup is defined in the system library and in
modules/libreg/src/vr_stubs.c (via libmozregsa_s.a). I haven't investigated
enough to determine why ld's behavior has changed, but I can't imagine needing
to provide strdup on any Mac OS X variant, so it may as well go into an ifdef.
The above problems were encountered when building Firefox on Mac OS X 10.4 using
GCC 3.3 (sudo gcc_select 3.3). Let's call this "phase 1." Building with GCC
4.0 can be a later phase. See bug 280479, bug 292266.
Cross-compilation issues:
With the problems above fixed, it is still difficult to target an older system
by specifying an alternate Mac OS X SDK when building on Mac OS X 10.4.
(Install the appropriate cross-development packages in Xcode and add
ac_add_options --with-macos-sdk=/Developer/SDKs/MacOSX10.2.8.sdk to .mozconfig.
This is the configuration recommended by Mozilla for release use, see .)
4. When specifying an alternate development SDK under host OS 10.4, C++ is
uncompilable because of problems including headers. The list of include
directories is incomplete. This was not a problem when building under earlier
versions of Mac OS X, because the system's own headers were "compatible enough"
with the headers in older SDKs. When compiling C++, we need to search the
following subdirectories under SDK_PATH/usr/include/gcc/darwin/GCC_VERSION: c++,
c++/ppc-darwin, c++/backward, and ., as well as the standard C include directory
SDK_PATH/usr/include. This information is gleaned from g++ -v. Currently, only
the GCC_VERSION directory itself and the standard C include directory is
searched. This is insufficient.
(XXX should we also add the proper Frameworks directories to the framework
search path using -F when building with an SDK?)
5. Note that the way these paths are built needs to be updated to support
Apple's GCC 4. ppc-darwin is now powerpc-apple-darwin# (# being the
corresponding Darwin release major version being targeted). GCC_VERSION needs
to be major.minor (4.0), but because Apple's GCC 4 identifies itself as 4.0.0,
the way that GCC_VERSION is constructed needs to be altered. This doesn't
prevent the use of GCC 3.3 on 10.4, though.
6. Header incompatibility causes more problems when configure determines that a
header is available based on its presence in /usr/include, but it is not present
in the SDK. For example, when targeting the 10.2.8 or 10.3.9 SDKs, when
building xpcom/obsolete/nsFileSpec.cpp, we include sys/types.h from the SDK and
sys/statvfs.h from /usr/include. sys/statvfs.h is not present in the 10.2.8 or
10.3.9 SDKs, but is included because configure notices its presence in
/usr/include and sets HAVE_SYS_STATVFS_H. sys/statvfs.h includes
machine/_types.h, also in /usr/include, which redefines, sometimes with
conflicts, the types already defined in the SDK's sys/types.h. This is a
particularly hairy problem, and the only solution I can think of is to wrap
AC_CHECK_HEADERS checks for system headers in a test to check that the header is
present in the SDK (and not /usr/include) when building on a Mac with
with-macos-sdk selected.
(A similar problem to #6 will be present in the orbit libIDL installation,
because libIDL/IDL.h will want to include wchar.h from /usr/include, and wchar.h
also includes _types.h. The only workaround is to eliminate the inclusion of
wchar.h from IDL.h when using an SDK.)
Reproducible: Always
Steps to Reproduce:
Created attachment 182336 [details] [diff] [review]
Fix issues 1-4
1. Rename FSLockRange and FSUnlockRange to MFX_FSLockRange and
MFX_FSUnlockRange (MFX, for MoreFilesX).
2. Make configure to check for the location of the sdp tool, and make sure it's
used.
3. Don't redefine strdup on Mac OS X.
4. C++ include path fix when targeting an older system.
No fix for 5 yet. Although that's trivial, it's not necessary to build with
GCC 3.3, which is all I'm shooting for at this point.
No fix for 6 yet. Would like some feedback on the proposed solution.
I also tested the attached patch on a system running 10.3.9 with Xcode/DT 1.5
and gcc 3.3 and was able to build without incident, both with and without
with-macos-sdk specified.
note that anything built with gcc4 requires 10.3.9 or later to run, so that
shouldn't be a concern for us for a VERY long time.
Part 6, header conflicts between SDK and system, is still a problem when using
gcc 3.3 on a 10.4 build host. It effectively means that you can't use a 10.4
host to target an older system release using any compiler.
Part 5's the only part that's gcc 4-specific.
(In reply to comment #3)
> note that anything built with gcc4 requires 10.3.9 or later to run, so that
> shouldn't be a concern for us for a VERY long time.
I don't see why building on gcc4 shouldn't be a concern for a very long time. Or I guess maybe I don't see
who "us" is. I can understand that official firefox/moz/camino/tbird/etc... builds won't be done w/ gcc4
(at least not MacOS) for a while, but I'd imagine there are mozilla folks for whom this would be at least an
area of interest in the near future, if not a full-blown concern.
(In reply to comment #5)
> I don't see why building on gcc4 shouldn't be a concern for a very long.
yes, sorry for the gcc4 sidetrack. my actual intent was to make sure we didn't
get sidetracked talking about gcc4 (for all the reasons you mentioned).
Boy, that sure worked out well.
(In reply to comment .
Fair enough. How about building without the cross-dev SDK using the older 3.3 compiler? Does this
even make sense or do you need to use the SDKs w/ 3.3?
Also, is there a better way to select the 3.3 compiler than sudo gcc_select? Something on a per build or
even per shell basis would be nicer.
When I try to set CC and CXX directly to the 3.3 versions and build I get the following error:
ld: Undefined symbols:
_fprintf$LDBLStub
_sprintf$LDBLStub
_vsnprintf$LDBLStub
Trying with gcc_select 3.3 now as I imagine just setting these directly isn't going to do the trick.
Adding "-nostdinc -F${MACOS_SDK_DIR}/System/Library/Frameworks" to CFLAGS and
"-nostdinc -nostdinc++ -F${MACOS_SDK_DIR}/System/Library/Frameworks" to CXXFLAGS
(in configure/configure.in) when $MACOS_SDK_DIR is set, seems to fix #6 for me.
(In reply to comment #1)
> Created an attachment (id=182336) [edit]
>
> 2. Make configure to check for the location of the sdp tool, and make sure it's
> used.
Do I need to run autoconf or something after applying the patch to make this work? I get the following:
...
/Users/sly/src/mozilla/mozilla/mozilla/config/nsinstall -L /Users/sly/src/mozilla/mozilla/mozilla/
xpfe/bootstrap/appleevents -m 644 libappleevents_s.a ../../../dist/lib
NEXT_ROOT= @SDP@ -fa -o mozillaSuite.r ./mozilla.sdef
/bin/sh: line 1: @SDP@: command not found
gmake[3]: *** [mozillaSuite.rsrc] Error 127
gmake[2]: *** [tier_50] Error 2
gmake[1]: *** [default] Error 2
gmake: *** [build] Error 2
(In reply to comment #10)
> Do I need to run autoconf or something after applying the patch to make this
> work? I get the following:
Yes, Cyrus, the patch changes configure.in, so you need to run autoconf to
generate a new configure.
Created attachment 182552 [details] [diff] [review]
A more complete fix, allows SDK builds too
(In reply to comment #9)
Good call, Peter.
Setting CFLAGS and CXXFLAGS alone won't do the trick, because configure doesn't
apply them when checking for header files. My initial thought was to set
CPPFLAGS, but there's no separate CXXCPPFLAGS, so it's kind of unclean. Also,
the CPPFLAGS get carried over into the build CFLAGS and CXXFLAGS, and all kinds
of ugly things start happening.
So I moved the check for CPP and CXXCPP up a little bit (not far). In the SDK
check, the appropriate flags get appended. It's only a tiny bit ugly, it does
the trick, and it shouldn't break anything.
I am using -isystem instead of -I to have the include directories treated as
system include directories. This avoids warnings about stddef.h redeclaring
wchar_t when compiling C++. I also fixed part of issue 5.
Using -nostdinc exposed a problem in gfx/cairo/cairo/src/cairo_atsui_font.c,
which was including iconv.h even though the code that requires that header is
in an #if 0. I put the include into an #if 0 as well. Important for SVG
builds, fixed here.
Created attachment 182554 [details] [diff] [review]
Oops, this one's better
CXXFLAGS should build on CXXFLAGS, not CFLAGS.
Created attachment 182555 [details] [diff] [review]
Last one tonight, I promise
CXXCPP should also use C SDK include directories.
I applied patch 4, but I the following errors came up when I ran the regenerated
configure.
checking whether gcc and cc understand -c and -o together... yes
./configure: line 6730: syntax error near unexpected token `macos-sdk,'
./configure: line 6730: `MOZ_ARG_WITH_STRING(macos-sdk,'
*** Fix above errors and then restart with "make -f client.mk build"
make: *** [/Users/dave/src/mozilla/Makefile] Error 1
Although I am not sure if I regenerated configure properly.
Created attachment 182578 [details] [diff] [review]
Only use -nostdinc for /usr/include, append includes to C(XX)FLAGS instead of prepend
It seems that any headers included in an isystem directory are implicitly
treated as extern "C", no good for C++.
I'm now using a Firefox produced by this patch, and am building a Seamonkey.
(In reply to comment #15)
Dave, you shouldn't have that text anywhere in configure, autoconf should have
transformed it when reading it from configure.in. Be sure that you can build a
usable configure with an unpatched configure.in first. The correct way to
build configure is to run autoconf while in the same directory as configure.in,
you need to be using autoconf 2.13 (not 2.5 or later) to do this.
well for what its worth I used autoconf 2.13, inside mozilla source directory
where configure.in is, but I still get the following error.
./configure: line 2689: syntax error near unexpected token `macos-sdk,'
./configure: line 2689: `MOZ_ARG_WITH_STRING(macos-sdk,'
This is with and without the patch applied.
note that for whatever patch is produced here, the only option we will check in
is building *with* the SDK. Using the 10.2.8 SDK is a requirement for builds we
distribute. Any solution needs to ensure that works.
also, i think the version of autoconf that moz requires is different (earlier)
from the one that ships with the OS. I seem to recall issues with this in the
past. bryner would remember for sure.
mozilla requires the fink autoconf (v 2.13). The one that ships with the dev
tools won't work with mozilla. You can tell if you have the right one by doing
'which autoconf' and if it's in /sw/bin, you're ok.
building with the patch now.
when i build camino (with the 10.2.8 sdk), I get:
ld: Undefined symbols:
_MOZ_Z_crc32
_MOZ_Z_inflateReset
_MOZ_Z_inflateEnd
_MOZ_Z_inflateInit_
_MOZ_Z_inflate
make[4]: *** [libimglib2.dylib] Error 1
Not building on Tiger could be a 1.1 blocker. I am using Tiger, and it is far better than Panther.
Requesting 1.1 blocker flag.
pink: are you doing a clobber build? The explanation that immediately jumps to
mind is that you did a build --without-system-zlib (or nothing at all, it's the
default) and are now doing a depend build --with-system-zlib over that. I don't
get this error on a clobber build (or depend builds with the same
configuration), and I'm going with the default which gives
--without-system-zlib. I've made a couple of changes since the last patch I
posted, but nothing that should affect this.
Is libimglib2.dylib being linked against -lmozz?
Does nm dist/lib/libmozz.dylib look sane?
This shouldn't block 1.1 because it doesn't affect usage, only building.
Re pink's zlib problem: on the second thought, it sounds like the problem is
limited to crc32.c and inflate.c in modules/zlib/src. Can you check on the cc
for both of those, see if anything fishy is happening, and look at what symbols
they produce?
Ok. I hope it will get fixed soon, as Tiger is going to be a great success...
My last useless comment on this bug ;)
I am attempting to compile firefox with patch #5 but the build fails with the
following error:
c++ -o firefox-bin -fno-rtti -fno-exceptions -Wall -Wconversion -Wpointer-arith
-Wcast-align -Woverloaded-virtual -Wsynth -Wno-ctor-dtor-privacy
-Wno-non-virtual-dtor -Wno-long-long -fast -mcpu=7450 -fpascal-strings
-no-cpp-precomp -fno-common -fshort-wchar -I/Developer/Headers/FlatCarbon -pipe
-DNDEBUG -DTRIMMED -fast -mcpu=7450 nsBrowserApp.o nsStaticComponents.o
-L../../dist/bin -L../../dist/lib -L../../dist/lib/components -lxpcom_compat_c
-lxpconnect -luconv -lucvmath -li18n -lnecko -lnecko2 -ljar50 -lpref -lcaps
-lrdf -lhtmlpars -lgfx_mac -limgicon -limglib2 -lgkplugin -lwidget_mac
-lgklayout -ldocshell -lembedcomponents -lwebbrwsr -leditor -ltxmgr -lnsappshell
-loji -laccessibility -lchrome -lmork -lmozfind -lappcomps -lcommandlines
-ltoolkitcomps -lpipboot -lpipnss -lpippki -lcookie -lxmlextras -lautoconfig
-ltransformiix -luniversalchardet -lwebsrvcs -lpermissions -lsearchservice
-lbrowsercomps -lunicharutil_s -lucvutil_s -lgfxshared_s -lgkgfx -ljsj
-lxulapp_s ../../dist/lib/libxulapp_s.a -L../../dist/bin -lmozjs
-L../../dist/bin -lxpcom -lxpcom_core -L../../dist/lib -lplds4 -lplc4 -lnspr4
-lpthread -framework Cocoa -framework Carbon -framework QuickTime -framework
IOKit -lm -L../../dist/lib/components -L../../dist/lib -lmozpng
-L../../dist/lib -lmozjpeg -L../../dist/lib -lmozz -L../../dist/bin
-L../../dist/lib ../../dist/lib/libcrmf.a -lsmime3 -lssl3 -lnss3 -lsoftokn3
-L../../dist/lib -lxpcom_compat
ld: warning suggest use of -bind_at_load, as lazy binding may result in errors
or different symbols being used
ld: Undefined symbols:
__ZThn4_N17nsHashPropertyBag11GetPropertyERK9nsAStringPP10nsIVariant
__ZThn4_N17nsHashPropertyBag13GetEnumeratorEPP19nsISimpleEnumerator
__ZThn4_N17nsHashPropertyBag17GetPropertyAsBoolERK9nsAStringPi
__ZThn4_N17nsHashPropertyBag17SetPropertyAsBoolERK9nsAStringi
__ZThn4_N17nsHashPropertyBag18GetPropertyAsInt32ERK9nsAStringPi
__ZThn4_N17nsHashPropertyBag18GetPropertyAsInt64ERK9nsAStringPx
__ZThn4_N17nsHashPropertyBag18SetPropertyAsInt32ERK9nsAStringi
__ZThn4_N17nsHashPropertyBag18SetPropertyAsInt64ERK9nsAStringx
__ZThn4_N17nsHashPropertyBag19GetPropertyAsDoubleERK9nsAStringPd
__ZThn4_N17nsHashPropertyBag19GetPropertyAsUint32ERK9nsAStringPj
__ZThn4_N17nsHashPropertyBag19GetPropertyAsUint64ERK9nsAStringPy
__ZThn4_N17nsHashPropertyBag19SetPropertyAsDoubleERK9nsAStringd
__ZThn4_N17nsHashPropertyBag19SetPropertyAsUint32ERK9nsAStringj
__ZThn4_N17nsHashPropertyBag19SetPropertyAsUint64ERK9nsAStringy
__ZThn4_N17nsHashPropertyBag20GetPropertyAsAStringERK9nsAStringRS0_
__ZThn4_N17nsHashPropertyBag20SetPropertyAsAStringERK9nsAStringS2_
__ZThn4_N17nsHashPropertyBag21GetPropertyAsACStringERK9nsAStringR10nsACString
__ZThn4_N17nsHashPropertyBag21SetPropertyAsACStringERK9nsAStringRK10nsACString
__ZThn4_N17nsHashPropertyBag22GetPropertyAsInterfaceERK9nsAStringRK4nsIDPPv
__ZThn4_N17nsHashPropertyBag22SetPropertyAsInterfaceERK9nsAStringP11nsISupports
__ZThn4_N17nsHashPropertyBag24GetPropertyAsAUTF8StringERK9nsAStringR10nsACString
__ZThn4_N17nsHashPropertyBag24SetPropertyAsAUTF8StringERK9nsAStringRK10nsACString
symbol _libVersionPoint used from dynamic library
../../dist/bin/libplc4.dylib(plvrsion.o) not from earlier dynamic library
@executable_path/libplds4.dylib(plvrsion.o)
make[4]: *** [firefox-bin] Error 1
make[4]: Leaving directory
`/Users/dave/src/mozilla/obj-powerpc-apple-darwin8.0.0/browser/app'
make[3]: *** [libs] Error 2
make[3]: Leaving directory
`/Users/dave/src/mozilla/obj-powerpc-apple-darwin8.0.0/browser'
make[2]: *** [tier_99] Error 2
make[2]: Leaving directory `/Users/dave/src/mozilla/obj-powerpc-apple-darwin8.0.0'
make[1]: *** [default] Error 2
make[1]: Leaving directory `/Users/dave/src/mozilla/obj-powerpc-apple-darwin8.0.0'
make: *** [build] Error 2
pink: I was backwards on that default for with-system-zlib, but I am able to
build through libimglib2.dylib both with-system-zlib and without-system-zlib.
Dave: don't use -fast/-O3, there are known problems with certain optimizations
(you know who you are, <cough>finline-functions<cough>) in GCC 3.3. This is
invalid bug 289586. Give it another shot with -O2 or less, or -Os. Initial
testing is always better with conservative optimization.
Applied patch and nothing works :(
Still blocked with a configure message saying :
checking for correct temporary object destruction order... no
configure: error: Your compiler does not follow the C++ specification for
temporary object destruction order.
*** Fix above errors and then restart with "make -f client.mk build"
make: *** [/Users/frederic/Documents/logs/fox/mozilla/Makefile] Error 1
My .mozconfig :
. $topsrcdir/browser/config/mozconfig
ac_add_options --disable-debug
ac_add_options --disable-tests
ac_add_options --enable-optimize="-Os -faltivec -mcpu=7450 -mtune=7450 -mpowerpc
-mpowerpc-gfxopt"
ac_add_options --enable-strip
ac_add_options --enable-prebinding
ac_add_options --enable-static
ac_add_options --disable-shared
ac_add_options --enable-svg
ac_add_options --with-macos-sdk=/Developer/SDKs/MacOSX10.2.8.sdk
Any tips to help ?
Removing SDK line cure the last line bug ?!
A problem in gcc version selection ?!
i'm building with the standard camino mozconfig
mozilla/camino/config/mozconfig
which uses the system zlib. i'm pretty sure that this was a clobber build, but i
can distclean again when i get home just to make sure.
Frederic, be sure you're not trying to use gcc 4. I've only seen that problem
in relation to gcc 4. The destructors fire properly, but compiling the test
program produces some junk on stderr. If you're not using gcc 4, look in
config.log to see what's happening.
Kinda stupid question. But how can I be sure that gcc 3.3 is used ?
I had both of them on my computer.
I will try to look at config.log and tell you what version is used, but I think
it is not gcc 3.3 :(
By the way, how can I be 100% sure to get gcc 3.3 used instead of gcc 4.0 ?
$ gcc_select
will tell you the currently selected gcc version. the default is gcc4, so if
you haven't done anything, you'll be on gcc4. To change it, run
$ sudo gcc_select 3.3
Oups ! I thought configure will choose right gcc... So, if I understand well, I have to choose gcc 3.3 for
now, until a new gcc 4.0 is out from Apple and cures the other known gcc 4.0 bug under OSX ?
we need to choose gcc3.3 until mozilla drops support for anything before 10.3.9,
which will be a long time.
Well, I will not build for a long time firefox because of fink not being
available in a binary version for 10.4
When I use gcc_select 3.3, I cannot get libIDL to be detected...
Strange. Configure says me : libIdl >= 0.6.3 : no
But I had built libIdl 0.6.8 :(
/me is kinda fed up :(
Created attachment 182701 [details] [diff] [review]
v6
Changes since v5:
- Determine GCC_VERSION even without SDK build so xcodebuild can use it
- Export GCC_VERSION to the environment for xcodebuild
- Do correct GCC_VERSION computation in preparation for gcc 4
- Warn when gcc 4.0.0/4061 is used (hopefully avoiding the issue being
reported)
- Configure should fail when --with-macos-sdk doesn't point to a valid SDK
- Warn during SDK build when libIDL-config is found but libIDL can't be used,
suggest a workaround
- Remove dependency on /usr/lib/libstdc++.a in
modules/plugin/samples/default/mac/DefaultPlugin.pbproj
- Camino default target (Camino) asks for -lmozz and attempts to copy
libmozz.dylib even though the default mozconfig specifies --with-system-zlib
Open issues:
-.
- NSS never builds with an SDK specified, because it's got its own weird
configuration system and it doesn't listen to $CFLAGS. NSS is also the only
part of the build that doesn't respect $CC. Bug 93206 (CC), bug 101249
(CFLAGS).
- Should we set MACOSX_DEPLOYMENT_TARGET for ld when --macos-target is
specified?
These two aren't really showstoppers and they've been present all along, but
the behavior with these problems isn't strictly correct and it COULD pose a
problem.
Other notes:
- In configure, why are NEXT_ROOT and LIBS being unset and then reset during
the libIDL check?
- When building camino, I've never been able to build with xcodebuild, I can
only do it in Xcode.app. With this patch, I am able to build Camino under
Tiger by running make and then opening Camino.xcode in Xcode when make dies.
I used to have exactly the same problem under Panther.
- Xcode 2 (the app) seems really crashy and screwed up.
Re comment 8, I tested this with setting CC and CXX to the 3.3 versions while
gcc_select was set to 4, and it now works properly. I don't recommend it
though, in light of the NSS problem.
Re comment 36, Frederic, please read the last part of comment 0, and then edit
libIDL.h so that wchar.h is no longer included. As of v6, configure will print
a warning about this, but it's not fatal so you need to watch for it. This
patch will cause this same problem on 10.3 build hosts too. It really is the
correct behavior, but the build machines will need to be checked and fixed
before this patch is checked in.
Mark
Thanks for your answer. I will try to tweak libIDL.h and comment line including
wchar.h
Let's hope it will work this time...
FWIW, I finally succeeded in compiling a non-optomized debug version of
SeaMonkey trunk with v5 of this patch under Tiger, with fink (selfupdated to
0.23.8)/fink autoconf 2.13/gcc 3.3 on my PB...
Well, patch 6 + libIDL.h tweaking works.
Posting using a Tiger build of Firefox 1.0+ !
About:buildconfig says :
"about:buildconfig
Build platform
target
powerpc-apple-darwin8.0.0"
Let's hope building on Tiger will get simpler soon. Let's see for thunderbird,
now ;o)
this is posted with camino debug, built from patch v6. awesome!!!
we should ensure that this patch still builds on panther (since tht's what the
nightlies and tinderboxen run).
fwiw, i didn't need to tweak libIDL (i still use the fink binaries that i
upgraded from 10.3) and i built camino straight-through from the command line. I
didn't have to open the xcode project to finish building. I wonder what is
different in your setup that you need to do that.
I tried building with the patch, and I'm getting this error:
In file included from xpidl.c:42:
xpidl.h:53:24:In file included from xpidl_idl.c:43 libIDL/IDL.h: No such file or
directory
IDL.h is located in /sw/include/libIDL-1.0/libIDL/IDL.h, and I'm using the same
fink binary install as I was in 10.3
Mike, I made a really clean install of tiger. I prefer doing this than a
"archive and install" installation.
Let's hope panther could built it too ;o)
/me wants to see this bug closed as FIXED ;)
Created attachment 182752 [details] [diff] [review]
v7
v6-v7:
- Remove space between -I and dir for C++ include directories
- Handle configure brain death for GSS gracefully
Glad to have some positive feedback - we're well on the way!
The major update here is that negotiateauth is restored for SDK builds. I
don't think anyone else noticed it was gone (yet). configure handles the check
for GSS pretty stupidly. It checks for it in a hard-coded location, /usr.
That won't work for an SDK build, when we need to keep our filthy mitts out of
/usr. Building on 10.4, configure detected major trouble and disabled
negotiateauth. Building on 10.3, there was no major conflict at configure
time, so -I/usr/include and -L/usr/lib went right back in, and the build would
fail in extensions/negotiateauth due to a header conflict.
jwa: the most likely cause for that error is that you didn't edit IDL.h to not
include wchar.h.
Mike: I'm surprised that your IDL.h didn't need adjustment. wchar.h was added
in 10.3, is it possible that your libIDL installation goes back further than
that? For what it's worth, I'm using the same libIDL that I was using in 10.3
too (but not 10.2).
Believe it or not, my xcodebuild problem with Camino was caused by having CC
set in the environment. It doesn't like CC in there at all, even if it's set
to a full path or if it's present but empty. And it only affects certain parts
of the project: AddressBookManager.o won't build, but the pref panes will.
Weird.
I am testing on 10.3 (using Xcode 1.1 against the 10.2.7 SDK - it's not a
computer I normally do dev on, so the toolchain is a little behind) as well as
10.4. I'd appreciate it if other folks could test 10.3 (and 10.2) too. There
are already a couple of caveats with this patch (libIDL.h), I really want to
avoid regressions.
Tested with Thunderbird - OK.
I'd like to hear others' thoughts on the open issues in comment 37.
> Camino uses the 10.2.8 SDK because its pbproj is hard-wired.
we should probably keep it this way, as if we set it only from the makefile, it
wouldn't be available when you built w/in xcode while developing.
i tested v7 on my panther box that i use for camino dev at work and it built
w/out modification to any files.
My only problem now seems to be the patches v6 - v7 do not apply cleanly if I
only checkout "browser" source form the tree.
The rest of the patch excluding patching
'mozilla/camino/Camino.xcode/project.pbxproj' applies cleanly.
Is they anything that can be done about the link error from comment #26 ? Or do we wait for
apply to fix their compiler.
(In reply to comment #47)
> we should probably keep it this way, as if we set it only from the makefile,
> it wouldn't be available when you built w/in xcode while developing.
I was thinking that we could transform the pbxproj file by substituting SDKROOT
at or after configure time. This is fine for objdir builds, and the more I
think about it, the more I don't hate the idea for non-objdir builds either. I
might like it better if the pbxproj file was renamed to pbxproj.in or something..
It's less of an issue for Camino than it is for the other pbxprojs, although if
I can come up with something that works well for those without hurting Camino,
it would make sense there too.
(In reply to comment #48)
> My only problem now seems to be the patches v6 - v7 do not apply cleanly if I
> only checkout "browser" source form the tree.
That's expected. Just let patch skip that file.
> Is they anything that can be done about the link error from comment #26
That's a different bug (bug 289586) that most likely won't be fixed because it's
a compiler problem. If you've got questions about it, please ask them in that bug.
(In reply to comment #49)
>.
I do that from time to time, using xcode to look at source or edit Camino files
on a clean tree before I build. *shrug*. Simon may have more of an opinion here.
cc'ing simon ;)
with v7, build process is crashing saying :
"nsFileSpec.cpp
c++ -o nsFileSpec.o -c -DMOZILLA_INTERNAL_API -DOSTYPE=\"Darwin8.0.0\"
-DOSARCH=\"Darwin\" -DBUILD_ID=2005050707 -D_IMPL_NS_COM_OBSOLETE -I.. -I./../io
-I../../dist/include/xpcom -I../../dist/include/string
-I../../dist/include/macmorefiles -I../../dist/include/xpcom_obsolete
-I../../dist/include -I../../dist/include/nspr -I../../dist/sdk/include
-I/usr/X11R6/include -fPIC -nostdinc
-nostdinc++ -I/Developer/SDKs/MacOSX10.2.8.sdk/usr/include/gcc/darwin/3.3/c++
-I/Developer/SDKs/MacOSX10.2.8.sdk/usr/include/gcc/darwin/3.3/c++/ppc-darwin
-I/Developer/SDKs/MacOSX10.2.8.sdk/usr/include/gcc/darwin/3.3/c++/backward
-isystem /Developer/SDKs/MacOSX10.2.8.sdk/usr/include/gcc/darwin/3.3 -isystem
/Developer/SDKs/MacOSX10.2.8.sdk/usr/include
-F/Developer/SDKs/MacOSX10.2.8.sdk/System/Library/Frameworks
-F/Developer/SDKs/MacOSX10.2.8.sdk/Library/Frameworks -fpascal-strings
-no-cpp-precomp -fno-common -fshort-wchar
-I/Developer/SDKs/MacOSX10.2.8.sdk/Developer/Headers/FlatCarbon -pipe -DNDEBUG
-DTRIMMED -Os -I/Developer/SDKs/MacOSX10.2.8.sdk/Developer/Headers/FlatCarbon
-I/usr/X11R6/include -DMOZILLA_CLIENT -include ../../mozilla-config.h
-Wp,-MD,.deps/nsFileSpec.pp nsFileSpec.cpp
In file included from nsFileSpec.cpp:520:
nsFileSpecUnix.cpp:59:25: sys/statvfs.h: No such file or directory
make[3]: *** [nsFileSpec.o] Error 1
make[2]: *** [tier_2] Error 2
make[1]: *** [default] Error 2
make: *** [build] Error 2"
Sources up-to-date 10:00pm mozilla.org time.
Any explanation ?
(In reply to comment #52)
You edited .mozconfig to switch from a non-SDK build to an SDK build without
dumping the results of the non-SDK build. Remove objdir or run make distclean
(make clean is insufficient), and try again. It's not safe to change the SDK
setting without rebuilding everything.
Well, it looks like I made a mistake somewhere. Retrying with a blank new source
right now ;)
/me is sorry for spamming the bug :(
Seamonkey can be build too (patch v7 too)
And the bug I reported before was my fault. I forgot to launch autoconf after
using the patch.
Created attachment 182874 [details] [diff] [review]
v8
Changes between v7 and v8
- handle SDK builds properly in nsprpub (SDK taken from $NEXT_ROOT). You
now must run autoconf in nsprpub as well as in the top level.
- fix libgfx_mac.dylib build to link Mozilla libraries before Carbon
framework
- configure: use $PERL instead of perl
- set up include and lib directories properly for gcc 4 SDK builds
- only use -F$MACOS_SDK_DIR/Library/Frameworks if it exists, avoiding ld
warnings
Most of these changes are self-explanatory. The libgfx_mac.dylib fix is
necessary because the 10.3.9 SDK's CFNetwork framework defines PR_Realloc and a
few other things included in NSPR. Since these aren't present in libSystem in
10.4, a Panther-targeted build will not run on Tiger if it depends on those
symbols being in libSystem. -framework Carbon needs to be moved after -lnspr4
when ld creates libgfx_mac.dylib.
Still pressing, getting closer...
Mark
Created attachment 182879 [details] [diff] [review]
v9
v8 was missing the libgfx_mac fix, v9 includes it
I've tried to follow this thread by downloading the latest source from cvs,
applying the patch (which applied successfully, BTW) and running autoconf.
However, autoconf didn't work for me, it returned the following:
build/autoconf/altoptions.m4:156: error: m4_defn: undefined macro:
_m4_divert_diversion
build/autoconf/altoptions.m4:153: MOZ_READ_MOZCONFIG is expanded from...
build/autoconf/altoptions.m4:156: the top level
autom4te-2.59: /sw/bin/gm4 failed with exit status: 1
(In reply to comment #58)
> I've tried to follow this thread by downloading the latest source from cvs,
> applying the patch (which applied successfully, BTW) and running autoconf.
> However, autoconf didn't work for me
You need to use autoconf 2.13. Later versions, including the 2.59 that ships in
/usr/bin, are incompatible. Since you seem to have fink, "fink install
autoconf" should give you 2.13 in /sw/bin/autoconf.
(In reply to comment #37)
> -.
I found that Camino respects SDKROOT passed in via the environment or on the
xcodebuild command line. So it should be possible to handle this without
dynamically modifying any of the project files. That's nice and clean..
> - Should we set MACOSX_DEPLOYMENT_TARGET for ld when --macos-target is
> specified?
I think this is probably a good idea.
Last patch is working, but it is harder and harder to use it :)
A simple question : can I use gcc_select 4.0 or not, now ?
Any nspr problem with that idea ?
> A simple question : can I use gcc_select 4.0 or not, now ?
Yes and no. v8/v9 set up SDK builds to work with gcc 4, so the configure and
build system is ready. But gcc 4 still won't work for reasons that have been
covered already, and the question really is spam in this bug. This patch only
covers the configure and build system, the fact still remains that gcc 4 on the
Mac is broken in ways beyond our control at the moment. See comment 6 and
comment 35. I do plan on prepping the Mac-specific parts of the codebase for
gcc 4 as soon as I'm done here unless someone else gets it first, but the
results of that work still won't allow you to build a usable 'zilla with that
compiler.
v9 works for me with gcc 3.3 and /Developer/SDKs/MacOSX10.3.9.sdk.
I didn't have to edit IDL.h either (I installed Fink 0.7.1 using the binary
installer and installed binary packages for orbit, etc).
(In reply to comment #63)
> v9 works for me with gcc 3.3 and /Developer/SDKs/MacOSX10.3.9.sdk.
> I didn't have to edit IDL.h either (I installed Fink 0.7.1 using the binary
> installer and installed binary packages for orbit, etc).
You don't need to edit IDL.h to target the 10.3.9 SDK. 10.3 includes wchar.h.
Pre-10.3 systems, and thus pre-10.3 SDKs, don't have it.
One behavior I don't like is that if ORBit is found, configure just assumes that
libIDL works without testing it. That means that it can't return a hard error
at configure time, and instead the build dies during make for reasons that may
seem unrelated to libIDL. Especially now that IDL.h might not work without
tweaking, I think that it might be prudent for configure to actually test the
libIDL installation pointed to by orbit-config.
(In reply to comment #60)
>.
SDKROOT and various other settings work for native targets but not for legacy
targets. Currently, DefaultPlugin and PrintPDE use jam (legacy) targets.
Camino on the trunk was upgraded to use native targets. Native targets only
function in Xcode (1.0 and up) and are not compatible with the older DT Project
Builder. Xcode 1.0 requires (and shipped with) 10.3.
If upgraded to native targets, xcodebuild will build these projects respecting
any SDKROOT passed on the command line, and the command-line option will
override anything in the pbproj. With the current Camino pbproj and mozconfig,
the build products will not change at all, and building from within Xcode.app
will still work. Perfect.
So the question now is: is it OK to require 10.3 to build? Currently, the
Mozilla minimum requirement is 10.2, but trunk Camino requires 10.3. Even if we
upgrade the pbproj files so that they require Xcode, the older project files
could still be distributed and configure could be used to select which project
to use based on which build system is being used. The only problem then is that
the legacy project would be prone to falling out of sync, but there aren't many
changes to either of the two projects in question.
I'd be surprised if any builders are still working with 10.2, but a big part of
me doesn't want to break this when a fix would be so trivial.
it depends on how much you want to allow individual build environments to differ
from the production environment distributing binaries. All the tinderboxen and
nightly build machines are running panther and using the SDK to target 10.2.8
(even for seamonkey and firefox).
sure, building on 10.2 still works, but it might cause people to make changes
that have issues on the panther-based production machines w/out knowing it.
Created attachment 183112 [details] [diff] [review]
v10
Changes between v9 and v10
- Much nicer handling of IDL that won't require anyone to edit any
files on their systems. If you edited IDL.h, please undo your
changes. If you were lucky enough to not have had to edit IDL.h,
there are still some other goodies for you in this patch.
- Check for usability of libIDL found via ORBit rather than assuming
it will work. This means problems with IDL.h will be treated as
hard errors at configure time, rather than at compile time. This
change is for all platforms.
- Do a better job with the check for GSS, to avoid adding unnecessary
-I and -L flags that point to already-included directories. This
change is for all platforms.
- Do not link Camino with libmozz for statically linked target
(already covered non-static target).
- Upgrade DefaultPlugin and PrintPDE to native targets, they now require
Xcode.
- Set GCC_GENERATE_DEBUGGING_SYMBOLS=NO for Deployment styles (was
already set in Camino).
- Turn on GENERATE_PKGINFO_FILE for DefaultPlugin target
- Pass these settings to xcodebuild on the command line:
- GCC_VERSION is now on the command line (it was in the environment
in previous patches), USE_GCC3 can be removed from the Camino
command line since GCC_VERSION replaces it.
- SDKROOT, only set for SDK builds. xcodebuild handles the SDK logic.
- OPTIMIZATION_CFLAGS, only set if --enable-optimize had an argument
in .mozconfig. Otherwise, the project's default optimization is
used. GCC_MODEL_TUNING is set to empty to prevent Xcode from
asking the compiler for -march, since the configuration's
optimization specifications should be respected.
- OTHER_CFLAGS gets the defines to enable or disable debugging.
- MACOSX_DEPLOYMENT_TARGET when so requested (see below).
- nspr uses OS_LIBS and not LIBS.
- Propagate SDK-specifying CFLAGS (only) to XCFLAGS for NSS build. The
entire tree should now properly built against the selected SDK.
- Export MACOSX_DEPLOYMENT_TARGET to the environment if
--enable-macos-target is specified. This lets ld take advantage of
features only available in later OS versions. --enable-macos-target
remains independent of --with-macos-sdk.
I realized that IDL.h is only needed for xpidl, and xpidl only needs to run on
the build host. Using the SDK to build xpidl is unnecessary. The logic to
handle this was already partially in place, except SDK castration was only
being handled for ld and not for cc.
Builds now require 10.3 and Xcode (not sure if there's a minimum Xcode version,
but I'm testing with Xcode 1.1 now). Mike was right: as soon as I had
converted the projects, I needed to make some changes, and I saw how tedious it
would have been to maintain the old Project Builder-compatible projects. If
you need to build on 10.2, speak now or forever hold your peace.
The patch should be just about complete now. Bang on it and let me know what
you've got it building (or not).
Notes for checkin time: remove/add these:
REM embedding/components/printingui/src/mac/printpde/PrintPDE.pbproj/
REM
embedding/components/printingui/src/mac/printpde/PrintPDE.pbproj/project.pbxproj
REM modules/plugin/samples/default/mac/DefaultPlugin.pbproj/
REM modules/plugin/samples/default/mac/DefaultPlugin.pbproj/project.pbxproj
ADD embedding/components/printingui/src/mac/printpde/Info-PrintPDE.plist
ADD embedding/components/printingui/src/mac/printpde/PrintPDE.xcode/
ADD embedding/components/printingui/src/mac/printpde/PrintPDE.xcode/ADD
project.pbxproj
ADD modules/plugin/samples/default/mac/Info-DefaultPlugin.plist
ADD modules/plugin/samples/default/mac/DefaultPlugin.xcode/
ADD modules/plugin/samples/default/mac/DefaultPlugin.xcode/project.pbxproj
Also, remember that Camino builds --without-system-zlib are probably broken
now.
Mark
Tiger with gcc 3.3
Patch : v10
SDK used : 10.3.9
Building successfully : firefox and Thunderbird (both with sources up-to-date at
10:00pm mozilla.org time)
Did not try building camino for now. Will try later :)
Created attachment 183156 [details] [diff] [review]
v11
Changes between v10 and v11
- Turn GENERATE_PKGINFO_FILE back off for DefaultPlugin target and
generate the PkgInfo file in the Makefile. GENERATE_PKGINFO_FILE was
added in Xcode 1.2 and does not work with Xcode 1.1. This patch was
tested successfully with Xcode 1.1 and Firefox; Camino is building now.
- Camino Makefile.in changes were not included in v10, so PBBUILD_SETTINGS
weren't being passed to xcodebuild. For those of you who don't check out
camino, you'll now need to let patch skip the first two files.
- unexport CC and CXX in Makefiles that call xcodebuild to avoid problems
(comment 45). These cropped up with PrintPDE too once it was converted to
a native target when CC was set in the environment. As long as selected
compiler is an Apple-provided one, xcodebuild is still able to find and use
the proper compiler based on the GCC_VERSION setting.
- Part of the Camino.xcode/project.pbxproj patch got checked in yesterday
(v1.67), don't include that fragment in the patch to keep it up-to-date.
oops, i didn't mean to check that in just yet. :) what's the impact, or should i
back it out?
also, at what point do we want to try to get this reviewed and landed? I'm all
for fixing stuff, but can we land it and then refine it further so people can
build w/out needing to know about this bug?
The only change that got checked in removed -lmozz from the Camino nonstatic
build (but didn't remove the libmozz dependency?)
I wasn't ready to ask for review yet before because there was still too much
stuff that was broken. The IDL situation, for example. I'm pretty confident in
it now, and I was planning on asking for review (prolly from you, with sr from
bryner) later today or tomorrow unless any big bugs popped up.
i'm not a good person for review, i don't know most of the make machinery.
'K. I guess seawood'll be my victim then.
I think we need to see this patch split into 3 pieces, at least:
- changes to the Mozilla core to permit it to build on Tiger
- changes to Camino to permit it to build on Tiger
- other build-system enhancements
That will make it much more likely that we get good review on those pieces, and
get them in promptly. There are some pieces that I don't understand, like why
the existing HOST_PROGRAMS stuff doesn't work for xpidl, but I'd rather make
sure I'm looking at the right (necessary) parts, and that I can get build-system
folks to look at them as well.
Mark, have you tested this patch on any other platform (Win32, Linux), just to
be sure your cross platform changes are legit?
Created attachment 183164 [details]
v11, annotated
Shaver: Most of the patch is required for either 10.4 builds or SDK builds on a
10.4 host. Both are essential. I looked at splitting it, and there are no
really clear boundaries, except for the stuff that's Camino-only in the first
couple of files.
I've annotated the patch with a brief description of each fragment, and my
assessment of whether or not the change is required or an enhancement. Note
that even most of the enhancements are in there to enforce the application of
an SDK when one is selected - while they're not strictly necessary to build and
run, they're mandatory for correctness, and are waiting to become problems the
next time Apple changes a header file if they're not addressed.
I've also marked off what each change is needed for (Camino, SDK builds, 10.4
builds, any Mac builds, etc.)
As for the xpidl HOST_PROGRAMS stuff: it would probably work (although we'd
still need a special case since a normal cross build isn't set up and we'd
still need to pull NEXT_ROOT out of the environment.) I didn't do that because
the OS X SDK was already special-cased for xpidl and that seemed like the
proper place to handle it.
Javier: I haven't tested on non-Mac platforms, but I've marked in the annotated
patch the fragments that affect other platforms.
Just built with this patch on Linux, and it worked as expected (no build breaks,
browser comes up, no noticeable differences between patched and non-patched builds).
I must not have made myself clear, for which I apologize.
I want to see the patch split up. I am not arguing against making the build
system more future proof, or "correct", or whatever. I am arguing against
presenting this patch at a 65K monolith.
Once we build on Tiger, we can fix the build to work on other future updates and
so forth. Mixing these things together makes it harder to review, and ties the
necessary build-on-Tiger fixes to the other enhancements and Camino fixes.
(Which latter should almost certainly be reviewed separately, if only because
they apparently break build-on-Jaguar.)
Factoring and applying an annotated patch sounds like a pretty painful
experience, given how context matching works, so I think it'd be best to split
them into 3 of the categories you've outlined (SDK-usage fixes, camino fixes,
core 10.4-build fixes), and attach separate patches. And when you asked for my
review, you asked what I thought. =)
Created attachment 183236 [details] [diff] [review]
Phase 1: Allow SDK-less builds on 10.4
Mike, that makes much more sense. I think I was getting caught up in the
delineations. These categories make sense.
Phase 1: Allow SDK-less builds on 10.4
- build: Handle now-variable location of sdp tool
- xpcom/MoreFiles: Work around redefinition of prototype
- modules/libreg/src/vr_stubs.c: Do not implement strdup
Created attachment 183237 [details] [diff] [review]
Phase 2: Allow SDK-ful builds on 10.4
Phase 2: Allow SDK-ful builds on 10.4
- configure.in: Logic reorganization to accommodate
- configure.in: Much better handling of CFLAGS, CXXFLAGS, and LIBS needed
for SDK builds
- configure.in: GSSAPI check does not use -I/-L to find GSSAPI in system
directories
- configure.in: do libIDL checks without SDK as IDL is only needed by the
build host
- xpcom/typelib/xpidl/Makefile.in: do xpidl build without SDK for reason
above
- extensions/java/xpcom/tools/xpidl/Makefile.in: as above
- gfx/cairo/cairo/src/cairo_atsui_font.c: wrap unused iconv.h in #if 0
(the implementation that depends on the header is already inside #if 0)
- gfx/src/mac/Makefile.in: link with Carbon framework after NSPR
libraries
Created attachment 183238 [details] [diff] [review]
Phase 3: Correct behavior for all non-core parts of the build system
Phase 3: Correct behavior for all non-core parts of the build system
(Make them respect the selected SDK)
- build: send SDKROOT to xcodebuild
- embedding/components/printingui/src/mac/printpde: update Xcode project
to native target to handle SDK for Xcode projects
- modules/plugin/samples/default/mac: as above
- nsprpub/configure.in: handle SDK for NSPR
- security/manager/Makefile.in: handle SDK for NSS
This patch is not as large as it seems - the old pbproj directories disappear
and are replaced by new xcode directories, accounting for 2/3 of the bulk of
this guy.
Created attachment 183239 [details] [diff] [review]
Phase 4: Miscellaneous enhancements
Phase 4: Miscellaneous enhancements
- build: Set MACOSX_DEPLOYMENT_TARGET for ld when the configure option
--enable-macos-target is used
- build: Pass a variety of other settings to Xcode projects being built:
GCC_VERSION, MACOSX_DEPLOYMENT_TARGET, GCC_MODEL_TUNING,
OPTIMIZATION_CFLAGS, and OTHER_CFLAGS
- configure.in: Soft warning when using the default compiler shipping
with 10.4, it is buggy
- configure.in: Hard error if specified SDK is missing
- configure.in: When finding libIDL via ORBit, check to make sure it is
usable
Created attachment 183240 [details] [diff] [review]
Phase 5: Camino fixes
Phase 5: Camino fixes
- Do not depend on libmozz in the Xcode project, Camino should be using
--with-system-zlib
- Accept xcodebuild settings to properly set selected SDK
Comment on attachment 183240 [details] [diff] [review]
Phase 5: Camino fixes
These guys are meant to be applied in order. Although I haven't tested them
individually, they were tested as a whole (v11). Except for phase 5, I'm not
sure who to tag for review.
There was one change since v11: there were two checks for
MACOSX_DEPLOYMENT_TARGET when one would have done, this is in phase 4.
Cannot apply patch phase 1, patch says :
$ patch -p0 < 292530.ph1.1.patch
can't find file to patch at input line 3
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|--- mozilla/config/autoconf.mk.in.dist 2005-04-22 16:58:52.000000000 -0400
|+++ mozilla/config/autoconf.mk.in.ph1 2005-05-10 19:23:20.000000000 -0400
--------------------------
File to patch:
What's the problem here ? Patch v11 is working well :(
(In reply to comment #86)
> Cannot apply patch phase 1, patch says :
That's a patch to config/autoconf.mk.in, I forgot to update the filenames in it
so they're artifacts of how I generated the patch.
If you apply patches ph1 through ph5 in sequence, you'll get the same result as
v11, with the one minor change mentioned in comment 85.
Comment on attachment 183164 [details]
v11, annotated
(removing outdated review req on v11-annotated)
I'll try (ugh) to get some time for at least the core patches this week, but
please don't skip over another reviewer to save them for me!
Comment on attachment 183236 [details] [diff] [review]
Phase 1: Allow SDK-less builds on 10.4
OK. Pointing it at seawood for his autoconf/build familiarity and bryner for
Mac familiarity. shaver and everyone else, your two centses will still be
accepted if you find the time.
Comment on attachment 183240 [details] [diff] [review]
Phase 5: Camino fixes
r=pink
Why the f**k this bug is marked as fixed ? It isn't because patches are not added to trunk !
I'm so sorry.
I just want to add a "CC:".
Wrong click, sorry for that.
Comment on attachment 183238 [details] [diff] [review]
Phase 3: Correct behavior for all non-core parts of the build system
Do we actually have to migrate the PrintPDE and Default Plugin projects to
xcode 2 to make them build? It would be great if we could leave them in the
old format for now.
bryner: The updated PrintPDE and DefaultPlugin projects work in Xcode 1 (10.3).
The update is necessary to make them build against an SDK. Old-style jam
(legacy) targets don't know or care about SDKROOT. New-style "native" targets
do, but they require Xcode. This makes the minimum build requirement for
Mozilla 10.3 and Xcode. I have used this patch to build on 10.3/Xcode 1.1.
Note that Camino already requires 10.3 to build. Mozilla now requires 10.2 at
minimum, and while I don't want to break that just for the sake of breaking it,
I question whether anyone actually needs to build on 10.2 any more.
It would be possible, as I mentioned earlier, to distribute both an .xcode
project and a .pbproj project alongside one other. We could select which to use
based on whether we're using xcodebuild/pbproj (Xcode) or pbxproj (Project
Builder). This would maintain buildability on 10.2. I initially wanted to do
this (comment 65) but had a change of heart. The machinery wouldn't be a
problem, but maintaining two separate projects could become tedious. Also,
testing the machinery would necessarily require a 10.2 machine. Anyone got?
Comment on attachment 183236 [details] [diff] [review]
Phase 1: Allow SDK-less builds on 10.4
Can you split the MoreFiles changes into a separate patch for darin &
pinkerton/simon to review? I'm not sure why we would just rename those
functions instead of just removing them completely since it doesn't look like
any of the callers were renamed.
Looking at the collection of patches, there's no AC_SUBST for SDP so the value
never gets substituted in autoconf.mk.
Comment on attachment 183237 [details] [diff] [review]
Phase 2: Allow SDK-ful builds on 10.4
For the Makefile changes, you should use $(shell) rather than the backticks.
Since you are rearranging that section anyway, can you just move the option
checks for --with-macos-sdk & --with-java-include down to the 'External
Packages' section? They do not need to be up there with the compiler tools
checks.
Created attachment 183648 [details] [diff] [review]
Phase 1a: SDK-less builds on 10.4, config/build portion
Splitting phase 1 into a configure/build half and a Mac-specific implementation
half per comment 96.
Chris, I do AC_PATH_PROG for SDP, and AC_PATH_PROG calls AC_SUBST. This is the
documented behavior for AC_PATH_PROG. I'll add a redundant AC_SUBST if you
insist, but I don't see why it should be necessary.
Created attachment 183649 [details] [diff] [review]
Phase 1b: SDK-less builds on 10.4, Mac-specific implementation portion
Re comment 96: removing those functions in MoreFilesX is an option, since there
are no calls to them in Mozilla. I renamed because those files were untouched
from the copies Apple supplies, and renaming with a comment seemed like a less
obtrusive and easier to follow change in the event that Apple ever updates and
we sync.
Comment on attachment 183238 [details] [diff] [review]
Phase 3: Correct behavior for all non-core parts of the build system
r=cls iff wtc also approves of the NSPR & NSS changes.
Comment on attachment 183648 [details] [diff] [review]
Phase 1a: SDK-less builds on 10.4, config/build portion
(In reply to comment #98)
> Chris, I do AC_PATH_PROG for SDP, and AC_PATH_PROG calls AC_SUBST. This is the
> documented behavior for AC_PATH_PROG. I'll add a redundant AC_SUBST if you
> insist, but I don't see why it should be necessary.
Looking at the docs, you're correct. I must've forgotten to run autoconf after
applying the patch. Sorry about that.
Created attachment 183652 [details] [diff] [review]
Phase 2, v2: Allow SDK-ful builds on 10.4
(In reply to comment #97)
> For the Makefile changes, you should use $(shell) rather than the backticks.
Done.
> Since you are rearranging that section anyway, can you just move the option
> checks for --with-macos-sdk & --with-java-include down to the 'External
> Packages' section? They do not need to be up there with the compiler tools
> checks.
I moved --with-java-include down, but --with-macos-sdk needs to run very early.
The changes it makes to CPP, CFLAGS, and friends are critical to the build
process. I did a small reorg to put the OS X toolchain stuff back where I
found it and moved --with-macos-sdk just below that. It can probably move a
little bit more down, but it really needs to remain above any AC_TRY or
anything else that does cpp, cc, ld, etc. So at the very least, it needs to
stay in the same section.
This patch may change the context for subsequent patches such that they won't
apply. Also, recent changes on the trunk may prevent subsequent patches from
applying cleanly. If any reviewer wants something more up-to-date, just ask.
I plan on at least cutting a new (unified or split into phases?) patch once the
reviews are in.? Does the stable branch usually take core build config
changes to build on newer hosts?
Comment on attachment 183649 [details] [diff] [review]
Phase 1b: SDK-less builds on 10.4, Mac-specific implementation portion
r=pink
Comment on attachment 183648 [details] [diff] [review]
Phase 1a: SDK-less builds on 10.4, config/build portion
This patch doesn't apply for me, because it apparently diffs between *.dist and
*.ph1, neither of which exist in my source tree. I guess I'll whack it with
some sed, but I wonder if I'm doing something wrong.
Comment on attachment 183649 [details] [diff] [review]
Phase 1b: SDK-less builds on 10.4, Mac-specific implementation portion
sr=shaver.
You're not doing anything wrong. I shoulda whacked it with sed, especially
after comment 86, but I forgot. Just drop the .dist/.phX suffixes.
Comment on attachment 183238 [details] [diff] [review]
Phase 3: Correct behavior for all non-core parts of the build system
cls: the NSPR change looks OK. I didn't review it carefully though.
Could you implement the NSS change inside mozilla/security/coreconf
as opposed to in mozilla/security/manager/Makefile.in? This way
standalone NSS builds will also work.
(In reply to comment #102)
>?
Yes, it is more likely that only the critical fixes be taken.
> Does the stable branch usually take core build config
> changes to build on newer hosts?
This has happened in certain cases but I wouldn't say that those cases are
usual. Usually only security fixes and patches for regressions from previous
security fixes are committed on the branches.
(In reply to comment #107)
> Could you implement the NSS change inside mozilla/security/coreconf
> as opposed to in mozilla/security/manager/Makefile.in? This way
> standalone NSS builds will also work.
wtc: That's not so simple. MACOS_SDK_FLAGS is filled with the results of a
bunch of scripted logic. I can export that variable and pick it up in
security/coreconf/Darwin.mk, but the variable itself will still need to be set
up by a top-level configure, so it's not that useful for a standalone NSS build.
The only way to make it work standalone would be to pick up NEXT_ROOT in
security/coreconf and use it to rebuild MACOS_SDK_FLAGS - a reimplementation of
the top-level configure logic, like I've done in NSPR's configure. I guess
that's OK, if you don't mind having a script in security/coreconf to build the
flags. A quick perl job could handle it. I'd do that if you wanted it, but I
think it should be in another bug, or at least a separate part of this bug.
Comment on attachment 183238 [details] [diff] [review]
Phase 3: Correct behavior for all non-core parts of the build system
Do we really need to fork the project files at this point? Can't the new
version of xcodebuild deal with old-format project files?
bryner: if we leave the pbproj files alone, xcodebuild won't listen when we
specify SDKROOT, and we wind up building without the SDK. It's an invitation
for trouble. The whole rest of the build uses the SDK.
I just want to make clear that the newer pbprojs still work with Xcode 1.x on 10.3.
Comment on attachment 183652 [details] [diff] [review]
Phase 2, v2: Allow SDK-ful builds on 10.4
>+ dnl If gcc >= 4, use powerpc-apple-darwin#, where # is the version of
>+ dnl the Darwin release corresponding to the target Mac OS X release.
>+ dnl For OS X >= 10.1.1, take the minor version number and add 4 to get
>+ dnl the Darwin major version number. If it can't be determined, use the
>+ dnl current Darwin major version number and hope that there's a symlink.
>+ TARGET_ARCH_LIB=powerpc-apple-darwin`echo $MACOS_SDK_DIR | $PERL -pe 's/MacOSX10\.([^\.]*)//;if ($1) {$_=$1+4;} else {$_="'$TARGET_OS'";s/(\d+)//;$_=$1;}'`
Why don't you use the existing MACOS_VERSION_MINOR variable
to compute the Darwin major version number?
(In reply to comment #112)
> Why don't you use the existing MACOS_VERSION_MINOR variable
> to compute the Darwin major version number?
MACOS_VERSION_MINOR tells us which deployment target has been selected by
--enable-macos-target, and defaults to 1 (as in 10.1). This is not the same
thing as which version the selected SDK is associated with (set by
--with-macos-sdk in top-level, and NEXT_ROOT in nsprpub) or the version of the
system running on the build host (TARGET_OS, used only for fallback when the
version can't be figured based on what's in NEXT_ROOT).
Comment on attachment 183238 [details] [diff] [review]
Phase 3: Correct behavior for all non-core parts of the build system
Mark,
Yes, I'd like you to reimplement that logic in mozilla/security/coreconf.
Here is some makefile code I put together. Since I don't have a Mac, I
can only test it on Linux to the best I can.
ifndef GCC_VERSION)
endif
ifndef DARWIN_TARGET_MAJOR
DARWIN_TARGET_MAJOR := $(shell echo $(NEXT_ROOT) | sed -e
's/^.*MacOSX10\.//' | awk -F. '{ print $$1 }')
ifeq (,$(DARWIN_TARGET_MAJOR))
DARWIN_TARGET_MAJOR := $(shell echo $(OS_RELEASE) | awk -F. '{ print
$$1 }')
else
DARWIN_TARGET_MAJOR := $(shell expr $(DARWIN_TARGET_MAJOR) + 4)
endif
endif
ifeq (,$(filter-out 2 3,$(GCC_VERSION_MAJOR)))
# GCC <= 3
else
# GCC >= 4
endif
Comment on attachment 183238 [details] [diff] [review]
Phase 3: Correct behavior for all non-core parts of the build system
I'd like to suggest some changes to the nsprpub portion
of this patch.
Replace the comment "top-level configure.in" by
"Mozilla's top-level configure.in" or "mozilla/configure.in".
Since NSPR only uses the C compiler, it is better to define
GCC_VERSION_FULL, GCC_VERSION, and GCC_VERSION_MAJOR using
$(CC) -v instead of $(CXX) -v.
It would be nice if you could copy from mozilla/configure.in
the comments that explain what those Perl scripts do.
NSPR has no makefile rules that use CPP or CXXCPP, so they
don't need to be defined.
TARGET_OS is not defined in mozilla/nsprpub/configure.in, so
you need to replace $TARGET_OS with ${target_os}.
Created attachment 183868 [details] [diff] [review]
Phase 3, v2: implement wtc's suggestions
(In reply to comment #114)
(NSS) Good call. This is much better.
(In reply to comment #115)
(NSPR) OK. The only thing I didn't implement is this:
> NSPR has no makefile rules that use CPP or CXXCPP, so they don't need to be
> defined.
CPP needs to be defined because AC_CHECK_HEADER uses it. I've added a comment
to clarify why I do this, in both nsprpub/configure.in and the top-level
configure.in.
Created attachment 183870 [details] [diff] [review]
Phase 2, v3: changes inspired by wtc's review of ph3.
Comment on attachment 183156 [details] [diff] [review]
v11
v11 is now obsolete, I'll cut a new unified patch once they're all stable.
Comment on attachment 183868 [details] [diff] [review]
Phase 3, v2: implement wtc's suggestions
I only reviewed the nsprpub and security/coreconf changes..
In mozilla/security/coreconf/Darwin.mk, you can use
ifneq instead of ifeq-else. I don't think you need to
define LDOPTS. You have a comment about including
-F$(NEXT_ROOT)/Library/Frameworks if it exists. If
Mac allows passing a nonexistent directory to -F, we
can just add that blindly. Otherwise, we'd need to
make a $(shell ) function call to test the existence of
that directory.
(In reply to comment #119)
>.
Yup. Not only that, but for C++, ac_cpp is $CXXCPP $CPPFLAGS. There's no
separate $CXXCPPFLAGS. It doesn't matter for NSPR, but it's imperative where
plusplus is concerned.
> In mozilla/security/coreconf/Darwin.mk, you can use
> ifneq instead of ifeq-else.
Noted and updated, thanks.
> I don't think you need to define LDOPTS.
Not for the Mozilla build, but aren't there things linked into executables
during a standalone build?
> You have a comment about including
> -F$(NEXT_ROOT)/Library/Frameworks if it exists.
I knew I forgot something!
> If
> Mac allows passing a nonexistent directory to -F, we
> can just add that blindly. Otherwise, we'd need to
> make a $(shell ) function call to test the existence of
> that directory.
The compiler spits warnings for missing -F directories (like -L), so I wanted to
make it conditional. Added this after setting DARWIN_SDK_LDFLAGS:
ifneq (,$(shell find $(NEXT_ROOT)/Library/Frameworks -maxdepth 0))
DARWIN_SDK_CFLAGS += -F$(NEXT_ROOT)/Library/Frameworks
endif
The only changes in ph3v2 were to NSPR and NSS, so with r=cls on v1 for
everything else save that, and r=wtc on v2 for that save everything else, it
should be good to go.
I'll have limited availability from the 19th to the 25th, it'd be nice to wrap
up by tomorrow. The only remaining issue as I see it is how to handle (or not)
building on 10.2.
Mark,
You may know the NSS build system better than I do now :-)
I found that $(LDOPTS) is in two NSS command-line utilities'
makefiles, but I am not sure if it is really being used.
Here is the makefile rule we use to build executables in NSS:
Now that I have looked at our makefiles more closely, I think
you should replace LDOPTS by OS_LIBS, although it is strange to
see a bunch of -L's without any -l. (We only link with libSystem.dylib
implicitly.) Will those -L's apply to libSystem.dylib if we
don't have -lSystem explicitly on the command line?
Mark, you can also try setting LDFLAGS (instead of LDOPTS)
in mozilla/security/coreconf/Darwin.mk. I don't know whether
OS_LIBS or LDFLAGS is more appropriate, but I believe either will
work.
I've determined that the two NSS makefiles in which I found
$(LDOPTS) are dead files, so definitely do not set LDOPTS.
I changed LDOPTS to LDFLAGS and still set it with +=. It seems that the other
mk fragments in coreconf are more likely to set OS_LIBS, but LDFLAGS and OS_LIBS
aren't used independently. I'm more comfortable calling -L a "flag" than a library.
With proper coaxing via -L, ld will use the libSystem we want. Actually, when
NEXT_ROOT is set, it should look where that points and not at /usr/lib at all.
The -L flags are more to point ld at the compiler-specific lib dirs in the SDK,
since the compiler doesn't know about NEXT_ROOT or have any other one-stop way
to ask for an SDK. This whole bug would be so much easier if it did.
I'm trying to build 1.7.7 from the source tarball on MacOS X 10.4 Tiger. I'm
using the stock GCC that came with the Xcode 2 on my machine. I know this may
not be supported, but until the build instructions are updated, I thought I'd
post here.
I renamed the FSLock and FSUnlock methods but now the build fails here:
sCollationMacUC.cpp: In member function `virtual nsresult
nsCollationMacUC::CompareString(PRInt32, const nsAString&, const nsAString&,
PRInt32*)':
nsCollationMacUC.cpp:223: error: invalid conversion from 'PRInt32*' to 'SInt32*'
nsCollationMacUC.cpp:223: error: initializing argument 7 of 'OSStatus
UCCompareText(OpaqueCollatorRef*, const UniChar*, UniCharCount, const UniChar*,
UniCharCount, Boolean*, SInt32*)'
nsCollationMacUC.cpp: In member function `virtual nsresult
nsCollationMacUC::CompareRawSortKey(const PRUint8*, PRUint32, const PRUint8*,
PRUint32, PRInt32*)':
nsCollationMacUC.cpp:244: error: invalid conversion from 'PRInt32*' to 'SInt32*'
nsCollationMacUC.cpp:244: error: initializing argument 6 of 'OSStatus
UCCompareCollationKeys(const UCCollationValue*, ItemCount, const
UCCollationValue*, ItemCount, Boolean*, SInt32*)'
regarding comment #124; You are using gcc 4.0, use gcc_select to switch to gcc
3.3. Doing that will eliminate those compiler errors you are having.
Please use "cvs diff -u" to create patches. "u" is a standard option, and the
file names in your patches don't match up with what gets checked out....
(In reply to comment #127)
>.
One item I've noted is the phase 4.1 patch does not apply cleanly. Here's the
terminal capture of applying the patch to yesterday's mozilla source archive:
pcp04368799pcs:~ dales$ patch -p0 < dales292530.ph4.1.patch
patching file mozilla/config/autoconf.mk.in
Hunk #2 FAILED at 517.
1 out of 2 hunks FAILED -- saving rejects to file mozilla/config/autoconf.mk.in.rej
patching file mozilla/config/config.mk
patching file mozilla/configure.in
Hunk #1 FAILED at 458.
Hunk #2 succeeded at 2433 (offset -14 lines).
Hunk #3 succeeded at 2454 (offset -14 lines).
Hunk #4 succeeded at 5781 (offset -3 lines).
1 out of 4 hunks FAILED -- saving rejects to file mozilla/configure.in.rej
pcp04368799pcs:~ dales$
All other phases apply cleanly now ... though I had to edit some names with
*.dist or *.ph# stuctures to get it to happen. No tests of phase 5 were done,
since I'm not doing Camino builds.
Environment is Panther ... 10.3.9 and gcc 3.3.
Dale
patch can't resolve some conflicts due to recent checkins. Stand by, it'll be
up to date by Thursday at the latest.
Created attachment 184647 [details] [diff] [review]
v12: up to date, consolidated
I'm back, this time with a suntan.
This patch is the consolidation of all six phase patches that have r+/sr+,
including the changes discussed with wtc, brought up to date relative to
current cvs. No phases, no diff silliness, applies cleanly against a virgin
tree.
There's no way this should hold up 1.1a1/1.8b2, so we'll hold off on getting
this checked in until those are out and the tree is unfrozen.
Notes for checkin: the following files and directories are removed:
embedding/components/printingui/src/mac/printpde/PrintPDE.pbproj/
embedding/components/printingui/src/mac/printpde/PrintPDE.pbproj/project.pbxproj
modules/plugin/samples/default/mac/DefaultPlugin.pbproj/
modules/plugin/samples/default/mac/DefaultPlugin.pbproj/project.pbxproj
The following files and directories are added:
embedding/components/printingui/src/mac/printpde/Info-PrintPDE.plist
embedding/components/printingui/src/mac/printpde/PrintPDE.xcode/
embedding/components/printingui/src/mac/printpde/PrintPDE.xcode/project.pbxproj
modules/plugin/samples/default/mac/Info-DefaultPlugin.plist
modules/plugin/samples/default/mac/DefaultPlugin.xcode/
modules/plugin/samples/default/mac/DefaultPlugin.xcode/project.pbxproj
Thanks! The tree may open as soon as tomorrow and we should get this in ASAP. I
will do the commit (after some testing) unless somebody else wants to.
Thanks for the one-for-all patch. I will test it on both firefox and thunderbird
asap.
Using Mac OS X 10.4.1 on a G5, with gcc 3.3 selected and fresh checkouts...
When building Firefox with your patch, I get this:
NEXT_ROOT= /usr/bin/xcodebuild -project DefaultPlugin.xcode -target "Default
Plugin" -buildstyle Deployment GCC_VERSION="@GCC_VERSION@"
MACOSX_DEPLOYMENT_TARGET="@MACOSX_DEPLOYMENT_TARGET@" OTHER_CFLAGS="-DNDEBUG
-DTRIMMED"
=== BUILDING NATIVE TARGET Default Plugin USING BUILD STYLE Deployment ===
undefined compiler specification com.apple.compilers.gcc.@GCC_VERSION@;
specification may be missing or target may be misconfigured
undefined compiler specification com.apple.compilers.gcc.@GCC_VERSION@;
specification may be missing or target may be misconfigured
** BUILD FAILED **
make[4]: *** [build-plugin] Error 1
make[3]: *** [libs] Error 2
make[2]: *** [tier_9] Error 2
make[1]: *** [default] Error 2
make: *** [build] Error 2
When building Camino with your patch I get this:
In file included from asdecode.cpp:40:
/usr/include/gcc/darwin/3.3/c++/cstdio:156: error: `vfscanf' not declared
/usr/include/gcc/darwin/3.3/c++/cstdio:165: error: `vfscanf' not declared
In file included from
asdecode.cpp: In function `int main(int, char**)':
asdecode.cpp:114: warning: comparison between signed and unsigned integer
expressions
make[2]: *** [asdecode.o] Error 1
make[1]: *** [default] Error 2
make: *** [build] Error 2
hmm... are you requiring the 10.3.9 sdk now?
Well, SDK 10.3.9 seems to be required now. I built both firefox and thunderbird
using SDK 10.3.9 (I removed SDK 10.2.8 a few weeks ago).
My builds are fully working and based on :
- G4 1.42 Ghz / 512 Mb
- Tiger 10.4.1
- SDK 10.3.9
- gcc 3.3
Great work ;p
the 10.2.8 SDK is required for building release builds. We must not enforce any
requirement for a 10.3.X SDK.
Josh, run autoconf both in top-level and nsprpub and try again. The
un-AC_SUBSTed @VAR@s in your Firefox build output are a dead giveaway. The
Camino build output also indicates that you haven't run autoconf, although the
errors there are way more subtle. You need autoconf 2.13 (not later) to test
the patch, the version supplied with the system in /usr/bin is too new and won't
work. This is a Mozilla requirement, not one introduced by the patch. At
commit time, you don't need to check in the regenerated configure scripts, they
will be automatically regenerated from the checked-in configure.ins.
I'm not requiring the 10.3.9 SDK, but without running autoconf, builds might
make more progress before failing if you're targeting 10.3.9. Like pink said,
it's very important that we stick to 10.2.8 for the foreseeable future at the
very least.
I've been building against the 10.2.8 SDK all along (build host 10.4.1/Xcode 2)
as well as the 10.2.7 SDK (build host 10.3.9/Xcode 1.1) to make sure that
nothing breaks.
Created attachment 184775 [details] [diff] [review]
Backport of critical parts to aviary 1.0.x branch
I backported ph1a, ph1b, and ph2 to aviary_1.0.x. These are only the critical
parts required to build under 10.4 while targeting an SDK. This doesn't
include anything that has even a remote chance of breaking anything. To use
it, run autoconf only in the top level, there aren't any nspr changes here.
I did test builds of Firefox with this patch on build host 10.4.1/Xcode 2.0/SDK
10.2.8 and build host 10.3.9/Xcode 1.1/SDK 10.2.7.
Mike, do you want anything like this for a stable Camino branch?
Created attachment 184898 [details] [diff] [review]
v13 (trunk) fixes a couple of Camino bugs introduced in v10
I just got a report of a couple of bugs in Camino building with the patch.
Attempts to open links in new tabs or windows wouldn't work, and location bar
autocomplete was behaving erratically. I traced the bug to missing
-fshort-wchar during the Camino build. -fshort-wchar is set in OTHER_CFLAGS in
Camino.xcode/project.pbxproj, but it was being overridden by OTHER_CFLAGS
passed to xcodebuild on the command line. This bug was introduced in v10 and
was present in ph4.
The only change in this patch is that OTHER_CFLAGS isn't passed to xcodebuild.
Diff-to-diff diff for config/config.mk:
-+ifdef MOZ_DEBUG
-+PBBUILD_SETTINGS += OTHER_CFLAGS="$(MOZ_DEBUG_ENABLE_DEFS)"
-+else # MOZ_DEBUG
-+PBBUILD_SETTINGS += OTHER_CFLAGS="$(MOZ_DEBUG_DISABLE_DEFS)"
-+endif # MOZ_DEBUG
Also, the line number offsets for Camino.xcode/project.pbxproj have changed.
Since xcodebuild is already told to use the Deployment or Development style
depending on MOZ_DEBUG, this shouldn't have any real impact.
Thanks to James for notifying me of the problem.
> Mike, do you want anything like this for a stable Camino branch?
hmmm. camino 0.8.x is checked out from MOZILLA_1_7_BRANCH. while i don't have
any plans to build that branch on tiger, or to release any further 0.8.x
releases, I guess in the future if i ever do, it might be far enough in the
future that all my machines are tiger.
if it's easy to backport, i'd say go ahead, but don't waste too much time with it...
Comment on attachment 184898 [details] [diff] [review]
v13 (trunk) fixes a couple of Camino bugs introduced in v10
Having trouble with Camino built on 10.3 due to the libmozz stuff being removed
from project.pbxproj. The app launches but doesn't open any windows and
crashes on any attempt to do anything useful. This isn't causing a problem for
10.4 build hosts.
Odd.
This may only affect non-static builds - I say that because I was testing
static builds more heavily before, and I didn't notice this until now.
Investigating alternatives - if the tree reopens before I've whacked this, the
patch can land without the Camino.xcode/project.pbxproj modifications so that
we can at least get the core stuff out there, and finish work on Camino
separately.
Got the following with the v13 patch applied when building on 10.4:
StandardURL.pp /cvsroot/mozilla/netwerk/base/src/nsStandardURL.cpp
/cvsroot/mozilla/netwerk/base/src/nsStandardURL.cpp: In member function
`nsresult nsStandardURL::BuildNormalizedSpec(const char*)':
../../../dist/include/string/nsTSubstring.h:502: error:
'nsCSubstring::nsCSubstring(const nsCSubstring&)' is protected
/cvsroot/mozilla/netwerk/base/src/nsStandardURL.cpp:497: error: within this context
../../../dist/include/string/nsTSubstring.h:502: error:
'nsCSubstring::nsCSubstring(const nsCSubstring&)' is protected
/cvsroot/mozilla/netwerk/base/src/nsStandardURL.cpp:497: error: within this context
make[5]: *** [nsStandardURL.o] Error 1
make[4]: *** [libs] Error 2
make[3]: *** [libs] Error 2
make[2]: *** [tier_9] Error 2
make[1]: *** [default] Error 2
make: *** [build] Error 2
Comment on attachment 184898 [details] [diff] [review]
v13 (trunk) fixes a couple of Camino bugs introduced in v10
a=me, for 1.8b3.
/be
I am building Firefox now one more time with v13. If it builds and runs, I will check the patch in.
- I will not check in camino-specific code (mozilla/camino/)
- we may need to continue to build on 10.2, pending a discussion with chase and dbaron about
tinderboxes. If my checkin breaks 10.2 building, the SeaMonkey tboxes will be horked. We should fix it
ASAP but the risk is not enough to hold up the checkin according to chase.
- please continue discussing any build issues with this patch on this bug so I can track them
Comment 142: Robert: You are using the gcc 4 that shipped with 10.4. It's known
to be broken. With the patch, a warning is printed at configure time about this
problem. "sudo gcc_select 3.3" and try again.
Comment 143: Brendan: Thanks!
Comment 144: Josh: A checkin of v13 will almost certainly break 10.2 builds. To
retain the ability to build on 10.2, we'll need to keep the pbproj dirs and
their contents around, so don't remove anything from cvs that comment 130 asks
you to remove.
Created attachment 184979 [details] [diff] [review]
Fix for probable Seamonkey tinderbox bustage
Apply this patch on top of v13 to hopefully restore buildability on 10.2. I
don't have any more 10.2 systems, so I'm not positive, but this should do it.
This doesn't restore 10.2 buildability for Camino. That ship sailed long ago.
This patch tests for the name of xcodebuild prior to doing a build for which
both pbbuild and xcode build files exist. If it's called pbxbuild, it's
assumed to be Project Builder, pre-Xcode, and it's directed to the pbproj. If
it's pbbuild, xcodebuild, or anything else, it's assumed to be Xcode, and it's
directed to the xcode project. Josh, drop me a private e-mail when you land
v13 with or without this - I'll be "on the hook" and watch the tinderboxen as
well.
Created attachment 184982 [details] [diff] [review]
nspr parts of patch v13 (with autoconf updates) - most people should ignore this (checked in)
Created attachment 184983 [details] [diff] [review]
Better fix for Camino (ph5)
Apply this patch INSTEAD of the patches to camino/ from v13. In other words,
this replaces the ph5 patch. Compatible with both 10.3 and 10.4 build hosts.
The zlib workaround I came up with in v6 resulted in some broken Camino builds
on 10.3 build hosts. Although the Camino mozconfig specified with-system-zlib,
the system zlib was not being used because it was too old, 1.1.3 on 10.3.9.
Mozilla requires 1.2.2, so libmozz would be built and used. 10.4 includes zlib
1.2.2, so any build on 10.4 WOULD use the system zlib and libmozz wouldn't be
built.
Even selecting the 10.2 SDK on 10.4, configure would still wind up detecting
and using zlib 1.2.2, because the test program calls the zlibVersion() function
for its check and it winds up with the build host's zlib runtime version,
1.2.2. If the test program might also checked the ZLIB_VERSION macro, brought
in from zlib.h, we wouldn't have this problem, but that's another bug for
another day (and one that will probably be forgotten).
This fully explains what pink saw in comment 20.
Dropping libmozz from Camino.xcode as I had done allowed builds on 10.4 at the
expense of 10.3.
I'm changing Camino's mozconfig to --without-system-zlib, since that's what the
effective setting was anyway, and because we don't want to be using zlib
runtimes older than 1.2.2 (pre-Tiger) even when the build host provides a newer
zlib.
Also restoring -lmozz where it had gotten dropped before in a premature checkin
(comment 72). It's not strictly necessary because ld would reach the library
through the dylibs that depend on it, and it's debatable that it even belongs
there because as far as I know, nothing in Camino uses zlib directly. It goes
back in because it was there before, it doesn't hurt anything, and it wouldn't
have gotten dropped but for the earlier solution in this bug.
Tested static build on 10.4 build host and non-static on 10.3, doing vice-versa
now.
Created attachment 185036 [details] [diff] [review]
up-to-date for configure.in
Now that the tree is open again, lots of other things landed this morning
before Josh had a chance to do the checkin. This is the patch to top-level
configure.in brought up to date.
Created attachment 185043 [details] [diff] [review]
security part of patch, most people should ignore this
Created attachment 185055 [details] [diff] [review]
Fix Seamonkey tinderbox (and other Panther users) build bustage
The proposal from last night wouldn't work because pbxbuild doesn't understand
-project. This is better.
Nelson --
Not sure about the history here, but Bob Relyea was asked to check in this patch:
to mozilla/security/coreconf. Apparently the mozilla tree is busted without it.
WTC was most likely involved in this discussion, but he currently is out of the
office.
Created attachment 185057 [details] [diff] [review]
Panther fix (again) - proper variable name
'securty part, which most people should ignore;)" checked into NSS tip
Checking in Darwin.mk;
/cvsroot/mozilla/security/coreconf/Darwin.mk,v <-- Darwin.mk
new revision: 1.10; previous revision: 1.9
done
I'll move the client tag only on this file to get Mozilla building again. NOTE:
before a mozilla product release, the client tag will have to be moved to an
official release of NSS, (currently the next release is slated to be 3.11).
bob
Client Tag has been updated.
makaila.sfbay.redhat.com(426) cvs log Darwin.mk | grep CLIENT
{static dated CLIENT_TAGS removed. }
NSS_CLIENT_TAG: 1.9
makaila.sfbay.redhat.com(428) cvs tag -F NSS_CLIENT_TAG Darwin.mk
T Darwin.mk
makaila.sfbay.redhat.com(429) cvs log Darwin.mk | grep CLIENT
{static dated CLIENT_TAGS removed. }
NSS_CLIENT_TAG: 1.10
Created attachment 185061 [details] [diff] [review]
Panther fix (yet again) - out-of-order includes
(In reply to comment #154)
> I'll move the client tag only on this file to get Mozilla building again. NOTE:
> before a mozilla product release, the client tag will have to be moved to an
> official release of NSS, (currently the next release is slated to be 3.11).
You didn't have to do that - the patch to security/coreconf/Darwin.mk was not
critical for building. Feel free to adjust tags if necessary.
All done here. Thanks to everyone who helped with testing.
*** Bug 292266 has been marked as a duplicate of this bug. ***
Note that if anyone decides to take the aviary 1.0.x patch, attachment 184775 [details] [diff] [review],
it will need to be augmented à la bug 296900 to work with Xcode 2.1.
> Note that if anyone decides to take the aviary 1.0.x patch, attachment 184775 [details] [diff] [review] [edit],
> it will need to be augmented à la bug 296900 to work with Xcode 2.1.
I just tried to compile Mozilla 1.7.5 with crypto and with the aviary 1.0.x patch, attachment 184775 [details] [diff] [review] on
10.4 and with XCode 2.0 and here is what I got:
ld: Undefined symbols:
__Z21mime_crypto_stamped_pP10MimeObject
__Z21mime_set_crypto_stampP10MimeObjectii
make[5]: *** [libmime.dylib] Error 1
make[4]: *** [libs] Error 2
make[3]: *** [libs] Error 2
make[2]: *** [tier_97] Error 2
make[1]: *** [default] Error 2
make: *** [build] Error 2
Any advice?
Created attachment 185940 [details] [diff] [review]
Backport of critical parts to Aviary 1.0.x/Mozilla 1.7 branch
(In reply to comment #161)
Couldn't reproduce. Be sure you're using gcc 3.3 and targeting a proper SDK.
If possible, be sure that the identical configuration doesn't result in the
same error on 10.3.
(In reply to comment #160)
This contains the necessary portions of bug 296900 to allow building under
Xcode 2.1. Patch prepared against Mozilla 1.7 this time, also applies on
Aviary 1.0.x.
These patches are working great for me. However, I am now having a related issue
with the CVS checkout. I have to remove the following two files each time before
I do a build (suite). I've even tried deleting the CVS directory to no avail.
cvs checkout: move away
mozilla/embedding/components/printingui/src/mac/printpde/PrintPDE.xcode/project.pbxproj;
it is in the way
C
mozilla/embedding/components/printingui/src/mac/printpde/PrintPDE.xcode/project.pbxproj
M mozilla/modules/plugin/samples/default/mac/DefaultPlugin.pbproj/project.pbxproj
cvs checkout: move away
mozilla/modules/plugin/samples/default/mac/DefaultPlugin.xcode/project.pbxproj;
it is in the way
C mozilla/modules/plugin/samples/default/mac/DefaultPlugin.xcode/project.pbxproj
Anyone who had tested the patch will get that on cvs checkout now that the patch
landed. Remove the source directories for printpde and defaultplugin and try
checking out again.
rm -rf /path/to/mozilla/embedding/components/printingui/src/mac/printpde
/path/to/mozilla/modules/plugin/samples/default/mac
If that doesn't work, try pulling a completely clean source directory, and if
you still have trouble, open a new bug.
(In reply to comment #162)
> (In reply to comment #161)
> Couldn't reproduce. Be sure you're using gcc 3.3 and targeting a proper SDK.
> If possible, be sure that the identical configuration doesn't result in the
> same error on 10.3.
Yes I have tried to target SDK 10.2.8 and SDK 10.3.0 same error...
I have no problem building 1.7.5 + crypto on 10.3
How can I compile a release version of Mozilla with crypto on Tiger? (I have no problem building 1.7.5 no
crypto)
I'm sorry if this is a total newbie / OT question here, but which patch am I supposed to apply now to build
Firefox 1.0.6 on Mac OS X 10.4? The incredible number of patches here is a bit bewildering...
You don't need a patch - you need 2 things...
1) use "sudo gcc_select 3.3" to select gcc 3.3 instead of 4. You can't build the
1.0.6 branch with gcc 4 AFAIK.
2) build against the Mac OS X 10.2.8 SDK (add a line to your .mozconfig file)
never mind - you can't build the branch on 10.4 without some patches that don't
exist. sorry.
(In reply to comment #168)
> never mind - you can't build the branch on 10.4 without some patches that don't
> exist. sorry.
Is this a new development specific to building 1.0.6? I built 1.0.5 on Mac OS X 10.4 after applying this
patch, running autoconf 2.1.3, and using gcc 3.3 with no problems.
You want attachment 185940 [details] [diff] [review] to this bug for the 1.0.x/1.7 branch. You need to
run autoconf (must be autoconf 2.13) and you're limited to using gcc 3.3 with
SDK 10.2.8. If it doesn't work, open a new bug or follow another support
channel. Let's try to keep the bugspam down here, 'k?
Comment on attachment 185940 [details] [diff] [review]
Backport of critical parts to Aviary 1.0.x/Mozilla 1.7 branch
1.0.5 and 1.7.9 have already shipped; unsetting approval requests. | https://bugzilla.mozilla.org/show_bug.cgi?id=292530 | CC-MAIN-2016-22 | refinedweb | 14,859 | 59.19 |
Suppose we have an array nums and a value k, we have to check whether the elements in nums can be made 0 by performing the following operation exactly k number of times or not.
So, if the input is like nums [2, 2, 3, 5] k = 3, then the output will be True because at first delete 2 from array, so the array will be [0, 0, 1, 3], then remove 1 to get [0, 0, 0, 2], then again delete 2 to get [0, 0, 0, 0].
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def solve(nums, k): distinct = set(nums) if len(distinct) == k: return True return False nums = [2, 2, 3, 4] k = 3 print(solve(nums, k))
[2, 2, 3, 4], 3
True | https://www.tutorialspoint.com/check-if-the-given-array-can-be-reduced-to-zeros-with-the-given-operation-performed-given-number-of-times-in-python | CC-MAIN-2021-25 | refinedweb | 139 | 51.48 |
One.
Both these tools can do more complicated stuff than that described in this article, but my aim is to motivate people who may not have tried them out to give them a go and see how much work they can save you for even simple tasks.
I've assumed that you know the basics of designing a database--why
you have several tables and
JOIN them rather than putting everything in the same table. I've also assumed that you're not allergic to reading documentation, so I'm going to spend more space on
saying why I use particular features of the modules rather
than explaining exactly how they work.
Synergy
The reason that
Class::DBI and the
Template Toolkit work so well together is simple.
Template Toolkit templates can call methods on objects
passed to them--so there's no need to explicitly pull every column
out of the database before you process the template--and
Class::DBI saves you the bother of writing methods to
retrieve database columns. You're essentially going straight from the
database to HTML with only a very small amount of Perl in the middle.
Suppose you're writing a web application to store details of books and their authors, and reviews of the books by users of the site. You'd like to have a page that displays all the books in your database and, for each book, offers links to all the reviews already written. With suitably set-up classes you can write a couple of lines of Perl:
#!/usr/bin/perl -w use strict; use Bookworms::Book; use Bookworms::Template; my @books = Bookworms::Book->retrieve_all; @books = sort { $a->title cmp $b->title } @books; print Bookworms::Template->output( template => "book_list.tt", vars => { books => \@books } );
hand your designer a simple template to pretty up:
[%Read review by [% review.reviewer.name %]</a>) [% END %] </li> [% END %] </ul> [% INCLUDE footer.tt %]
and your task is done. You don't have to explicitly select the reviews; you don't have to then cross-reference to another table to find out the reviewer's name; you don't have to mess with HERE-documents or fill your program with print statements. You hardly have to do anything.
Except of course, write the
Bookworm::* classes in the
first place, but that's easy.
Simple, Small Classes
For convenience, we write a class containing all the SQL needed to set up our database schema. This is very useful for running tests as well as for deploying a new install of the application.
This class has a single method that sets up a database conforming to the schema above. Here's the rendered POD for it; the implementation is pretty simple. The "force_clear" option is very useful for testing.This class has a single method that sets up a database conforming to the schema above. Here's the rendered POD for it; the implementation is pretty simple. The "force_clear" option is very useful for testing.
package Bookworm::Setup; use strict; use DBI; # Hash for table creation SQL - keys are the names of the tables, # values are SQL statements to create the corresponding tables. my %sql = ( author => qq { CREATE TABLE author ( uid int(10) unsigned NOT NULL auto_increment, name varchar(200), PRIMARY KEY (uid) ) }, book => qq{ CREATE TABLE book ( uid int(10) unsigned NOT NULL auto_increment, title varchar(200), first_name varchar(200), author int(10) unsigned, # references author.uid PRIMARY KEY (uid) ) }, review => qq{ CREATE TABLE review ( uid int(10) unsigned NOT NULL auto_increment, book int(10) unsigned, # references book.uid reviewer int(10) unsigned, # references reviewer.uid PRIMARY KEY (uid) ) }, reviewer => qq{ CREATE TABLE review ( uid int(10) unsigned NOT NULL auto_increment, name varchar(200), PRIMARY KEY (uid) ) } );
setup_db( dbname => 'bookworms', dbuser => 'username', dbpass => 'password', force_clear => 0 # optional, defaults to 0 ); Sets up the tables. Unless "force_clear" is supplied and set to a true value, any existing tables with the same names as we want to create will be left alone, whether or not they have the right columns etc. If "force_clear" is true, then any tables that are "in the way" will be removed. _Note that this option will nuke all your existing data._ The database user "dbuser" must be able to create and drop tables in the database "dbname". Croaks on error, returns true if all OK.
Now, another class to wrap around the
Template Toolkit;
we want to grab global variables like the name of the site, and so on,
from a config class. (There are plenty of config modules on CPAN;
you're bound to find one you like. I quite like
Config::Tiny; other people swear by
AppConfig--and since the latter is a prerequisite of the
Template Toolkit, you'll have it installed already.)
Bookworms::Config is just a little wrapper class around
Config::Tiny, so if I change to a different config method
later I don't have to rewrite lots of code.
package Bookworms::Template; use strict; use Bookworms::Config; use CGI; use Template; # We have one method, which returns everything you need to send to # STDOUT, including the Content-Type: header. sub output { my ($class, %args) = @_; my $config = Bookworms::Config->new; my $template_path = $config->get_var( "template_path" ); my $tt = Template->new( { INCLUDE_PATH => $template_path } ); my $tt_vars = $args{vars} || {}; $tt_vars->{site_name} = $config->get_var( "site_name" ); my $header = CGI::header; my $output; $tt->process( $args{template}, $tt_vars, \$output) or croak $tt->error; return $header . $output; }
Now we can start writing the classes to manage our database tables. Here's the class to handle book objects:
package Bookworms::Book; use base 'Bookworms::DBI'; use strict; __PACKAGE__->set_up_table( "book" ); __PACKAGE__->has_a( author => "Bookworms::Author" ); __PACKAGE__->has_many( "reviews", "Bookworms::Review" => "book" ); 1;
Yes, that's all you need. This simple class, by its ultimate
inheritance from
Class::DBI, has auto-created
constructors and accessors for every aspect of a book as defined in
our database schema. And moreover, because we've told it (using
has_a) that the
author column in the
book table is actually a foreign key for the primary key
of the table modeled by
Bookworms::Author, when we use
the
->author accessor we actually get a
Bookworms::Author object, which we can then call methods
on:
my $hobbit = Bookworms::Book->search( title => "The Hobbit" ); print "The Hobbit was written by " . $hobbit->author->name;
There are a couple of supporting classes that we need to write, but they're not complicated either.
First a base class, as with all
Class::DBI
applications, to set the database details:
package Bookworms::DBI; use base "Class::DBI::mysql"; __PACKAGE__->set_db( "Main", "dbi:mysql:bookworms", "username", "password" ); 1;
Our base class inherits from
Class::DBI::mysql instead
of plain
Class::DBI, so we can save ourselves the trouble
of directly specifying the table columns for each of our database
tables--the database-specific base classes will auto-create a
set_up_table method to handle all this for you.
At the time of writing, base classes for MySQL, PostgreSQL, Oracle,
and SQLite are available on CPAN. There's also
Class::DBI::BaseDSN, which allows you to specify the
database type at runtime.
We'll also want a class for each of the author, review, and reviewer
tables, but these are even simpler than the
Book class.
For example, the author class could be as trivial as:
package Bookworms::Author; use base 'Bookworms::DBI'; use strict; __PACKAGE__->set_up_table( "author" ); 1;
If we wanted to be able to access all the books by a given author, we could add the single line
__PACKAGE__->has_many( "books", "Bookworms::Book" => "author" );
and an accessor to return an array of
Bookworms::Book
objects would be automatically created, to be used like so:
my $author = Bookworms::Author->search( name => "J K Rowling" ); my @books = $author->books;
Or indeed:
<h1>[% author.name %]</h1> <ul> [% FOREACH book = author.books %] <li>[% book.title %]</li> [% END %] </ul>
Simple, small, almost trivial classes, taking a minute or two each to write.
What Does This Get Me?
The immediate benefits of all this are obvious:
- You don't have to mess about with HTML, since the very simplistic use of the
TemplateToolkit means that templates are comprehensible to competent web designers.
- You don't have to maintain classes full of copy-and-paste code, since the repetitive programming tasks like creating constructors and simple accessors are done for you.
A large hidden benefit is testing. Since the actual CGI scripts--which can be a pain to test--are so simple, you can concentrate most of your energy on testing the underlying modules.
It's probably worth writing a couple of simple tests to make sure that
you've set up your classes the way you intended to, particularly in
your first couple of forays into
Class::DBI.
use Test::More tests => 5; use strict; use_ok( "Bookworms::Author" ); use_ok( "Bookworms::Book" ); my $author = Bookworms::Author->create({ name => "Isaac Asimov" }); isa_ok( $author, "Bookworms::Author" ); my $book = Bookworms::Book->create({ title => "Foundation", author => $author }); isa_ok( $book, "Bookworms::Book" ); is( $book->author->name, "Isaac Asimov", "right author" );
However, the big testing win with this technique of separating out the heavy lifting from the CGI scripts into modules is when you'd like to add something more complicated. Say, for example, fuzzy matching. It's well known that people can't spell, and you'd like someone typing in "Isaac Assimov" to find the author they're looking for. So, let's process the author names as we create the author objects, and store some kind of canonicalized form in the database.
Class::DBI allows you to define "triggers"--methods that are called at given points during the lifetime of an
object. We'll want to use an
after_create trigger, which
is called after an object has been created and stored in the database.
We use this in preference to a
before_create trigger,
since we want to know the uid of the object, and this is only created
(via the auto_increment primary key) once the object has been written
to the database.
We use
Search::InvertedIndex to store the
canonicalized names, for quick access. We start with a very simple
canonicalization--stripping out vowels and collapsing repeated
letters. (I've found that this can pick up about half of name
misspellings found in the wild, which is pretty impressive.)
We'll write a couple of tests before we move on to code. Here are some that check that our class is doing what we told it to--removing vowels and collapsing repeated consonants.
use Test::More tests => 2; use strict; use Bookworms::Author; my $author = Bookworms::Author->create({ name => "Isaac Asimov" }); my @matches = Bookworms::Author->fuzzy_match( name => "asemov" ); is_deeply( \@matches, [ $author ], "fuzzy matching catches wrong vowels" ); @matches = Bookworms::Author->fuzzy_match( name => "assimov" ); is_deeply( \@matches, [ $author ], "fuzzy matching catches repeated letters" );
We should also write some other tests to run our algorithms over various misspellings that we've captured from actual users, to give an idea of whether "what we told our class to do" is the right thing.
Here's the first addition to the
Bookworms::Author
class, to store the indexed data:
use Search::InvertedIndex; my $database = Search::InvertedIndex::DB::Mysql->new( -db_name => "bookworms", -username => "username", -password => "password", -hostname => "", -table_name => "sii_author", -lock_mode => "EX" ) or die "Couldn't set up db"; my $map = Search::InvertedIndex->new( -database => $database ) or die "Couldn't set up map"; $map->add_group( -group => "author_name" ); __PACKAGE__->add_trigger( after_create => sub { my $self = shift; my $update = Search::InvertedIndex::Update->new( -group => "author_name", -index => $self->uid, -data => $self->name, -keys => { map { $self->_canonicalise($_) => 1 } split(/\s+/, $self->name) } ); $map->update( -update => $update ); } } ); sub _canonicalise { my ($class, $word) = @_; return "" unless $word; $word = lc($word); $word =~ s/[aeiou]//g; # remove vowels $word =~ s/(\w)\1+/$1/eg; # collapse doubled # (or tripled, etc) letters return $word; }
(We'll also want similar triggers for
after_update and
after_delete, in order that our indexing is kept up to
date with our data.)
Then we can write the fuzzy_matching method:
sub fuzzy_match { my ($class, %args) = @_; return () unless $args{name}; my @terms = map { $class->_canonicalise($_) => 1 } split(/\s+/, $args{name}); my @leaves; foreach my $term (@terms) { push @leaves, Search::InvertedIndex::Query::Leaf->new( -key => $term, -group => "author_name" ); } my $query = Search::InvertedIndex::Query->new( -logic => 'and', -leafs => \@leaves ); my $result = $map->search( -query => $query ); my @matches; my $num_results = $result->number_of_index_entries || 0; if ( $num_results ) { for my $i ( 1 .. $num_results ) { my ($index, $data) = $result->entry( -number => $i - 1 ); push @matches, $data; } } return @matches; }
(The matching method can be improved. I've found that neither
Text::Soundex nor
Text::Metaphone are much
of an improvement over the simple approach already detailed, but
Text::DoubleMetaphone is definitely worth plugging in, to
catch misspellings such as Nicolas/Nicholas and Asimov/Azimof.)
There are plenty of other features that our little web application
would benefit from, but I shall leave those as an exercise for the
reader. I hope I've given you some insight into my current preferred
web development techniques--and I'd love to see a finished
Bookworms application if it does scratch anyone's
itch. | http://www.perl.com/pub/2003/07/15/nocode.html | CC-MAIN-2015-48 | refinedweb | 2,171 | 54.56 |
Agenda
See also: IRC log
<trackbot> Date: 24 September 2015
Wo hoo! Good to have you back zakim bot :-)
<Makx> so I understand the problem was that the start time given on the agenda (12:00 Berlin) was in error. I see that 8:00 Sao Paulo is 13:00 CEST.
<Makx> Some of us were here an hour ago.
:-( A thousand apologies Makx
<Caroline_> Hello!
<Makx> I am connected to WebEx but hear no sound
<Makx> yes, sound is on
<deirdrelee> agenda:
deirdrelee: Thanks Nic BR for
hosting us and looking after us so well
... note the poster!
... We're at quite a mature stage now. We need to get into the details of the docs
... we get through a lot at F2F meetings
... I'm sure these days will be the same.
... We're quite punctual. Set up within 20 mins
Vagner_Br: Welcome everyone.
Pleasure to have Phil and Dee at the conference yesterday
... Thanks Brazil team for coming as well
-> DQV
<deirdrelee> agenda:
deirdrelee: Editors have prepared questions for us all
<deirdrelee> dqv agenda:
deirdrelee: Turns over the Antoine and Riccardo
<RiccardoAlbertoni> sure ..
<RiccardoAlbertoni>
antoine: Offers a brief review of the doc at
<scribe> scribe: phila
<scribe> scribeNick: phila
phila: I really like the intro text
antoine: A reminder that we're
not defining what quality is - rather, we're offering a core
framework that can be extended to create their own metadat
about the quality of datasets
... Idea is to make it easy to compare quality assessments and enhance the interop of these systems
... usual sections on conformance and namespaces
... Some vocab review, presents the main parts of the vocab
... RiccardoAlbertoni created this section - very usefeul
... the Datasets class is the subject of any description. Below and around that are the different aspects of quality that we've identified so far
... Top class is the class for dcat:Datastet or dcat:Distribution
... on the left is the part about quality measures
... not so much inspired as copied from DAQ
... the middle part - there are a couple of classes about annotations
... this is an area for discussion later
... on the right is the part about conformance
... we'll have discussions later about conforming to certain standards
... and we're not sure how to indicate that an SLA is available
... so these are the core elements of hte model
... The dotted line are about representing provenance
... this has been discussed on the mailing list. We re-use Prov of course but there is some discussion about containment
phila: Clarified the different divisons
antoine: There's an open
nquestion on what role Prov should play, how does that relate
to quality
... one aspect of prov is the prov of the quality metadata
... this is important but that's at a different meta level
BernadetteLoscio: Is the quality annotation done by the publisher?
antoine: It can be, or the data
re-users
... this will be a topic for future work
... which will go hand in hand with DUV
BernadetteLoscio: Yes, if it's given by the consumer then it's related to the usage, where we have methods for feedback
antoine: Yes.
... That's the a good transition
... You can see that one of the first issues for DQV is the relationship/overlap with DUV
... that's scheduled later in the agenda
WagnerMeiraJr: It seems that
you're considering quantitative measure.
... I've seen this done - is that a parallel path?
antoine: This is a good point.
Right now, the point about measures is quantitative.
... This comes from the DAQ vocabulary that we've re-used.
... I'm not clear how to add a qualitative measure. That could be seen as an annotation unless there's a clear example of how to make it more structured
... A problem that we face is that we don't have a lot of examples
... so please if you know if any, please provide them
WagnerMeiraJr: One example - in
info retrieval. If you have a live experiemnt with users
evaluating text, you give them a set of possible responses
(like sentiment analysis)
... and you're measuring how the dataset matches expectations
... and benchmarks
... I can collect some examples and send them to the group
antoine: So you mean things like 5 star scales
WagnerMeiraJr: Yes.
antoine: If you could write that
up it would be very helpful
... Is a scale quantitative or qualitative? - that's a question
... Probbaly not a good idea to enter deep discussion on this as we've not considered it. So examples would be very helpful so that we can see where they fit in the model.
action meira to collect examples of qualitative feedback and send them to the group, including 5 star scales
<trackbot> Error finding 'meira'. You can review and register nicknames at <>.
action wagner to collect examples of qualitative feedback and send them to the group, including 5 star scales
<trackbot> Created ACTION-200 - Collect examples of qualitative feedback and send them to the group, including 5 star scales [on Wagner Meira Jr. - due 2015-10-01].
laufer: Raises issue of metadata about different distributions of the same dataset
antoine: I'm tempted to ask you to raise that later as it's very specific. I don't want to skip it, but from the perspective of the discussion process I'd like to continue the agenda
<RiccardoAlbertoni> i am taking a note
antoine: What I want to go on to
is not so exciting... section 1 is the standard text about
defining the various classes and properties in the model
... It's currently organised by classes, and then the properties that can typically be applied to this class.
... This is a little different from some vocabs where all the classes are grouped together and then the properties.
... If you think that's not a good way to proceed then please say so.
... otherwise I won't dive into all these tables.
... they just reflect the detailed discussions that we've had
... The tables just reflect what the RDFS/OWL definitions will be
... Section 6 is the example stuff I was mentioning before. We have a general framework so we think it's important to provide examples.
... It's not as complete as it could be so we'll keep on asking for more examples
... There's only so much that we can create ourselves.
... It's good if we can put in real info from real use cases.
... In 6.3 and 4 we see the difficlty about Prov that I mentioned earlier. There's the prov of the annotation and the prov of the dataset
... this will overlap with the BP doc probably.
... We want to include an example of a certificate (e.g. from the ODI)
... and finally something about quality of a linkset. Things published separately - e.g. aligning with SKOS concepts and we want to say something about that.
... We don't want to tell people what quality is but we want others to share their notion of quality
... so we're providing the framework for that.
<Zakim> phila, you wanted to make a suggestion about examples
phila: Suggests using the next publication as a trigger to get new examples
antoine: Can we note an action on the editors to add such a note to the doc
<scribe> ACTION: antoine to add note to DQV document seeking examples from external reviewers [recorded in]
<trackbot> Created ACTION-201 - Add note to dqv document seeking examples from external reviewers [on Antoine Isaac - due 2015-10-01].
antoine: So back to section 7 -
hints for dimensions and metrics
... this refers to the use cases and elements that we have
... need to come back to this with Riccardo
... Main areas that we want t explore are the ones raised by various contributuions to the WG.
... Ideally we want examples relevant to all the elements in section 7
... The last section of the doc is the one that lists the requirements that we elicited previously. It's a motivation section.
deirdrelee: Is it worth going
back to the UCR at this stage?
... might that give us more examples do you think?
antoine: What do you have in mind?
<nandana>
deirdrelee: Maybe update the UCR based on the examples that come in?
<antoine>
antoine: In principle it makes
sense but many of the use cases are very general. In the
previous phase of work, we analysed each use case to see what
they had about quality
... Many of the UCs are too general to get some example from there without going to back to each UC owner
... Only hesitation is the amount of work involved
... maybe that's a discussion for later?
deirdrelee: OK, let's go ahead with the next point on your agenda
antoine: Any comments on the doc overall?
phila: I like it
<laufer> +1
<nandana> +1
deirdrelee: I think the doc looks very strong. There's a logical flow to it, I think it's def in the right direction and it will be very useful
antoine: Then we shouodl get into the very specific issues
<RiccardoAlbertoni> ok
antoine hands over to Riccardo to go through the issues
RiccardoAlbertoni: So we can start with the first issue
issue-184?
<trackbot> issue-184 -- Is an dqv:ServiceLevelAgreement a kind of certificate, or a standard? -- open
<trackbot>
<RiccardoAlbertoni> issue-184?
<trackbot> issue-184 -- Is an dqv:ServiceLevelAgreement a kind of certificate, or a standard? -- open
<trackbot>
RiccardoAlbertoni: It's current
defined as a kind of standard. One part of the discussion is
whether this is right or is it a certificate
... Some have said that an SLA is neither. It's a collection of promises
... So it seems to me that an SLA is quite a complex thing.
... There have been 2 proposals. 1 - keep it as a kind of document
... or model it using entities
... Christophe suggested modelling it as a doc, Antoine suggetsed modelling it along the ODRL model
phila: ASks for clarification of poss use of ODRL
<RiccardoAlbertoni> there is a lot of echo ..
phila: they express things like licensing statements
<nandana> +q to comment why ODRL might be useful
phila: It can fit pretty much any sort of agreement between parties, so we could see an SLA as an instance of that
BernadetteLoscio: maybe I missed something, it;s not clear for me, why do you need this SLA info. Will you use it to calculate sometehing?
RiccardoAlbertoni: The idea is
that the SLA tells you how reliable the service is
... so it's related to hte quality
BernadetteLoscio: OK... but for the dataset...
Giancarlo_Guizzardi: There is a
lot of work on this. An SLA is a type of social contract. These
can be understood as aggregations of commitments and
claims.
... This would be an interesting way to look at this. For example, partial satisfaction of a SLA might be met
... I can include some refs to work in this area.
<Zakim> nandana, you wanted to comment why ODRL might be useful
nandana: My first comment matches
Bernadette, are there use cases that motivate its
inclusion?
... I think ODRL can express commitments clearly
<deirdrelee> action Giancarlo_Guizzardi to share examples around service level agreement activity
<trackbot> Error finding 'Giancarlo_Guizzardi'. You can review and register nicknames at <>.
<deirdrelee> action Giancaro to share examples around service level agreement activity
<trackbot> Error finding 'Giancaro'. You can review and register nicknames at <>.
<deirdrelee> action Giancarlo to share examples around service level agreement activity
<trackbot> Created ACTION-202 - Share examples around service level agreement activity [on Giancarlo Guizzardi - due 2015-10-01]. and both ask for SLAs
antoine: My approach to this is there are aspects of quality that everyone agrees are important. Something like the fact that a dataset is refreshed every week
<nandana> another ontology that defines SLAs
<Makx> +q
antoine: So you can measure that, and you might express it in an ODI Certificate
<Giancarlo_Guizzardi> In the following Core Ontology of Services, we address the use of Service Offerings in terms of social commitments and claims. This might be relevant in this context:
antoine: We can represent this in
the mode in several ways
... We don't want to close the door to one way or another. For some people, info that data is udated every week is all they need to know/.
laufer: taking the example of a
Distribution. We have the dataset itself and we have the
service of providing this data.
... it's confusing to know what we're talking about (what's the subject of the triple)
PeterWinstanley: SLAs require an
agreement between parties. So if we're talking about open data
there's only one side
... secondly, if you begin to have the level of detail required in ODRL - I can see a lot of organisations who would pass it to the legal department... for a long time
... Danger is getting to a nice vocab that is only useful in a lab
<Zakim> phila, you wanted to weild Occam's Razor
<deirdrelee> phila: agree with peter. wonders should we use the term SLA as there are two sides,as peter said
<deirdrelee> ... if a publisher wants to publish a pledge then FOAF could be sufficient
Makx: We might be mixing up
things here. An SLA is a promise or a pledge, it doesn't say
anything about the quality of the data
... If I say I'm going to update it every day and trhen I don't, that's confusing
... an SLA doesn't talk about quality
antoine: Lots of points to answer
there.
... start with the last first
... Yes, an SLA is not a measure of quality, but it is useful info to potential users
<Makx> +1 to antoine
antoine: an annotation might say
nothing about quality either
... it depends omn the provenance whether you can assess these things
... I don't think an SLA will solve all quality issues.
... To Peter on ODRL, the risk of adding sometehing that is too complex. I wouldn't suggest that we go through ODRL and include it here.
... If there is a community that thinks it's good to expfess these pledges, then people should be entitled to do this. It's finding the most flexible way to makr this happen.
... I think we're not on very stable ground and I'm wary of closing doors.
deirdrelee: I agree that the SLA
is about the service, not the data, but could be describe the
presence of an SLA as a quality metric. So the metric would be
- is an SLA present?
... which speaks to the relaibility
<jerdeb> 100% agree with deirdre here
deirdrelee: SO we cojld put that in one of the examples without it being explicitly in the model.
antoine: In this case, i'd
consider adding the SLA/Pledge as a sort of annotation rather
than a metirc
... something in the same area as the certificates
... The question was whether an SLA is a certificate or a standard. Now it looks like we want to move it to a third place.
RiccardoAlbertoni: I see there
are opther people who want to say womthing about this. But I
wonder if we're at the point where we can make a proposal
... we are not sure if an SLA is a measuer of quality bnut we don't want to close the door to useful information
<BernadetteLoscio> we had a long discussion about SLA during the F2F at Santa Clara
<BernadetteLoscio>
RiccardoAlbertoni: I'd like to suggest we try and answer a specific question. We have annotations, standards, etc. We want to leave things flexible.
deirdrelee: I think you're raising an important issue wrt to timing. So I'll start timing things.
laufer: I think it's importsant
that SLA is important but we need to be clear. We have the
provenance about the metadata, and then about the data
etc.
... WE have meta meta data
BernadetteLoscio: During the F2F at Santa Clara we discussed SLAs and thought it was probably the wrong term. It's good to look back at that discussion
Giancarlo_Guizzardi: I think it's
useful to have a sort of commitment. When an entity makes a
commitment, that's a potential reason for using a
dataset.
... I'm still puzzled by the use of the word service.
... If there is no social contract then even an SLA commitment might be better.
... Sorry if ontologists have strange concepts sometimes. Whewn you make a pledge, you generally have in mind someone who will receive that commitment.
... Who has the claim here?
antoine: maybe the terminology is
the problem.
... Would the term policy, as defined by ODRL, be applicable
<RiccardoAlbertoni> Do we have a link to the definition ?
<nandana>
<Makx> dct:conformsTo
<antoine> Makx++
antoine: I agree with Phil that
it's not standard
... but I really like dcterms:conformsTo as a property
deirdrelee: So is that a proposal
<Makx> A basis for comparison; a reference point against which other things can be evaluated
<deirdrelee> RiccardoAlbertoni: thinks we should go for a proposal, and we will have an example showing how an SLA is modelled
<RiccardoAlbertoni> yes
BernadetteLoscio:
If you're going to describe this commitment, maybe you should consider the measure you're going to use to describe the dataset.
scribe: The commitment should reflect the quality description
<Zakim> nandana, you wanted to ask whether antoine is proposing to use ordl:Policy or to define dqv:Policy instead of dqv:SLA
nandana: At some point I think I understood that we don't want to use the ODRL policy, but maybe we want dqv:Policy which might be a sub class of dcterms:Standard
antoine: I think we should have just that - dqv:Policy rdfs:subClassOf dcterms:Standard and then an example
<BernadetteLoscio> yes!
antoine: I assume that what Berna has in mind is the dimensions?
<nandana> I think antoine said dqv:QualityPolicy
laufer: It's interesting to see
the differnet users of he document about the quality. We have
the publisher, the consumer, etc.
... maybe an intermediary
... Users can make statemetns about the dataset, the service etc. That makes the info complicated
<RiccardoAlbertoni> replace the class dvq:ServiceLevelAgreement with dqv:QualityPolicy (subclass of ODRL:policy ?!? ), and check against some "real" example if this works for the group
deirdrelee: Invites Antoine and Riccardo to wrap this up
<nandana> dqv:QualityPolicy (subclass of dcterms:Standard)?
<antoine> Suggested re-write: 1. replace current dqv:ServiceLevelAgreement with dqv:QualityPolicy, subclass of dcterms:Standard and odrl:Policy 2. add an example with an SLA as Quality Policy, trying to use the same dimensions as metrics and annotations
PROPOSED: 1. replace current
dqv:ServiceLevelAgreement with dqv:QualityPolicy, subclass of
dcterms:Standard and odrl:Policy 2. add an example with an SLA
as Quality Policy, trying to use the same dimensions as metrics
and annotations
... 1. replace current dqv:ServiceLevelAgreement with dqv:QualityPolicy, subclass of dcterms:Standard and odrl:Policy
<Makx> +1
PROPOSED: Add an example with an SLA as Quality Policy, trying to use the same dimensions as metrics and annotations
Giancarlo_Guizzardi: I was
thinking about what luafer said
... We have these differnet relationships between entities around the dataset
... I've made this dataset according to something else, like a quality policy
... Perhapos there is a general pattern to unify the two vocabs
<nandana> +1, we should also investigate a bit about odrl:Policy semantics as the definition didn't say much
Giancarlo_Guizzardi: You have certain activities... I can use a certain dataset, committing not to do sometehing... differnet roles and activities
<antoine> ODRL has prohibitions as part of the Policy
Giancarlo_Guizzardi: Explores
various relationships between different actors.
... The pattern will be the same in DQV and DUV
RiccardoAlbertoni: Not sure if I understand the proposal of Giancarlo
antoine: If people want to
represent these things, then that's when they can go and look
into ODRL
... ODRL includes way to exprfess constraints and prohibitions
... it might be a good thing to point to odrl:Policy
PROPOSED: Replace current dqv:ServiceLevelAgreement with dqv:QualityPolicy, subclass of dcterms:Standard and odrl:Policy
<deirdrelee> PROPOSED: 1. replace current dqv:ServiceLevelAgreement with dqv:QualityPolicy, subclass of dcterms:Standard and odrl:Policy
<nandana> +1
0 (I don't think dcterms:Standard is right but I defer to Makx)
<yaso> +1
<antoine> +1
<newtonca_> +0
<RiccardoAlbertoni> +1
<BernadetteLoscio> 0
<Gisele> 0
<PeterWinstanley_> 0
Splitting the proposal
<deirdrelee> PROPOSED: replace current dqv:ServiceLevelAgreement with dqv:QualityPolicy,
<RiccardoAlbertoni> let's split in two..
+1
<RiccardoAlbertoni> +1
<Giancarlo_Guizzardi> +1
<antoine> +1
<Gisele> +1
<nandana> +1
<PeterWinstanley_> +1
<laufer> +1
<jerdeb> 0 (i am still not sure about the concept fitting quality metadata - but will give my views after seeing an example)
RESOLUTION: replace current dqv:ServiceLevelAgreement with dqv:QualityPolicy
RESOLUTION: replace current dqv:ServiceLevelAgreement with dqv:QualityPolicy
<deirdrelee> PROPOSED: dqv:QualityPolicy will be subclass of dcterms:Standard and odrl:Policy
<antoine> +1
<deirdrelee> PROPOSED: dqv:QualityPolicy will be subclass of dcterms:Standard
<antoine> +1
<laufer> +1
<nandana> +1
+0 Only 0 not -1 because Makx thinks it's right
<RiccardoAlbertoni> +1
<adrianov> +1
<PeterWinstanley_> 0
<BernadetteLoscio> 0
<Giancarlo_Guizzardi> 0
<antoine> we can add a specific ISSUE about this to call for feedback
<PeterWinstanley_> policy is not a standard
<jerdeb> 0
+1 to antoine adding it as a specific issue
<deirdrelee> PROPOSED: 2. add an example with an SLA as Quality Policy, trying to use the same dimensions as metrics and annotations
<antoine> +1
<nandana> +1
+1
<Giancarlo_Guizzardi> +1
<deirdrelee> +1
<Seiji> +1
<jerdeb> +1
<RiccardoAlbertoni> +1
<Caroline_> +1
<PeterWinstanley_> +1
<laufer> +1
<BernadetteLoscio> +1
RESOLUTION: Add an example with an SLA as Quality Policy, trying to use the same dimensions as metrics and annotations
<scribe> ACTION: riccardo to add an example with an SLA as Quality Policy, trying to use the same dimensions as metrics and annotations [recorded in]
<trackbot> Created ACTION-203 - Add an example with an sla as quality policy, trying to use the same dimensions as metrics and annotations [on Riccardo Albertoni - due 2015-10-01].
deirdrelee: Because we didn't resolve to make it a subclass of dcterms:Standard, I assumed we have not resolved the odrl:Policy issue as wll
issue-185?
<trackbot> issue-185 -- dqv:QualityAnnotation modeling issues -- open
<trackbot>
RiccardoAlbertoni: That was raised by Antoine.
antoine: Actually I;m not si sure
what the issue was except a general call for feedback
... We would recommend that the instances of this class ?? from Open Annotation
... this was a call for feedback. There has not been a lot of feedback,. so maybe that foodback will come when we look at DUV. For now though I'd say this issue can be closed.
... If everyone's OK I'd say we could resolve to close.
RiccardoAlbertoni: Just wondering whether motivation should refer to ao SKOS concept - do we need a spedcific taxonomy?
<nandana> oa:Annotation ->
antoine: My feeling is that we
should just show some examples but not represent all possible
motivations
... One exception might be that the quality dimensions coujld be modelled as motivations - but I'm not sure
<nandana> oa:motivatedBy ->
BernadetteLoscio: ... The issue is the modelling or the usage of hte annotation? It's not clear what is a quality annotation?
RiccardoAlbertoni: AIUI, the
ontology's vision is that you have to indicate the moitivation
for your annotation and that's usually expressed as a SKOS
concept.
... it could be a post or a reply
... etc.
... We could have a basic taxonomy?
antoine: I realised I've not been
super clear... the proposal is to have at least one concept
defined in our namespace - quality assessment. We can do that
easily enough
... and then if they want to define sub concepts of that, OK
<RiccardoAlbertoni> ok
antoine: I think we should just have this one concept
Giancarlo_Guizzardi_: A comment
about the relationship between user feedback and quality
annotation
... user feedback can be about anything
... maybe the user feedback in data usage is more general than one that makes any statement about quality
laufer: I don't want to try and define quality, but when we talk about annotation, we can say whether the annotation is quality info or not
deirdrelee: Would it make sense 165 and move on to 185?
<deirdrelee> close issue-185 and move to issue-165
Giancarlo_Guizzardi_: We could capture what kind of metric/dimension this annotation is about
<antoine> Giancarlo_Guizzardi++
<antoine> (thought that would be a different issue)
<antoine>.
phila: I like Giancarlo_Guizzardi_'s ideas but they sound like something for hte lab, not the real world.
BernadetteLoscio: Just a comment
- we have the policy that says what is expected, the quality
statement by the publisher and the assessment of the user
... so maybe it would be nice to define everything using the same dimensions
<deirdrelee> phila: if every instance of the class has a particular property, can't you add that inthedefinition of the class. could you use owl to say that they property oa:motivation exists? otherwise redundent triples
phila: If the same triples are always defined, do we need to state them. Can we do it without having to state those triples every time?
antoine: Yes, you define it as an OWL equivalent class with those features
<antoine> +1
<Giancarlo_Guizzardi_> +1
<nandana> +1
<Caroline_> +1
<yaso> 0
<RiccardoAlbertoni> +1
<PeterWinstanley_> 0
<Makx> +1
<laufer> +1
+1
<deirdrelee> RESOLVED:
== Short Break ==
<scribe> scribe: yaso
<Caroline_> 5min break
<BernadetteLoscio> dqv:qualityAssessement is defined on the model?
<RiccardoAlbertoni> Antoine, is there any issues you want to focus in particular .. ?
<antoine> I think we could try to NOT discuss the provenance issues, which are very technical (181). The voc management ones could be postponed, but I guess they will be naturally as they are at the end :)
<RiccardoAlbertoni> Ok
<antoine> Riccardo, I think we should focus on 165, 187, 190, 164, 153, and GeoDCAT-AP
<RiccardoAlbertoni> let's go for the 165 ? which I am afraid will bring lot of discussion .. what do you think .. and then 187 I think there is a kind of consensus about keep the cardinality between dimension and metric as in DAq so I suppose we can easily close it ..
<antoine> 165 is needed as per the connection to DUV
<RiccardoAlbertoni> ok
<antoine> 187 may not be so consensual. Actually I had understood that the consensus was rather on not keeping the cardinality from daQ, i.e. relax it.
<RiccardoAlbertoni> ok let's go for 165, 187, 190, 164, 153, and GeoDCAT-AP ..
antoine: this is issue 165
<deirdrelee> issue-165
<trackbot> issue-165 -- What is the relation between duv:Feedback and dqv:UserFeedback? -- open
<trackbot>
antoine: user feedback is a kind of quality annotation
<nandana> DUV ->
Giancarlo_Guizzardi: things like
correction and suggestion
... you can say "I don't like this vocab" and etc
<BernadetteLoscio> +1
Giancarlo_Guizzardi: no all feedback is quality annotation
antoine: actually i completely understand what Giancarlo_Guizzardi said
<RiccardoAlbertoni> +1 to QualityUserFeedback
Giancarlo_Guizzardi: that was going to be my suggestion
laufer: my question is to
Giancarlo_Guizzardi: if only sometimes feedback are quality
information, how can we say that an annotation is a quality
information if we don'tlate it to a dimension
... yes, but how say to the user that he can or not put this information in this document
<nandana> +q to ask whether it was intentionally left Feedback to cover more things than user feedback? (so instead of using dqv:UserQualityFeedback and use just dqv:QualityFeedback)
Giancarlo_Guizzardi: I think this has to do with the issue regarding user Feedback
phila: in practice, you might
have a CKAN portal, somebody makes use of a dataset - it's hard
to get people to fit at your data model
... if it's a machine that is going to classify your data then you can have a more complicated model
... but if otherwise, not
... we should keep a strong focus on how it will be in a real world, with real application
BernadetteLoscio: we were
discussing if we should have specific types of feedback
... if we want to specify the types of feedback
<Zakim> nandana, you wanted to ask whether it was intentionally left Feedback to cover more things than user feedback? (so instead of using dqv:UserQualityFeedback and use just
BernadetteLoscio: if we decide that we are going to have just feedback, so it fits the data usage vocab
nandana: you said feedback specifically
<BernadetteLoscio> q_
<nandana> I was just referring to the difference Feedback and *User*Feedback
BernadetteLoscio: I think we can keep feedback general
<RiccardoAlbertoni> Proposal: rename DQV:UserFeedback with dqv:QualityUserFeedback making it as duv:Feedback
BernadetteLoscio: but tomorrow we are going to discuss if we are going to have this subclass, right?
<Giancarlo_Guizzardi> Feedback = UserFeedback (as far as I understand it). You are right that only one of them should be used
<RiccardoAlbertoni> Proposal: rename DQV:UserFeedback with dqv:QualityUserFeedback making it as duv:Feedback subclass
antoine: right now I don't feel
that is incompatible with this decision
... I like the fact that is from users
<RiccardoAlbertoni> +1 to antoine
<Giancarlo_Guizzardi> +1 (terminologically speaking it seems like a good idea)
it will be interesting to keep the user on the label of the class
<Giancarlo_Guizzardi> in that case we would have UserFeedback that is specialized in QualityUserFeedback
<nandana> +1
deirdrelee: ok so for now we will keep the user on the class
<Giancarlo_Guizzardi> which in turn specializes QualityAnnotation
<RiccardoAlbertoni> Proposal: rename DQV:UserFeedback with dqv:QualityUserFeedback making it as duv:Feedback subclass
<antoine> +1
deirdrelee: and in terms of ricardo's proposal
<Seiji> +1
<jerdeb> +1
<RiccardoAlbertoni> +1
<deirdrelee> +1
Giancarlo_Guizzardi: I guess that if we agree with antoine, feedback should be UserFeedback
<RiccardoAlbertoni> yeah please
<Giancarlo_Guizzardi> rename DQV:UserFeedback with dqv:QualityUserFeedback making it as duv:UserFeedback subclass
<adrianov> +1
<laufer> +1
deirdrelee: in general we agree with this?
+1
<BernadetteLoscio> +1
<Giancarlo_Guizzardi> +1
<Caroline_> +1
close issue-165
<trackbot> Closed issue-165.
<deirdrelee> RESOLVED: rename DQV:UserFeedback with dqv:QualityUserFeedback making it as duv:Feedback subclass
antoine: we proposed to move to issue-187
<deirdrelee> issue-187
<trackbot> issue-187 -- Do we want to keep the same occurrence constraints as defined in DAQ (for example, that every metric should belong to exactly one dimension)? -- open
<trackbot>
Do we want to keep the same occurrence constraints as defined in DAQ (for example, that every metric should belong to exactly one dimension)?
Giancarlo_Guizzardi: dimension
would be a quality dimension, like height etc
... so availability would be a sort of dimension
antoine: right now it belongs to
one dimension
... imagine that uptime could be a metric for availability
<BernadetteLoscio> antoine - I can't find dqv:qualityAssessement in the model
<Zakim> jerdeb, you wanted to clarify
jerdeb: a dimension is made of many metrics
<antoine> BernadetteLoscio - yes the idea is that we've resolved to add it
Giancarlo_Guizzardi: then I would
change the description in the document
... it is a bit confusing
<antoine> yes the wording with "unit" is confusing
<nandana> DAQ diagram ->
<BernadetteLoscio> antoine - ok! sorry :)
RiccardoAlbertoni: I was wondering if Giancarlo_Guizzardi can write the definition that he suggested
<Gisele> RiccardoAlbertoni: we are closig the issue and keeping the constraints
<antoine> -1
<Giancarlo_Guizzardi> A Metric is not a unit of measuring. An Observation (QualityMeasure) assigns a value in a given unit to a Metric
<Gisele> jerdeb: I suggest that we use these constraints and propose to provide guidelines
<Gisele> ... I believe we should keep than as guidelines but not formally constrain them
<antoine> jerdeb++ it's really great that you've consulted with colleagues!
<Gisele> ... we should still provide guidelines
<nandana> +1 to jerdeb
<phila> +1
<Gisele> deirdrelee: that would mean that the concepts we use would have no constraints but only guidelines
<Giancarlo_Guizzardi> I meant "Unit of Measurement" instead of "unit of measuring" (although DQV mentions "unit of measuring")
<Zakim> phila, you wanted to ask if a metric is a slice
<Gisele> phila: aguideline is a slice thourgh a datacube
<Gisele> ..i'trying to match what are saying with my knoeldge on data cube
<Gisele> jerdeb: we can have slices from multiple observation but im not sure
<Gisele> deirdrelee: proposal for issue 187
<deirdrelee> PROPOSED: Don't keep the constraints from DAQ but provide guidelines
<ericstephan> good morning phila :-)
<deirdrelee> +1
<BernadetteLoscio> Hi Eric! :)
<antoine> +1
<phila> +1 Noting that DAQ is moving in the same direction
<Seiji> +1
<nandana> +1
<Gisele> +1
<RiccardoAlbertoni> +1
<laufer> +1
<ericstephan> ericstephan present+
<adrianov> +1
<jerdeb> +1 (will remove constraints from daQ as well)
Giancarlo_Guizzardi: what do we mean by "provide guidelines"
<deirdrelee> RESOLVED: Don't keep the constraints from DAQ but provide guidelines
close issue-187
<trackbot> Closed issue-187.
issue-189
<trackbot> issue-189 -- Aether VoID extension uses a different from the pattern that DQV inherits from DAQ -- open
<trackbot>
Giancarlo_Guizzardi: we could
have a uniform treatment of this part of the model. So I was
wondering if we are going to have a discussion on this, or it
will be discussed my email.. It's a general question
... there's a lot of work here that we could use, there's a lot o discussions here
<Giancarlo_Guizzardi> Ok. Thanks
<deirdrelee> issue-189
<trackbot> issue-189 -- Aether VoID extension uses a different from the pattern that DQV inherits from DAQ -- open
<trackbot>
antoine: in our patter for measure on the quality of datasets there will be a connexion between
<RiccardoAlbertoni> to phila
antoine: the question is if we are comfortable with a more complex proposal and if we should try to reflect this in the document
<Giancarlo_Guizzardi> A known proposal in the subject actually comes from VU:
<antoine> can I try to re-phrase the problem?
<antoine> <> <> "62,014"^^<> ;
<Giancarlo_Guizzardi> Other relevant references are:,. We also did some work on that which could be relevant: and
antoine: this about it and decide if this is something that we are comfortable with
<phila> scribe: Giancarlo_Guizzardi
RicardoAltertoni mentions that we need some of this complexity in the proposal but he also thinks that Antoin is right in advocating a simple way of representing statistics
<nandana> +1 to RiccardoAlbertoni. we might start with Aether but end up again something similar to DAQ if we want to represent the all the information to that we represent now
<Zakim> phila, you wanted to make a suggestion
<RiccardoAlbertoni> +1 to jerdeb
<phila> phila: I asked whether it might be possible to treat Aether VoID as a quality meansure within DQV, or use a CONSTRUCT query to convert from one to the other. The answer was no.
laufer, DQV is a way to besides the quality of the data, it semantically describes the data
<deirdrelee> laufer: trying to understand issue. i think that dqv is a way of as well as describin quality data, we describe the semanticcs
<deirdrelee> ... void is description of the data,not the semantics of the informaiton. so void and dqv are two differnet things
<deirdrelee> ... it is more complicated to describe the semantics ofthe data
<RiccardoAlbertoni> +1 to laufer
laufer, these are two separate things. Describing the semantics of the quality of the data is more complicated but it is a more general model
<jerdeb> jerdeb: re transform Aether to daQ -> no this cannot happen because we do not know any quality information about the aether property, such as category and dimension which are important to daQ
<deirdrelee> ... dav is a simpler model, but they don't have semantics
riccardo, once you have described your property with DAQ, it is possible to serialized it Aether but not the other way around
<deirdrelee> RiccardoAlbertoni: it is difficult to erialise the results in the header as daq is more complex
RiccardoAlbertoni: the bridge can only be done in one direction
<deirdrelee> antoine: it's not that the void extension has not semantics. the semantics are in the properties
antoin, it's not that the VoiD extension has no semantics.
<deirdrelee> ... the semantics are not positions as a quality metric
<deirdrelee> ... we feel as a group not satisfied, that we're missing something
<deirdrelee> ... it must be possible to express these simple triples
<deirdrelee> laufer: agree we have semantics in the properties, but in dqv in the description there will be semantics, a more sophisticated way
antoine: we seem to be calling semantics different things
<phila> issue-189?
<trackbot> issue-189 -- Aether VoID extension uses a different from the pattern that DQV inherits from DAQ -- open
<trackbot>
<deirdrelee> ... we don't really have the means to find out they're about quality, they're just properties. dqv provides a framework that facilitates interoperability
<deirdrelee> deirdrelee: make a specific proposal around issue-189
<deirdrelee> RiccardoAlbertoni: proposal, keep dqv as it is,provide guidance on how to convert daq to aether void
<deirdrelee> antoine: we should have this for market adoption
<deirdrelee> phila: i've been looking at aether, i'm happy to say we keep dqv as it is
<deirdrelee> ... they're not antagonistic, we can extend dqv with aether, there are lots of other things that you could say about the dataset, not necessary to include
<deirdrelee> antoine: really have doubts about it. i'm in a community where they'll look at vocab like aether and say this is quality
<phila> phila: That makes it sounds as if I don't like Aether voID - it looks very interesting. I just don't think it's necessarily something we should feel obliged to move towards/include as an example
<deirdrelee> ... agree not all statistics are relevant for quality, but would like us to be stronger about
<phila> PROPOSED: keep dqv as it is, provide guidance on how to convert daq to aether void
<deirdrelee> antoine: in my community this is important
<deirdrelee> PROPOSED: keep dqv as it is, provide guidance on how to convert daq to aether void
<jerdeb> -1 (because there are other ontologies like aether, such as lodstats)
<phila> +1
<laufer> -1
<antoine> +1
<ericstephan> +1
<deirdrelee> 0
<PeterWinstanley_> +1
<Seiji> +1
0
<Caroline_> +1
<RiccardoAlbertoni> +1
<Gisele> 0
<deirdrelee> anthoine: it doesn't have to be aether
<deirdrelee> PROPOSED: keep dqv as it is, provide guidance on how to convert daq to another quality statistics vocabulary
<laufer> +1
<Seiji> +1
<nandana> +1
<jerdeb> +1
+1
<adrianov> +1
<antoine> +1 to "work with"
<Caroline_> +1
<ericstephan> +1
<RiccardoAlbertoni> +1
<deirdrelee> PROPOSED: keep dqv as it is, provide guidance on how daq can work with another quality statistics vocabulary
+1
<phila> +1
<deirdrelee> +1
<Gisele> +1
<laufer> +1
<jerdeb> +1
<adrianov> +1
<Seiji> +1
<RiccardoAlbertoni> +1
<Caroline_> +1
<deirdrelee> RESOLVED: keep dqv as it is, provide guidance on how daq can work with another quality statistics vocabulary
<nandana> _1
<nandana> +1
<ericstephan> ++++++++++++++++++1
<deirdrelee> close issue-189
<phila> RESOLUTION: keep dqv as it is, provide guidance on how daq can work with another quality statistics vocabulary
<trackbot> Closed issue-189.
<deirdrelee> issue-164
<trackbot> issue-164 -- Are statistics about a dataset a kind of quality info we need to include in the data quality vocabulary? -- open
<trackbot>
<RiccardoAlbertoni> yeah , let's close it
<phila> I think we just resolved that issue
<deirdrelee> antoine: proposal is we agree that some statistics may be relevant for expressing data quality
<deirdrelee> ... after resolution for issue-189, we should have examples
<phila> PROPOSE: Close Issue 164 as previous proposal covers it
<phila> PROPOSE: Close Issue 164 as previous resolution covers it
<deirdrelee> +1
<BernadetteLoscio> +1
<phila> +1
<Seiji> +1
<laufer> +1
<antoine> +1
<RiccardoAlbertoni> +1
<adrianov> +1
<ericstephan> +1
<newtoncalegari> +1
+1
<nandana> +1
<deirdrelee> RESOLVED: Close Issue 164 as previous resolution covers it
<Caroline_>
<deirdrelee> action-153
<trackbot> action-153 -- Antoine Isaac to Look at completeness as one of the quality dimensions -- due 2015-04-20 -- OPEN
<trackbot>
<deirdrelee> RiccardoAlbertoni: the discussion in the mailing list says that completeness is an example of one ofthe quality dimensions
<deirdrelee> jerdeb: agree that completeness should be a dimension. how can we measure this as linked data?
<deirdrelee> ... open world assumptions
<deirdrelee> RiccardoAlbertoni: we have to assume closed world to measure completeness
<deirdrelee> jerdeb: that's one of the main problems i'm having, difficult to measure
<deirdrelee> antoine: some more info on this aciton. like RiccardoAlbertoni said, completeness is important to measure, but didn't receive much feedback
<deirdrelee> ... asked for specific feedback on completeness but didn't get any
<deirdrelee> ... similar to statistics, used this as a proxy for completeness
<deirdrelee> ... if you are keen for completeness, please send examples
<deirdrelee> phila: one of the reasons i don't like using dcterms:conformsto is that ?
<deirdrelee> ... there are various things that you could point to something that defines what complete meants
<deirdrelee> RiccardoAlbertoni: there are some situation that the closed world assumptoin works fine, and we would like the opportunity to say something about it
<phila> phila: I was saying that one quality description could be that the dataset matches a spedcific profile, such as DCAT-AP, or maybe point to a SHACL description ()
<deirdrelee> phila: it could even be a description in a pdf. as long as you say it conforms to, e.g. to say that ckan dcat export
<deirdrelee> RiccardoAlbertoni: we are thinking about different kind of completeness. the one i'm talking about is the one in the linked data survey
<deirdrelee> ... being compliant to a certain profile
<phila> PROPOSED: That we include completeness as a quality metric. That can be defined in any way that puts boundaries around what the data should contain.
<nandana> +1 for including completeness dimension and asking for concrete metrics and examples.
<phila> PROPOSED: That we include completeness as a quality dimension. That can be defined in any way that puts boundaries around what the data should contain.
<phila> PROPOSED: That we include completeness as a quality dimension. That can be defined in any way that puts boundaries around what the data should contain, closes the world etc.
<BernadetteLoscio> +1
<Seiji> +1
+1
<antoine> +1
<nandana> +1
<RiccardoAlbertoni> +1
<deirdrelee> +1
<Gisele> +1
<phila> +1
<laufer> +1
<Caroline_> +1
<ericstephan> +1
<phila> RESOLVED: That we include completeness as a quality dimension. That can be defined in any way that puts boundaries around what the data should contain, closes the world etc.
<phila> RESOLUTION: That we include completeness as a quality dimension. That can be defined in any way that puts boundaries around what the data should contain, closes the world etc.
<jerdeb> +1 if we have specific examples for population completeness and schema completeness
<phila> close issue-153
<trackbot> Closed issue-153.
<RiccardoAlbertoni> yeah it was very useful ..
<antoine> Thanks everyone!!!
<phila> == Lunch ==
<BernadetteLoscio> Thanks!
<laufer> Thank antoine, riccardo
<phila> close action-153
<trackbot> Closed action-153.
<jerdeb> sorry but need to leave now. will join you again tomorrow morning (afternoon here in germany)
<deirdrelee> close-164
<deirdrelee> close issue-164
<trackbot> Closed issue-164.
<RiccardoAlbertoni> enjoy the lunch!
<deirdrelee> ok, let's get back...
<newtoncalegari> Let's go
<RiccardoAlbertoni> yeah.. I am on webex
<deirdrelee>
<newtoncalegari> yaso: starting the meeting with BP agenda
<yaso>
<deirdrelee> scribe: newtoncalegari
<yaso> ISSUE-137
<trackbot> ISSUE-137 -- Review BP Preserve person's right to privacy -- open
<trackbot>
yaso: issue-137 about privacy
BernadetteLoscio: during the last F2F we had a discussion about privacy
<deirdrelee> BP Editor's draft:
BernadetteLoscio: and we raised
some issues
... now we need to decide what we gonna do
... hadleybeeman was not sure if we will talk about privacy
<yaso>
BernadetteLoscio: so, there is
this action to rewrite the BP. but we need to discuss what we
need to do
... to rewrite, keep it as it is, or discontinue..
... the discussion in the end of last f2f was not clear if we should have a BP like this, about privacy
... what we should do with this section?
phila: yes, hadleybeeman make the point that it's not technical
<phila> It is clearly essential that individuals' privacy is respected. This means that Personally Identifiable Information needs to be handled according to policies and procedures that reflect the local jurisdictional context and it is therefore beyond the scope of this document to make specific recommendations on this topic.
phila: makx suggested that we put
some text in the introduction
... we can potential link to some definition
<yaso> ericstephan,
phila: the scope is policy and law, and it's not in the technical scope
<phila> Makx's comment
ericstephan: phila is propposing
to take this out of the BPs, and put it in another
section
... it could be in a section called "Assumptions"
<phila> ericstephan: Perhaps we could have a section called 'Assumptions' - i.e. things that we recognise as being important but that are out of scope.
yaso: there are challenges in the Use Cases and this challenge is out of the scope
<deirdrelee> BP 20q+
phila: we can't in a Technical document say "you should follow the law"
<phila> Principles/assumptions - I;m OK wth either
(someone could help me with Peter speech?)
BernadetteLoscio: we can add some links appoint to this issue of Sensitive Data
yaso: is there any way to ask to other groups to deal with it?
phila: dealing with this issue is different of using dublin core, or vocabs
<phila> Peter was saying that in Enterprise Architectures often begin with a bunch or principles
deirdrelee: there is a technical element on saying to share, integrate, publish datasets
<Caroline> +1 to deirdrelee
<Caroline> to put in the BP document
laufer: the ideia of a paragraph
is interesting to clarify people there is a law to deal with
it
... we don't need to have a BP about it, the paragraph is enough
Caroline: BernadetteLoscio and I
discussed about it
... if we don't keep it as a BP, it's important to say something about this topic
... say that this topic is broader than other BPs
... I Agree with Deirdre on point about this in the Document
Giancarlo_Guizzardi: I
agree
... but it's very complicated
... this seems to be also related to one aspect of quality
... this is related with conformance
deirdrelee: if you classify a
dataset, you can say some terms are commercial, others
sensitivity
... maybe if we provide a classification for the dataset
BernadetteLoscio: it's quite
similar of what laufer propposed
... if we have a proporty to describe of classify a dataset, maybe it could be a part of the dataset description
deirdrelee: but it could be not only human-readable
<antoine> ?
deirdrelee: need to be machine readable
yaso: I don't think we don't have
to try to classify
... it's not only technical
... I'm in favor of keep as a note and maybe other group to talk about Privacy
phila: Norway classifies datasets
BernadetteLoscio: I think the idea of having an extra metadata to describe this kind of information could be nice
yaso: for instance, if facebook
has an API and I get data from my friends. but suddenly
facebook closes the API, and I can't get my data anymore
... is this data public? sensitive?
... for me it's hard to do that, to classify datasets in that way
Seiji: I think we can have an
agreement among those ideas
... in the Draf there is not section called "Policy"
WagnerMeiraJr: I believe it's
important to make a difference between what is Ethical and what
is Illiegal
... each provider usually have different rules
... it's in our scope to discuss in a BP doc what is illegal or not (???)
... data is in some sense public
... for instance, the ashley madison web site
... they had a agreement about privacy
... but hackers have violated and have gotten the private data
... the second point is what is illegal?
... we may recommend that you verify license and terms
<Zakim> deirdrelee, you wanted to say gov already classify docs as open, confidential, secure, etc
deirdrelee: the data is on the Web, you should recommend a license
ericstephan: (??? sorry ericstephan -( )
laufer: the problem is not when
you have the data, is when someone access the data
... you can have the some dataset with different licenses
<ericstephan> I was just mentioning that I agreed with WagnerMeiraJr and mentioned that this was complementary to the way people think of open and closed data
<deirdrelee> possible proposal: Remove BP 20 'Preserve people's right to privacy'. Instead add a note around data protection and linking to other related work
Caroline: I understand we maybe put as a note
BernadetteLoscio: in this case we need to remove the section, 2 BPs and challenge 'Sensitive Data'
<Makx> +1 to remove BP20. there is no universal 'right to privacy'
yaso: I don't know if we can remove the section
<Zakim> phila, you wanted to argue for BP21
<annette_g> these are two different questions
phila: I agree on removing the
BP20
... but BP21 we cuold keep
<ericstephan> +1 to keeping BP21
<antoine> +1 Actually BP21 is much more on the technical side of things.
<RiccardoAlbertoni> +1 to phil
<yaso> +1 to keeping 21
<Makx> +1 to keep BP21
BernadetteLoscio: but you want to keep the Sesntive Data section, with the BP21 but without BP20?
phila: (you answered yes?)
<deirdrelee> newtoncalegari: should bp21 stay in the sensitive data section or it should be moved?
phila: it's up to the editors :-)
<phila> newtoncalegari: On keeping the BP on Provide data unavailability reference - does that mean keeping the section but with one BP?
<Makx> BP21 has nothing to do with sensitive data
<phila> phila: That's up to the editors
annette_g: for BP20, are we going to replace if it's removed?
<Makx> the only thing we can say about BP20 is that data providers should respect applicable laws
<yaso> +1 to Makx
phila: we are agreeing on taking out BP21 but write some notes about the topic
BernadetteLoscio: if we keep the section 'Sensitive Data', I think we can't have only the description without a BP
<annette_g> +1 to Bernadette
BernadetteLoscio: we can keep the
BP21, but this BP seems to doesn't fit in the Sensitive
Section
... and we need to look for a place for BP21
Caroline: I agree with BernadetteLoscio
<Seiji> +1 to what bernadette said
Caroline: maybe BP21 fits in Data
Preservation section
... and the text of BP20 will be transformed in a note
yaso: we need to let people know Sensitve Data is a challenge, and I think we can keep the section
<Caroline> +1 to yaso that privacy is a challenge important to be mentioned
BernadetteLoscio: Ok. It can be a challenge, but no in the scope of this document, and I don't agree on having a section like others, but without any BP
deirdrelee: two counter suggestions
<Caroline> Caroline: the editors may make the change on Sensitive data and send to the group
annette_g: maybe we can rewrite
the BP
... we need to consider those issues
PROPOSAL: removing BP20 - Preserve people's right to privacy
<phila> PROPOSED: That the Best practice on Preserve people's right to privacy be removed and replaced by a suitable note/paragraph
<annette_g> removing and replacing by a note are two different issues
<yaso> +1
<Makx> +1
<annette_g> 0
<Caroline> +1
<AdrianoCesar-InWeb> +1
<BernadetteLoscio> +1
<BernadetteLoscio> +1
+1
<Seiji> +1
<Gisele> +1
<ericstephan> +1
<deirdrelee> +1
<nandana> +1
annette_g: I think it should a BP
<Caroline> +q
annette_g: agree on removing BP20, but put another BP in the empty place (??? is that right, annette_g? )
phila: writing a draft proposal
<phila> Draft proposal - That the Best practice on Preserve people's right to privacy be removed
<annette_g> * :)*
<phila> Draft proposal that the section on sensitive data be reviewed in the broader scope of the doc
<phila> draft proposal - that privacy is an important issue and we shouold say something, even if it is only "think about this stuff"
<phila> PROPOSED: That the Best practice on Preserve People's Right to privacy be removed
<yaso> +1
<Makx> +1
<annette_g> +1
+1
<Caroline> +1
<RiccardoAlbertoni> +1
<Seiji> +1
<phila> +1
<ericstephan> +1
BernadetteLoscio: Editors will review the Senstive Data section
<phila> PROPOSED: That the section on sensitive data be reviewed in the broader scope of the document
<BernadetteLoscio> +1
<Makx> +1
+1
<laufer> +1
<phila> +1
<Gisele> +1
<deirdrelee> +1
<Seiji> +1
<Caroline> +1
<BernadetteLoscio> +1
<annette_g> +1
<AdrianoCesar-InWeb> +1
<phila> RESOLVED: That the Best practice on Preserve People's Right to privacy be removed
<yaso> newtoncalegari, Draft proposal - That the Best practice on Preserve people's right to privacy be removed
<phila> RESOLUTION: That the Best practice on Preserve People's Right to privacy be removed
<phila> RESOLVED: That the section on sensitive data be reviewed in the broader scope of the document
<phila> RESOLUTION: That the section on sensitive data be reviewed in the broader scope of the document
<phila> close action-164
<trackbot> Closed action-164.
<phila> close action-166
<trackbot> Closed action-166.
<phila> close issue-137
<trackbot> Closed issue-137.
<BernadetteLoscio> bye bye! thanks!
<annette_g> * closed instead of close? *
<yaso>
<yaso> issue-166
<trackbot> issue-166 -- Should the data vocabularies section be removed? -- open
<trackbot>
yaso: we're going to discuss about the issue-166
BernadetteLoscio: there is an
ongoing discussion about this section
... on removing or not the vocabularies section
<annette_g> * oops, didn't see the whole interaction w/trackbot *
BernadetteLoscio: in this section
we have more BPs related on publishing vocabularies, and only
one on using vocabularies
... there is a discussion if we should have BP for publishing vocabularies or not
<RiccardoAlbertoni> bye nandana !
BernadetteLoscio: I discussed by email with antoine, we had some agreements, but we want know if the group agrees on keeping the section or not
laufer: when you say to remove the section, we need to remove the BPs of the section?
<antoine> this is a fair account, BernadetteLoscio
BernadetteLoscio: no. antoine and I have agreed on keep the section, but it's not about the vocabulary creation, but it's vocabulary publication
<antoine> also about re-use
<Seiji> +1 keep the section
BernadetteLoscio: not sure if BP14 should be there
laufer: I don't think BP14 is equal to the 'Re-use vocabularies'
<yaso> laufer has a point
laufer: for me vocabulary is a kind of dataset
<annette_g> examples?
laufer: we can't deal with vocabulary like a special kind of dataset
antoine: I disagree with laufer
<annette_g> +! that these are not datasets
<deirdrelee> +1
<scribe> scribe: Caroline
Giancarlo_Guizzardi: if you
consider all the schemas it would be strange to make
recommendations
... but if the focus is dataset
... the dataset may refers to one BP and define the terms
... it is a essencial aspect of quality of data to have these BPs
... we must say something about it
BernadetteLoscio: do you think we
need to have BPs for the publication of this
... or we just keep the BP like "we should use vocabularies" and "we should use standards"
Giancarlo_Guizzardi: we should
talk about the quality of relation between the datasets and
what we use to annotation
... we should recommend that people use those, whatever they are
newtoncalegari: I agree on
re-using vocabulary
... but it seems confusing on standarizing terms
phila: standarizing terms maybe
not in a vocabulary, I personally woul keep it
... use them, re-use them and tell people what you have re-used is what we could keep
deirdrelee: if we are talking about vocabularies meaning standarized terms and also core vocabulaires or in sens of schemas
newtoncalegari: using standarized
terms refering as vocabularies
... when you say it is like everyone using the same vocabulary could use FOAF, per example
<phila> newtoncalegari: Using standardised terms, referring to vocabs... if I use FOAF - should we always use the prefix 'foaf:'
BernadetteLoscio: it is not clear the difference vocabularies and standarized terms and also from core vocabulaires to other vocabularies
<phila> BernadetteLoscio: I don't know how to distinguish between core vocabs and others
<phila> BernadetteLoscio: We have BPs 15, 16, 17 and 19
BernadetteLoscio: we have 2 things: 1. BPs 15, 16, 17 and 19 are related to vocabularies publication
<phila> ... those are related to vocab publication.
BernadetteLoscio: 2. relation between 14 an 18
<phila> ... What is the relationship between 14 and 18
<phila> laufer: Is a code list a vocabulary?
<phila> scribe; Caroline
<ericstephan> If I cross my eyes I have no problems distinguishing between vocabularies and standardized terms. ;-)
<phila> scribe: Caroline
annette_g: I think vocabulary is
not data
... if vocabularies were the same as data
... it is woth to try people how to be consistency when they use their own terms
<phila> +1 to annette_g
annette_g: if there is not a vocabulary you can try to be consistency
<Makx> There are two types of 'vocabularies'; a. predicate vocabularies (e.. Dublin Core terems) and b. value vocabularies (such as code lists, e.g. language codes)
ericstephan: the question about
difficulties on semantic web that someone asked at Web.br
... I think one of the difficulties of adopting semantic web or existing vocabularies is ??
... I think having guidance on how people use vocabularies is helpful
Giancarlo_Guizzardi: I agree with
phil
... use standarized terms makes sense
... and re-use vocabularies makes sense also
... BPs 14 and 18 may be miss interpreted
<Zakim> phila, you wanted to focus on Use Standardised Terms
Giancarlo_Guizzardi: we should be clear that we are talking about using vocabs to annotate metadada
phila: standarized terms could be
written code lists
... maybe be not metadata
<antoine> for the record code lists are mentioned in BP 19
phila: to write it it is better
to talk first about standarized terms and then code lists
... I would use BP 19
... the ones that are clearly about vocabs we could take them out
Giancarlo_Guizzardi: on BP 19 we should make it clear that we are not talking about vocabulary creation
<deirdrelee> ack Giancarlo_Guizzardi n
<phila> PROPOSED: That the BP on Use Standardized Terms be amended to talk about terms and code lists
<phila> draft prop - that
<phila> Best Practice 15: Document vocabularies, Share vocabularies in an open way , Vocabulary versioning be removed
laufer: we have a lot of communities that use some terms as standards for them
deirdrelee: to be part of a code list of vocabulary it doesn't have to be standarized
laufer: I don't think we have to
use informal things
... but I don't know that our BPs are restricted to things that are only standarized
<phila> Community Standard is the usual term for something everyone uses that isn't a formal standard
<annette_g> I cannot hear anything
<phila> Examples include RSS, GTFS, robots.txt etc.
yaso: at netflix they classify films themselves
<annette_g> * just been about a minute*
yaso: they create a lot of
relationships between the movies and what people write
there
... they don't use W3C standards
<RiccardoAlbertoni> yes
<Makx> I think the term 'vocabulary' is really confusing!
yaso: are you saying that what netflix does would be that?
laufer: kind of
<annette_g> * I got it, local problem *
yaso: if I have a online news agency I could have standards there
Giancarlo_Guizzardi: the purpose
of this BPs is to increase the interoperability
... to community to re-use vocabs
<Zakim> deirdrelee, you wanted to give example of informal codelist
Giancarlo_Guizzardi: we could capture that on these terms
deirdrelee: in Irland there are 4 or 5 vocabs valid for spacial references
BernadetteLoscio: we should
define what we mean about standarized terms
... I propose we keep it and put code list
... considering also Giancarlo_Guizzardi suggestion's to show the consensus about a term
<Makx> And also define what we mean by 'vocabulary'
BernadetteLoscio: we can rewrite it considering these comments
<BernadetteLoscio> yes Makx ;)
<Giancarlo_Guizzardi> It think it is more about shared vocabularies than standard vocabularies, i.e., vocabularies that capture a consensus of the community the dataset refers to
<annette_g> * is someone speaking/ *
<RiccardoAlbertoni> could you write a proposal because I think I am a little lost ;)
<BernadetteLoscio> :)
<phila> - That Choose the right formalization level be reviewed
phila: I have 4 proposals
... before we do all that, is that a consensus?
<laufer> +4
<annette_g> +4
+4
<yaso> +4 also (new kind of voting)
deirdrelee: from the external comments and feedback was anything about it?
<laufer> speed voting
BernadetteLoscio: no, only internal discussion for now
PeterWinstanley: I have to go! I see you tomorrow!
<annette_g> bye Peter!
<Giancarlo_Guizzardi> +4 (+1 (but we should make sure that we don't mean Use Standardized Terms in creating your vocabulary and we don't mean "use the right formalization level in creating...")
<Makx> -1
<Giancarlo_Guizzardi> and we don't mean re-use vocabularies in creating a vocabulary, etc...
RiccardoAlbertoni: I am ok with
it
... but I would like to see something: "if you are defining your own vocab follow this"
yaso: are you saying that we should recommend if someone is defining a new vocab
<phila> The BP on re-using vocabs already points to the LD-BP document
RiccardoAlbertoni: we should at least adjust to follow the document that has been done in Linked Data Government group, per example
BernadetteLoscio: we can put this
in the section introduction
... that there are other materials
annette_g: if you have to create
a vocabulary, how are we mentioning something that already
exists?
... if you don't find a existing vocab you could use something that already exists
RiccardoAlbertoni: if you have a
data to publish and you have your own database and the schema
is not mentioning what you are using
... you need to define more portion of a vocab
... as a publisher you have to make that undertandable
... that is why you suppose to publish your vocabulary
... and people can understand a specific attibute
... my suggestion is to put a link to Linked Data gov group because they already explain how to do data
<Zakim> deirdrelee, you wanted to sya that could be part of desc of bp18
RiccardoAlbertoni: if you don't want to go to linked data we can suggest that it could rely on something else
deirdrelee: I agree with RiccardoAlbertoni
<Makx> +1
deirdrelee: we can mention the vocabs to be seen
phila: there is already in the
BPs
... it could be emphazied
<phila> RiccardoAlbertoni: Yes, it's there but we should emphasise that the doc talks about creating vocabs if they don't already exist.
Makx: BP 18 we use in a way that
RDF uses vocabs
... in DCAT they talk in a different way
... sometimes we use vocabs differently
... my suggestion is that where we use vocabs as attibutes
... so people who are not familiar with linked data don't get confused
... I agree that on 14 we use the word standarized terms
laufer: when we are publishing
data we have a BP to provide structural metadata
... a vocab like FOAF doesn't need to be explained
... if I will publish my own ontology the linked data WG can show how to do it
... we could put a link to this document
... I think we don't have to say how to do this
BernadetteLoscio: I think we can
keep Phil's proposal and change the one to re-use the term
vocab and say that the term vocab can be defined
... Makx do you agree?
<phila> draft 3 becomes... - That Re-use vocabularies be retained but the term vocabulary should be defined as a set of attributes
<phila> i.e. we get
but the term vocabulary should be defined as a set of attributes
<phila> - That Choose the right formalization level be reviewed
<yaso> Hi Sumit_Purohit :-)
<Sumit_Purohit> Hi Everyone.
<phila> PROPOSED: That Use Standardized Terms be amended to refer to code lists and other commonly used terms.
<yaso> +1
+1
<deirdrelee> +1
<antoine> +1
<phila> +1
<Seiji> +1
<annette_g> +1
<Makx> +1
<laufer> +1
<newtoncalegari> +1
<ericstephan> +1
<RiccardoAlbertoni> +1
<phila> RESOLVED: That Use Standardized Terms be amended to refer to code lists and other commonly used terms.
<AdrianoCesar-InWeb> +1+
<Sumit_Purohit> +1
<Giancarlo_Guizzardi> +1
<phila> PROPOSED: That Document vocabularies, Share vocabularies in an open way, Vocabulary versioning be removed from the document.
<deirdrelee> +1
<yaso> +1
<phila> +1
<Giancarlo_Guizzardi> +1
<laufer> +1
<Seiji> +1
+1
<annette_g> +1
<newtoncalegari> +1
<Makx> +1
<antoine> +1
<RiccardoAlbertoni> +1
+1
<phila> RESOLVED: That Document vocabularies, Share vocabularies in an open way, Vocabulary versioning be removed from the document.
<phila> PROPOSED: That Re-use vocabularies be retained but the term vocabulary should be defined as a set of attributes
<Makx> +1
<yaso> +1
<laufer> +1
+1
<phila> +1
<annette_g> +1
<Gisele> +1
<newtoncalegari> +1
<deirdrelee> +1
<antoine> 0
<Seiji> +1
<Sumit_Purohit> +1
antoine: I have been though this
once
... if the group feels this should be there I am not opposing this
<Makx> Current text in intro says "According to W3C, vocabularies define the concepts and relationships (also referred to as “terms”) ..."
antoine: I am just warning it is not easy to do it
<Makx> Let's add (... "terms" or "attributes")
antoine: this section has 4 paragraphs trying to describe what vocab is
<phila> yaso: You're saying it will be difficult to re-write that BP. I wrote those 4 paragraphs introducing the section. It took several weeks - it's not easy
<Makx> +q
<ericstephan> +1 Makx
yaso: I was going to propose a extention of this definition
BernadetteLoscio: I don't know if we can define a vocab as a set of atributes
<RiccardoAlbertoni> +1 to Makx's proposal to add (... "terms" or "attributes") into "According to W3C, vocabularies define the concepts and relationships (also referred to as “terms”) ..."
BernadetteLoscio: Makx do you agree with the definition we have now?
Makx: on the first paragraph it could be add to refer as terms or atributes
<phila> Makx: Rather than terms, refer to terms and attributes
<phila> Draft 3 - - That Re-use vocabularies be retained but that it should refer to 'terms or attributes' to broaden the acceptance beyond the LD community
antoine: if the proposal is that only adding attributes I am fine with it
<antoine> +1
<Makx> +1
<RiccardoAlbertoni> +1
<laufer> +1
<phila> antoine: Happy if we're talking about adding a few words rather than rewriting
<adrianov> +1
<phila> PROPOSED: That Re-use vocabularies be retained but that it should refer to 'terms or attributes' to broaden the acceptance beyond the LD community
<yaso> +1
<antoine> +1
<deirdrelee> +1
<RiccardoAlbertoni> +1
<annette_g> +1
<phila> +1
<ericstephan> +1
<laufer> +1
<Seiji> +1
<BernadetteLoscio> +1
<newtoncalegari> +1
<Giancarlo_Guizzardi> +1
+1
<phila> RESOLVED: That Re-use vocabularies be retained but that it should refer to 'terms or attributes' to broaden the acceptance beyond the LD community
<phila> PROPOSED: That Choose the right formalization level be reviewed
<deirdrelee> +1
<yaso> +1
<annette_g> +1
<BernadetteLoscio> +1
<Gisele> +1
<laufer> +1
<phila> +1
<RiccardoAlbertoni> +1
<Makx> +1
<phila> RESOLVED: That Choose the right formalization level be reviewed
<deirdrelee> close issue-166
<trackbot> Closed issue-166.
<phila> close issue-166
<trackbot> Closed issue-166.
<yaso> o/
<phila> Bernadette is happy!
<Sumit_Purohit> OK....
<yaso> we can return in 5 minutes!!
<deirdrelee> 5 minute break (tea has arrived!)
<ericstephan> back from coffee run
<Sumit_Purohit> No one wants to come back from tea ??? :-)
<yaso>
<deirdrelee> issue-145
<trackbot> issue-145 -- It makes sense to have a BP "Use unique identifiers"? -- open
<trackbot>
<deirdrelee> issue-163
<trackbot> issue-163 -- Should the bp document refer to uris or identifiers -- open
<trackbot>
<deirdrelee> issue-194
<trackbot> issue-194 -- Data Identification -- open
<trackbot>
<annette_g> * what one are we on? *
<deirdrelee> all three annette_g
<AdrianoCesar-InWeb> BernadetteLos
<deirdrelee> grouped together under agenda
<newtoncalegari> BernadetteLoscio: the issues on the agenda are grouped by topic
<deirdrelee> all issues about identification
<deirdrelee> BartvanLeeuwen: let's look at all three together
<deirdrelee> ... lots of discussion on mailing list around uris
<AdrianoCesar-InWeb> BernadetteLoscio: next one BP 194
<deirdrelee> s/bartvanleeuwen/bernadetteloscio
<AdrianoCesar-InWeb> BernadetteLoscio: about data identification section, talking about some messages (33) about this topic
<AdrianoCesar-InWeb> BernadetteLoscio: is this issue still opened?
<AdrianoCesar-InWeb> BernadetteLoscio: ask Annette about her opinion
<yaso>
<AdrianoCesar-InWeb> annette_g: the first one is solved (145)
<deirdrelee> close issue-145
<trackbot> Closed issue-145.
<yaso>
<deirdrelee> close issue-163
<trackbot> Closed issue-163.
<yaso>
<AdrianoCesar-InWeb> yaso: 194 is about limiting this section to information that applies to publishing *data*
<phila> PROPOSED: That the BP document will use the term 'URI' throughout
<Makx> +1
<Makx> +1 to annette
<AdrianoCesar-InWeb> deirdrelee: decision is to use URI or not? Let´s clarify it
<phila> PROPOSED: That the BP document will use the term 'URI' throughout, unless there is a clear reason to use a differfnet term (URL, IRI etc.)
<ericstephan> +1 to consistent and intentional use of uri
<yaso> +1
<phila> PROPOSED: That the BP document will use the term 'URI' throughout, unless there is a clear reason to use a different term (URL, IRI etc.)
<annette_g> +1
<Sumit_Purohit> +1
<yaso> +1
<RiccardoAlbertoni> +1 to phila about keeping the information
<AdrianoCesar-InWeb> BernadetteLoscio: include the description of the terms and other point is to use this terms in the document
<AdrianoCesar-InWeb> phila: it is important to have definitions informed in the document
<Makx> -1 to Phil
<annette_g> -1
<Makx> +1 to Ivan
<Makx> Let's not go there
<phila> +1 makx, let's not
<phila> PROPOSED: That the BP document will use the term 'URI' throughout, unless there is a clear reason to use a different term (URL, IRI etc.)
<annette_g> +1
<Makx> +1
<antoine> +1
<laufer> +1
<Sumit_Purohit> +1
<BartvanLeeuwen> +1
<annette_g> * I keep seeing URI *
<ericstephan> +1
+1
<annette_g> * in W3C space *
<annette_g> -1 to IRI
<scribe> scribe: Caroline
annette_g: using countries specific IRIs I don't think is a BP to include that
phila: it is better to use URI considering data
annette_g: I think is a BP of everything on the Web
<Sumit_Purohit> +q
annette_g: I want to keep it as data
phila: We can stick as URI
... a lot of people will ready any say "you mean URL"
<scribe> scribe: AdrianoCesar-InWeb
<Makx> I second Annette and I am not American
<newtoncalegari>ãopaulo.gov.br/example/dataset
<newtoncalegari>
newtoncalegari: give an example of saopaulo.gov.br, the idea is to use an international format
<deirdrelee> sa0pa0l0.gov.br
<phila> +1 to the security issue
<phila> +1 _ I can't write Sao Paulo properly and easily without copying and pasting from somewhere else
phila: W3C suggests to use international format, avoid to use special characters
<newtoncalegari> +1 deirdree
<yaso> +1 to deirdrelee
annette_g: this is important for everything on the Web, not only for data
<Sumit_Purohit> +1 deirdrelee
<yaso> +1 to newtoncalegari proposal
newtoncalegari: it is important to justify the need to suggest this
<annette_g> in a tiny little footnote
<Makx> Let's just keep the intro of section 9.7 as it is.
<newtoncalegari> newton: we can use URI and warn about the security issue. what do you think?
laufer: We are recommending to use URI?
<newtoncalegari> maybe we should recommend to avoid using special characters
+1 to newtoncalegari
<Sumit_Purohit> need to leave for a meeting..Will be back.
<newtoncalegari> annette_g, not using special characters we tend to avoid some security issues, right?
<annette_g> right
<yaso> +1 to newton
<yaso> annette_g is not happy with the definition
<phila> PROPOSED: That the definitions of URI, URL and IRI be removed from the draft section 9.7
annette_g: propose to describe this definition
<phila> Other proposal is to use the term URI throughout
BernadetteLoscio: we can record that the group agree to use URIs
<phila> +1 not to discuss this any more
<phila> annette_g: This is about our own writing, not what other people should do
<yaso> PROPOSED: That the BP document will use the term 'URI' throughout
<phila> PROPOSED: That the definitions of URI, URL and IRI be removed from the draft section 9.7
<newtoncalegari> -1
<Makx> keep the second part
BernadetteLoscio: proposing to rewrite the introduction of the section
<annette_g> PROPOSED: That the definitions of URI, URL and IRI be removed from the draft section 9.7
Caroline: suggest to explain the definitions, but to explain all definitions
<yaso> sorry, annette_g
<yaso> speak slowly, please!
<phila> annette_g: Says this is as crazy as including a definition of antidisestablishmentarianism because we think it's cool
annette_g: there is no reason to define if we are not going to discuss in the document
<laufer> +1 to phil proposal
<annette_g> maybe we need to decide first whether we are going to include anything about identifiers
<yaso> +1 to newtoncalegari
newtoncalegari: someone is
reading the document to learn, as a W3C document we need to
inform the difference between URI, URL etc
... therefore prefer to keep this in the document
phila: I desagree with that because the definition can generate more discussion, since there is no clear definition about these terms
<Seiji> +1 to phil
<BartvanLeeuwen> +1 to phil
<annette_g> +1 to phil
<laufer> completely agree +1
+1 to phil
<newtoncalegari> +1 for that proposal
<phila> PROPOSED: That the definitions of URI, URL and IRI be removed from the draft section 9.7
<yaso> +1 to phil
<newtoncalegari> +1
<yaso> +1
<antoine> +1
<Caroline> +1
<Makx> +1
<BernadetteLoscio> +1
<phila> +1
<laufer> +1
<Seiji> +1
<Gisele> +1
<adrianov> +1
<RiccardoAlbertoni> +1
<phila> RESOLVED: That the definitions of URI, URL and IRI be removed from the draft section 9.7
yaso: next item
<phila> PROPOSED: That the BP document will use the term 'URI' throughout, unless there is a clear reason to use a different term (URL, IRI etc.)
<phila> +1
<yaso> +1
<annette_g> +1
<newtoncalegari> +1
<BernadetteLoscio> +1
<BartvanLeeuwen> +1
<deirdrelee> +1
<RiccardoAlbertoni> +1
<Seiji> 0
<Gisele> +1
<Caroline> +1
<Makx> +1
<yaso> -q
<laufer> +1 (to define what is a clear reason)
<ericstephan> +1
<phila> RESOLVED: That the BP document will use the term 'URI' throughout, unless there is a clear reason to use a different term (URL, IRI etc.)
<phila> annette_g: What's there now is not specific about data on the Web, it's about anything on the Web
phila: there is a confussion about what each of these terms represent...
<yaso> +1 to phila
<phila> annette_g: It's the bulletted list I object to
<phila> phila: It's gone
<phila> annette_g: You can't put something on the web without using a URI so it's pointless saying that you need to give datasets a URI
<annette_g> PROPOSED: that the best practice about identifiers be rewritten to address issues when posting data on the web.
<Zakim> phila, you wanted to try and squatre this circle
<phila> some draft text - When any resource is put on the Web, it has a URI. Many URIs are generated automatically but when sharing data, it is useful to bear in mind the following factors
<yaso> +1 to phil
<deirdrelee>
<phila>
<newtoncalegari> "So what should I do? Designing URIs"
laufer: if an information does not have an URI, then it is not on the Web...
yaso: proposing to try to finish the discussion about this issue
BernadetteLoscio: we are going to
use URI as identifier, ok? Yes
... now we are discussing the best practice, is a different issue, right?
yaso: suggest to annette_g to describe this issue about the best practice...
annette_g: I can try it, describing this issue
<ericstephan> +1 phila
<phila> ACTION: phila to take another run at the BP Use persistent URIs as identifiers [recorded in]
<trackbot> Created ACTION-204 - Take another run at the bp use persistent uris as identifiers [on Phil Archer - due 2015-10-01].
BernadetteLoscio: we can close the 3 open issues... ok
<phila> close issue-145
<trackbot> Closed issue-145.
<phila> close issue-163
<trackbot> Closed issue-163.
<yaso>
<phila> close issue-194
<trackbot> Closed issue-194.
yaso: next topic - Discuss the versioning section and resolve open issues (30 min.)
<yaso> ISSUE-193
<trackbot> ISSUE-193 -- Data Versioning -- open
<trackbot>
BernadetteLoscio: in the last Draft (last F2F) we discuss about data versioning...
there was a diagram and we had discussed by email about this... about the meaning of a versioning
We agree that time series is not a case of versioning...
We try to explain better the meaning for versioning for this document
<yaso>
<BernadetteLoscio>
<phila>
BernadetteLoscio: annette_g, do
you agree with this proposal? Look in agenda, item 193
... one thing is our definition of data versioning
<phila> s/
<Caroline>
<phila>
<Caroline>
<BernadetteLoscio>
<yaso> close issue-193
<trackbot> Closed issue-193.
yaso: is it ok to close this issue (193)?
<ericstephan> I have to leave in 20 minutes unfortunately...
<Makx> I need to leave in 20 minutes, dinner time
<RiccardoAlbertoni> I am going to stay only for 10/20 minutes
<Seiji> need to leave
<yaso> so we are going for more 20 min
<Caroline> scribe: WagnerMeiraJr
<phila> issue-168?
<trackbot> issue-168 -- Dataset versioning -- open
<trackbot>
yaso: Going to issue 168. Newton, can you start?
newtoncalegari: I was working on this issue in the 1st part of the meeting: which vocabulary to use in versioning?
BernadetteLoscio: I'd like to know what is the suggestion for using when defining versions?
yaso: Any other suggestions?
phila: We cannot make a normative dependency. It is one possible way, but I do not want to do it.
BernadetteLoscio: It is just to give an example.
<annette_g> link?
yaso: I think that it is ok to use for sake of an example section.
<antoine> +1 to use Memento as a (quite different) alternative to PAV
newtoncalegari: There is an issue (3), the beginning of data version that motivates it.
yaso: Seems ok to me.
BernadetteLoscio: It is not just because it is an open issue that it is worth doing it. We will close issues 92 and 68. What's the opinion of the group regarding changes in the data. It is not clear whether updating the schema is a new version or not. Does this new attribute justify a new version?
<newtoncalegari> q
antoine: Not sure I understood the point.
<annette_g> +1 to letting the publisher decide
antoine: In the case you mentioned it does not sound to me it is the case to create a new version.
BernadetteLoscio: Sometimes the published does not know whether it is the case of creating a new version.
antoine: Let the publisher decide.
Giancarlo_Guizzardi: If we use the vocab and onto, there could be changes in them that do not change the semantics, but if the latter change, it should be anew evrsion.
Seiji: Same comment of Giancarlo_Guizzardi
<Zakim> phila, you wanted to say we shouldn't define when a new version is a new version
BernadetteLoscio: The publisher may decide, but we at least sign about it.
phila: When does something change enough? It is such a difficult question.
<Makx> yes, it's a can of worms
BernadetteLoscio: We tried to
define based on the discussions.
... We should give some guidance to the publisher. If the definition is not good enough, we should not do it.
<phila> Mind you, I like the text in
<Makx> +q
laufer: The term version is used with several meanings. It also varies depending on the language. We need a way to talk about relations among datasets. People saying that one thing is a version of other is not just because it is a change, they may be in completely different languages.
BernadetteLoscio: There is a
confusion among several terms that are used differently:
version, distribution etc
... A time series is not a new version of a dataset. We are trying to define and let the publisher to decide.
... This new dataset is derived or is a version of other dataset. If the publisher does not know what is a version how come he will decide what to do.
annette_g: A language is not
version specific. We may need to perform the same change in
several languages at once.
... If you make a change in a dataset, you may create a new version depending on the publisher.
... It is sort of a editorial work to make a change and evaluate how different it is.
laufer: I'm not saying that different languages are different versions. We have to define our concept of version.
antoine: Imagine your updates are
not used by the dataset in question, then it does not produce a
new version of the dataset.
... What are the principles we want to follow when discussing versions? Should we discuss these?
... Versioning means that you change something that affects your dataset.
Makx: It is very hard to define
what a version is for a particular person.
... They should not throw away old data upon a new version. People may be using it.
phila: Agree with Makx . I like the text and want to add: we can't antecipate everything and tell when a new version makes sense. I would encourage consistency. It may be every six weeks, publishing a new version.
<Makx> +1 to Phil
phila: They may decide and stick to it.
Giancarlo_Guizzardi: I agree that it is useful to give guidelines, including handling deprecated content and vocab changes. I agree that defining it is very interesting. But it is extremely hard. We tried recently to characterize versions for software and it is hard.
<Makx> We discussed this for a long time for the DCAT-AP in Europe and could not resolve it ;-(
laufer: I don't know whether it is feasible, but you may encourage the publisher to define what is a version.
<Makx> We were hoping that DWBP could give guidance ;-)
<ericstephan> Talk to you tomorrow everyone. Sorry to take off in the middle of discussion.
BernadetteLoscio: It is interesting and I agree that it is hard to define and I was trying to write about. I'm going to rewrite it considering our discussion here, towards help the publisher to decide. I'll rewrite the introduction and ask for feedback.
<BernadetteLoscio> bye bye Eric!
newtoncalegari: How to version
data stream?
... DCAT uses dcterms:modified.
... A change in data stream will be treated as such just when the schema changes.
<annette_g> 2 separate issue
<annette_g> issues
<Makx> Even that is not agreed by everyone, Deirdre
deirdrelee: Just when the API changes?
<Makx> Apologies, I have to sign off. Will be back tomorrow.
BernadetteLoscio: Newton's concern is that you have a stream and there should not be a new version.
<deirdrelee> deirdrelee: if the API changes it doesn't matter, because an API is related to data access, not data structure or content
<BernadetteLoscio> bye bye Makx!!!
annette_g: API related versioning is really hard to define.
newtoncalegari: Don't we need to worry to track changes in data streams?
yaso: It does not seem to be necessary.
<yaso>
yaso: We were discussing 192.
newtoncalegari: We are not going to recommend and we may close the issue.
<yaso> close issue-192
<trackbot> Closed issue-192.
newtoncalegari: We have no examples.
<phila> There is an alternative to PAV at but I prefer PAV which is better developed
<yaso> close ISSUE-168
<trackbot> Closed ISSUE-168.
yaso: It looks like we are done
for today.
... Thanks everyone.
<annette_g> I won't be on until 6 PT
<annette_g> which is 10
<phila> Thanks everyone. Good night/good afternoon
<yaso> neither us, annette_g
deirdrelee: Is it fine to start at 8AM Sao Paulo.
<yaso> so tomorrow is 8:00 am
<laufer> bye annette... good lunch...
yaso: We will start at 8:00 AM.
<annette_g> bye!
<RiccardoAlbertoni> Enjoy your staying in sao paolo.. thanks for the interesting discussions , bye
<laufer> bye all...
<yaso> Thanks, RiccardoAlbertoni and annette_g and others attending remote :-) | http://www.w3.org/2015/09/24-dwbp-minutes.html | CC-MAIN-2018-39 | refinedweb | 13,860 | 58.82 |
Yes, this is a homework problem, but I have already submitted it for a grade, so please don't think I am trying to get you to complete it for me. So, now I am really just trying to learn what I should have done so that I will be able to fix this problem in the future, as I have LabView, Microcontrollers, and VeriLog coming up.
I have a loop that gets the a set of data points. It seems to work fine if I use a for loop, however, I need the loop to continue until the user enters zero (0) for the time input. So, I changed from a for loop to a Do... while loop. I am thinking that the problem is in the loop since that is all that changed, but I am new to using the structures and pointers as well, so my mistake could be located else where.
The commented out sections are a part of my trying to troubleshoot the error. I don't get any data from the Do... While Loop, which makes me think it might be a pointer or structure problem. Again, we just covered structures and pointers in class, so I am new to them.
Thanks for any help that you can offer.
Code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
double f(double x);
double monteCarlo(double a, double b, double yMin, double yMax, int trials);
double expectedDoubles(void);
double randDouble(double min, double max);
struct Data {
float time;
float accel;
};
void printItem(struct Data pi);
const int MAX = 100;
struct Data points[MAX];
void main(int argc, char* argv[])
{
int count;
int i = 0;
double v;
int steps = 10000;
int a, b, yMin, yMax;
//printf("How many items? ");
//scanf("%d", &count);
////Enter in the data, Time = 0 means quit
printf("Enter in all data, time = 0 to quit.\n");
count = 0;
do {
printf("Time? ");
scanf("%f", &points[i].time);
printf("Accel? ");
scanf("%f", &points[i].accel);
++count;
} while (points[i].time != 0);
//for (i = 0; i < count; ++i) {
// printf("Time? ");
// scanf("%f", &points[i].time);
// printf("Accel? ");
// scanf("%f", &points[i].accel);
//}
//Print out the data points
/*printf("\n\nPrinting Data Points\n");
for (i = 0; i < count; ++i) {
printItem(points[i]);*/
//}
//Find a,b,yMin,yMax ==> Starting data point is assumed to be 0,0
a = 0;
b = points[0].time;
yMin = 0;
yMax = points[0].accel;
for (i = 1; i < count; ++i) {
if(points[i].time > b){
b = points[i].time;
}
if(points[i].accel > yMax){
yMax = points[i].accel;
}
}
//Print resulting Velocity
//Data check
/*printf("%d, %d, %d, %d\n",a,b,yMin,yMax);*/
v = monteCarlo(a, b, yMin, yMax, steps);
printf("Velocity = %.3f [m/s]\n", v);
getchar();
getchar();
}
void printItem(struct Data dp) {
printf("Time: %.2f\n", dp.time);
printf("Accel: %.2f\n", dp.accel);
printf("\n\n");
}
double f(double x) { //function to be integrated
double v;
//Vf = V0 + a * t
v = 0 + x; //v0 starts at 0 according to the problem & at is replaced by x here
return v;
}
double monteCarlo(double a, double b, double yMin, double yMax, int trials) {
double boundryArea = (b - a) * (yMax - yMin);
int trial;
double randX, randY;
int hits = 0;
srand(time(0));
for (trial = 0; trial < trials; ++trial) {
randX = randDouble(a, b);
randY = randDouble(yMin, yMax);
if (f(randX) >= 0 && randX >= 0 && randY < f(randX)) {
++hits;
} else if (f(randX) < 0 && randY < 0 && randY > f(randX)) {
++hits;
}
}
return (hits / (double) trials) * boundryArea;
}
double randDouble(double min, double max) {
double r = rand() / (double) (RAND_MAX + 1);
return r * (max - min) + min;
}
double expectedDoubles(void) {
const int TRIALS = 10000;
int trial;
int die1;
int die2;
int rolls;
int totalRolls = 0;
for (trial = 0; trial < TRIALS; ++trial) {
rolls = 0;
do {
die1 = rand() % 6 + 1;
die2 = rand() % 6 + 1;
++rolls;
} while (die1 != die2);
totalRolls += rolls;
}
return (double)totalRolls / TRIALS;
} | http://cboard.cprogramming.com/c-programming/147253-do-while-loop-problem-printable-thread.html | CC-MAIN-2015-27 | refinedweb | 646 | 68.91 |
#include <hallo.h> * Hunter Peress [Mon, Dec 30 2002, 06:18:03AM]: > > Has anyone got some real-world evidence that this makes a difference? > > I'm thinking about things like how many pages/second an Apache server + ... > Next, there has been talk about this in the debian community before. I > googled, and here are some results: Nice googling, but WHERE IS THE EVIDENCE? You just follow the dreams of others and waste lots of time fighting for worthles targets. > To this second argument, I will give a response: who the hell makes you > think that every mirror has to take on i686??? A few servers would start > out serving this i686 distro, and it would be evident that these are in Sure. Find someone to provide the bandwith, who forbids you to do so? > great demand, and hence more i386 mirrors can switch over until the > demand is met. (See , its a > document that addresses policy/practice on this issue). As said, that is you personal joy, we have a consens - creating a whole optimised FTP pool does not make sence, only optimisation of particular show makers (crypto and science stuff). > So SOMEONE PLEASE step out there and start working on an i686 distro. It > will take a minimal time to port. And it will progress THE WORLD!!! GO AND MAKE IT! Who does not let you make the first step? Just setup a hacked sbuild or pbuilder system, which gets latest package versions from unstable, adds "+686" to every version number and rebuilds it. Stop talking. Begin with the real work. You could just hack the gcc package to provide the wrapper script for gcc-3.2+optimised-flags. You could setup a mini-policy about how to cooperate with package maintainers to inherit optimisation settings in their package from somewhere from the build-environment. I fail to see anything impossible. So go ahead, cooperate with other fanatics and implement it. Otherwise, shut up and stop bithing and asking US to provide expensive implementations of crazy ideas. Gruss/Regards, Eduard. -- "I think Debian's doing something wrong, `apt-get install pesticide', doesn't seem to remove the bugs on my system!" -- Mike Dresser | https://lists.debian.org/debian-devel/2002/12/msg01750.html | CC-MAIN-2019-22 | refinedweb | 364 | 73.68 |
Lectures on GUI and Swing, May 2011
Chris Johnson, Alexei Khorev
Nowadays, all computer programmes which are intended for interaction with the human user are created with Graphical User Interface (while "In the Beginning was Command Line", by Neal Stephenson). According to Wiki: "allows for interaction with a computer or other media formats which employs graphical images, widgets, along with text to represent the information and actions available to a user. The actions are usually performed through direct manipulation of the graphical elements." The history of GUI development so far is very worth reading. Since standard computers have a well defined and constrained (less constrained now, after introduction of iPhone and iPad) interface, the type of GUI which can be deployed on them is often called WIMP (window, icon, menu, pointing device).
One of the very first GUI as it was created by Xerox 6085 ("Daybreak") workstation in
1985. ⇒
Java had the facility to create Graphical User Interface for its programs as the part of the standard library from the very beginning. Originally, the package which contained necessary resources was Abstract Window Toolkit. A little later its drawing capabilities were extended by the Java2D API. Then (in Java 1.2) came Swing. Most Swing components are pure Java components or so-called lightweight components. That is, they are written completely in Java. AWT components are implemented natively on each different platform that supports Java. Somewhere deep down in the implementation, there is a bridge to the system's native graphics routines. Obviously this is different on Linux, Windows, Macintosh etc. As a result, these heavyweight components look different on different platforms.
However, as we shall see, even in a simple example of GUI program, the behaviour can exhibit subtle platform-specific differences (MouseSpy.java)
Swing is only one (though very large) package from the Java Foundation Classes, a metapackage used for building GUI and adding rich graphics functionality and interactivity to Java applications. The JFC content:
Unfortunately many of the Java GUI classes have very large and confusing interfaces so that it can be hard to figure out what are the useful bits and what parts you can safely ignore (unlike with standard non-GUI interfaces). The Swing (and AWT) usage requires time for learning and experimenting, detailed tutorials and documentation. The Java Tutorial contains two sections on using Swing, one in the main trail, basic introduction, and one more advances, with many example of how to use Swing classes to fulfil major GUI programming tasks (creating windows, labels, widgets, text fields etc).
Java Swing (backed up by AWT) provides a rich set of GUI features including pluggable look and feel (plafs), shortcut keys, tool tips, support for assisting technologies and for localisation (or internationalisation). We won't have time to cover anything like all of it, but we'll do enough to get you started writing realistic graphical user interfaces. If time permits, we will demonstrate the usage of plaf, when the GUI appearance can be changed during run-time.
Swing isn't the only GUI library around. There is a smaller suite of widgets called Standard Widget Toolkit, which comes with the Eclipse platform (SWT and JFace are main GUI software components used in Eclipse). It's also free, and there are good on-line tutorials and the book about SWT ("SWT/JFace in Action" by M. Scarpino et al, Manning, 2005). Some believe that SWT is a better alternative to Swing, other countenance this with "So WhaT"? (Valid point after serious performance and design improvements of Swing in Java 1.6.) Another framework is QtJambi from (former Trolltech) Nokia — the makers of excellent Qt C++ GUI framework.
GUI applications have important differences:
Type of events:
Polling (old, single-threaded)
Callbacks (modern, multi-threaded)
Widgets are ready-made low-level (and not-so-low-level) components provided by the underlying library (e.g. Motif, MFC, GTK+, Java's AWT and Swing etc).
Examples of widgets include (the Java Tutorial contains a far more detailed description of the Swing controls and examples of their use):
Our first example include creating a simple graphical layout and simple event handling (for complimentary study — look into the Swing Tutorial starting with Getting Started with Swing).
The one class program we consider here is
MouseSpy.java, which is converted
from
an applet code from The Big java book. The program puts a window on the screen and
then catches all relevant mouse events and prints information about them on the standard output
(
System.out). We start with import declarations:
import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.*; import java.awt.event.*;
Every class in the GUI part of your application must import all necessary classes and static methods from the relevant packages. Do not import everything (using the wildcard "*"), many Swing classes are very large.
What follows next is implementation of the MouseListener interface. Many (most) widgets in Swing can be used to pass data from the user to the application. This done via the mechanism of registering and responding to an event, which user (or some other agent) generates by interacting with the widget. Different types of widgets can react to a specified type of events, which are declared in a related listener interface. The GUI code must implement all required interfaces for the application to handle the required events.
public class MouseSpy implements MouseListener { public void mousePressed(MouseEvent e) { System.out.println("Mouse pressed at (" + e.getX() + ", " + e.getY() + ")"); } public void mouseReleased(MouseEvent e) { System.out.println("Mouse released at (" + e.getX() + ", " + e.getY() + ")"); } public void mouseClicked(MouseEvent e) { System.out.println("Mouse clicked at (" + e.getX() + ", " + e.getY() + ")"); } public void mouseEntered(MouseEvent e) { System.out.println("Mouse entered at (" + e.getX() + ", " + e.getY() + ")"); } public void mouseExited(MouseEvent e) { System.out.println("Mouse exited at (" + e.getX() + ", " + e.getY() + ")"); } public static void main(String[] args) { ..... }
In the particular (very simple) case, the main application class itself implements the MouseListener interface, which will be registering five different events (declared by five methods in the interface), generated by the mouse input device. The complete list, description and example of usage of all major listeners in Swing is to be found in Listener API Table section of the Java Tutorial.
The listener methods define what actions take place as the result of event occurrence. Here, our only actions are printing some information on System.out stream. The MouseEvent has data like coordinates where it's happened. They can be established and (possibly) used. Apart from knowing its own coordinates, the event (MouseEvent, to be specific) can maintain the click count, characterise the type of component on which it occurred, and so on (the Java API java.awt.event documentation contains full nomenclature of what you can extract from an event).
main()
public static void main(String[] args) { JFrame frame = new JFrame(); MouseSpy listener = new MouseSpy(); frame.addMouseListener(listener); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello world"); JPanel panel = new JPanel(); panel.setPreferredSize(new Dimension(300, 300)); panel.add(label); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); }
Let's go through it like we did with HelloWorld.java in the very beginning.
JFrame frame = new JFrame(); // creates an application main window
Frames know how to display themselves and their contents, how to minimise, maximise, move and change size. In the Swing Tutorial they are described in How to make frames (main windows).
MouseSpy listener = new MouseSpy(); // creates an event listener to monitor mouse events frame.addMouseListener(listener); // attaches the listener to the frame (fixes geometrical area of events)
This code connects the listener with the GUI component (widget) it's listening for events on. In this case we're listening for events on the main window, but it can be any component. Later we'll see buttons: there you attach the listener to the button, a different listener for each button (usually, like in menu items). The relevant part of the Swing Tutorial is Writing event listeners.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This statement tells the program what to do if the user closes the window (by clicking in the little X in one of the top corners usually, although the details of the appearance of the window and its decorations depends on the system and the window manager). Here we're saying that closing this window should quit the application. There are other possibilities: check the javadoc documentation for class JFrame for more.
JLabel label = new JLabel("Hello world");
This creates a label, which is a simple widget that can display a bit of text or an image, or both. This one just displays text. The constructor we've called sets the text of the label to the string “Hello world”. For more about labels, see How to use labels in the Swing Tutorial.
JPanel panel = new JPanel();
Another object creation. A panel is a container that you can pack other widgets into. We probably don't really need one here, but it helps with the next step. For more about panels, see How to use panels in the Swing Tutorial.
panel.setPreferredSize(new Dimension(300, 300));
This sets the preferred starting size of the panel. You can also tell a frame what size it should be, but this doesn't always have any effect. Try modifying the program to see. Anything that inherits from class java.awt.Component (including class JFrame and class JPanel) has a method setSize() that can take two integers or one Dimension object. Anything that inherits from class javax.swing.JComponent (including class JPanel) also has a setPreferredSize() method, but this only accepts a Dimension object.
Sometimes setting the size of a widget works as expected, sometimes it doesn't. There's probably good design rationale for that, but damn be the user who must scour the documentation for literally thousands of classes. This is one of the hardest things about GUI programming. A good beginner's strategy for getting around it is to reuse chunks of code from other programs that work. Eventually you will want to understand everything you're doing, but initially you need to have some small successes, and reusing a few lines that work is a good way of getting that.
panel.add(label);
This puts the label inside the panel. This hides a detail: whenever you put widgets inside a Container (such as a JPanel) the way they are arranged is controlled by a Layout Manager. If you don't specify, then the default is what's called a Flow Layout, which means that components are packed in from left to right, top to bottom. This usually isn't what you really want. Later we'll see examples of some other layout managers: border layout and grid layout. For more about layout managers, see Laying out components within a container in the Swing Tutorial.
frame.setContentPane(panel); // (1) frame.pack(); // (2) frame.setVisible(true); // (3)
The first makes the panel be the main display area of the frame (the “content pane”). Frames also have separate, specially defined areas at the top for menus and at the bottom for status bars or elsewhere. The second one is when the actual sizes and positions of everything in the window gets worked out. If you change the contents of a container and don't do this, the appearance doesn't change, which can lead to a lot of frustration. So if something isn't working, try repacking the frame and see if that fixes it. Lastly, the third instruction is needed because initially, when created, the frame is invisible. This is so that users don't see the messy process of adding components to the frame. Once everything has been put together and packed, you make the whole "concoction" visible as the last step.
The general strategy of writing a GUI (View) part of the application can now be formulated as follows:
Create the widget. Depending on what type it is, you may want to pack it into a container, or pack other widgets inside it or whatever. Then display it on the screen.
Create a ‘listener’ object to receive the event. This object must implement a listener interface (or extend one of the pre-supplied do-nothing adapter listener classes) from the package javax.swing.event or java.awt.event (usually the latter). You can create an object of a special class written just for this purpose, or you can add this capability to an existing object by adding extra code to its class.
Connect this listener with the GUI component (widget) it's listening for events on. In this case we're listening for events on the main window, but it can be pretty much any component. Later we'll see buttons: there you attach the listener to the button — either its own listener for each button, or one listener to many buttons (or any widget which reacts to an ActionEvent).
Write the code that must be executed when the event takes place. This must be in a special method specified by the listener interface. In most cases (where the listener is an ActionListener) this is just called actionPerformed(), but in the case of our mouse listener, there are several methods we have to implement, one for each different type of mouse event: down, up, click, enter and exit.
For more detailed and definitive information on this, see Handling events in the Swing Tutorial. For the full detail, see Writing event listeners in the Swing Tutorial.
In this example, we have a separation of the Model part from the rest
of the program,
Counter.java.
class Counter { private int count; public Counter() { this.reset(); } public void reset() { this.count = 0; } public void increment() { this.count++; } public int getCount() { return this.count; } }
It can be used by any client, eg by
TestCounter.java which is run on the
command line.
We want to use Counter in the "baby-GUI" application. Our first version, counter1, is the following:
/** This class is not a listener (as in MouseSpy), it's a JFrame */ class CounterApplication extends JFrame { Counter counter; // gives access to Model's data and logic JLabel label; // GUI parts can be private if they are not used by outsiders JButton incrementButton, resetButton; // two button widgets public CounterApplication() { // constructor counter = new Counter(); label = new JLabel("" + counter.getCount(), SwingConstants.CENTER); // label is created and positioned incrementButton = new JButton("Increment"); // buttons created with names resetButton = new JButton("Reset"); Container container = this.getContentPane(); // container to lay out buttons in the main window container.setLayout(new GridLayout(3, 1)); // type of layout can be different, GridLayout is chosen container.add(label); // label is added (it'll go on top) container.add(incrementButton); // first button is added (under the label) container.add(resetButton); // second button (at the bottom) ... ...
Greater details from the Swing Tutorial:
Moving on,
... ... class IncrementButtonHandler implements ActionListener { public void actionPerformed(ActionEvent event){ // the method implemented counter.increment(); // calling the model's method update(); // repaints the frame (defined below in the code) } } ... ...
A class within a class — an inner class. This is a new java construct which we hardly met before. It's a full Java class that just happens to be defined right in the middle of another class. When the Java compiler compiles this, it produces a separate .class file CounterApplication$1IncrementButtonHandler.class for this class. They are especially useful for GUI event programming. The inner class “knows” about all the local variables and fields that are in scope at this point, which saves quite a few lines of code.
This inner class has a name (which they don't all have to have). In this form it's the closest to what it would be like if it was in a separate file. We'll see some examples of other ways to use inner classes in other versions of Counter.
What does this inner class do? It's an action listener: a listener that reacts on event occurrence by taking an appropriate action. For a button, the action is that it is clicked on. It turns out that for most GUI components, the listener you need is an action listener, which is pretty much the simplest sort of listener. It only has one method you have to implement: actionPerformed() (MouseListner had five). Here when the user clicks on the increment button, we want to increment the counter and then update the display.
... ... IncrementButtonHandler ibh = new IncrementButtonHandler(); incrementButton.addActionListener(ibh); // repeating the same stuff for the reset button class ResetButtonHandler implements ActionListener { public void actionPerformed(ActionEvent event){ counter.reset(); this.update(); } } ResetButtonHandler rbh = new ResetButtonHandler(); resetButton.addActionListener(rbh); this.setSize(150, 450); // setting the size of the frame this.setVisible(true); // making the frame visible } // the frame constractor ends public void update() { // updating the display by using the current value from Model label.setText("" + counter.getCount()); repaint(); }
There was no call to pack() — you need to call it with some layout
managers, not others. You need it for border layout and flow layout, but apparently not for
grid layout. If you want to know the details, look it up in
Laying
Out Components Within a Container in the Swing Tutorial. After that, you need to call
repaint() on a component when the application's
internal state has changed and it needs to be redrawn to reflect that change.
Finally, the main:
... ... /* the main method */ public static void main(String[] args){ // creating the frame and the model CounterApplication app = new CounterApplication(); // seen it before (could be placed in the constructor) app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
Compiling, running,... there!:
Note: here the applet version of the Counter application
version was meant to be displayed. But the latest (and the last) "upgrade" for JRE from
Apple
has introduced a bug which prevents correct simultaneous run of a Java Script and a Java applet
(perhaps, it is a good thing that Apple will not support Java anymore). To run the applet,
go to the examples directory, and the applet
appletviewer CounterApplet.html.
In a modified version (from counter4), a title was added to the main window, and also a menu bar with two menus and mnemonics (keyboard shortcuts). Adding the title is just one line:
setTitle("Counter Application");
Adding the menus is a little more work. Here are the basic steps:
Create a JMenuBar and link it to the window
Create one or more JMenu objects and add them to the menu bar
Create one or more JMenuItem objects and add them to the menus
Write an action listener class for each menu item, with the appropriate action coded into its actionPerformed() method
Create a listener object for each menu item
Link each action listener to its menu item
For menus and menu items, you can set the keyboard shortcut with setMnemonic(). Once you've done this, you can use the keyboard to activate the menus. The exact keys involved varies from one system to another. On a Linux machine (Windowz too) one can increment the counter by typing Alt-A followed by I. On the Mac it's probably the Apple key instead of the Alt key.
Here's the code for adding the menus to the counter application. To illustrate possible ways, each listener is implemented differently. The first one (for the Exit item in the File menu) is done with a named inner class, like in the first version of the counter application. The second one (for the Increment item in the Action menu) is done with an anonymous inner class. Neither the class nor the object has a name. The third one (for the Reset item) is done as a separate class in a separate file. You can judge for yourself which method you prefer. Does the shorter code sacrifice readability? Probably, not. One only has to get used to it, and then you will even like it.
JMenuBar menuBar = new JMenuBar(); this.setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); JMenuItem exitItem = new JMenuItem("Exit"); exitItem.setMnemonic('x'); // Handler implemented as named inner class class ExitItemListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.exit(0); } } exitItem.addActionListener(new ExitItemListener()); fileMenu.add(exitItem);
(continued)
menuBar.add(fileMenu); JMenu actionMenu = new JMenu("Action"); actionMenu.setMnemonic('A'); JMenuItem incrementItem = new JMenuItem("Increment"); incrementItem.setMnemonic('I'); incrementItem.addActionListener( // Anonymous inner class to handle exitItem event new ActionListener() { public void actionPerformed(ActionEvent event) { counter.increment(); update(); } } // end anonymous inner class ); // end call to addActionListener actionMenu.add(incrementItem); JMenuItem resetItem = new JMenuItem("Reset"); resetItem.setMnemonic('R'); // Handler implemented in separate class resetItem.addActionListener(new ResetItemHandler(counter, this)); actionMenu.add(resetItem); menuBar.add(actionMenu);
What GUI does?
They can be used everywhere in Java, eg in creating a collection object which required implemented Comparator type parameter. The anonymous class is a particular example of an inner Java class. The inner class can be static, it can be private, it can be local to a class method (rarely used, eg for implementing Iterator interface inside a method for traversing a Collection type). The anonymous classes are often used in GUI programming.
// w is a widget generating the OneEvent with which we register an event handler, it // in turn, implements OneListener interface by defining the method handleEvent(OneEvent e); // the event handler class is instantiated without a name and defined without a name ....... ......... ge.addListener(new OneListener() { public void handleEvent(OneEvent e) { ... do something ... } } ); // the instance of the event handler is created and missing definitions are added on the fly
What is being achieved through the anonymous inner classes technique?
Using the anonymous inner class techniques a good practice only if the event handler is small (few lines of code). If it takes half a screen or more, it's better to make it in proper outside class of its own.
The Model-View-Controller architecture (MVC), has been first introduced in the
revolutionary Smalltalk-80 platform (much like Java + NetBeans today —
the language + environment + IDE
— but 15 years earlier). The architecture is based on the concept of separating out an application
from its user interface. This means that different interfaces can be used with the same application,
without the application knowing about it. The intention is that any part of the system can be
changed without affecting the operation of the other. For example, the way that the
graphical interface displays the information could be changed without modifying the actual application
or the textual interface. Indeed the application need not know what type of interface is currently
connected to it at all.
The MVC components are:
The MVC is rarely used in its pure form. Swing design can be characterized as MVC in the most general sense: in Swing views and controllers are indivisible, implemented by a single UI object provided by the look and feel. The Swing model architecture is more accurately described as a separable model architecture. The Swing model architecture is described in the Swing Architecture Overview.
When the GUI application is designed with clear separation of data/logic part (Model) and
representation part (View), it's important to maintain the consistency between the separated
classes. But for the sake of reusability, the classes should not be tightly coupled.
(Of course, this is a more general problem which arises in all kind of applications, not just GUI.)
The OO design has a solution to creating a loosely related components (classes), such that a change in
one of them (subject, or observable) changes, the other(s)
(observers) is notified, and as the result the observer queries the subject
for synchronization of its own state with the subject state. The number of observers is not
limited and can change dynamically. The subject does not depend on observers: When the subject
changes its state and notifies the attached observers, it doesn't need to know how many of them are,
and what they are. The strong coupling is avoided because the observer does not have to
watch the subject closely, instead it gets notified when a change in the subject state occurs.
This solution is known as Observer (design) pattern.
The Observer is one of many design patterns which developers use for creating software applications. This DP approach was popularized by the so called Gang-Of-Four (E.Gamma, R. Helm, R. Johnson and J. Vlissides) in 1994. Their original book cataloged 23 different DPs on the area of general OO design. Since then, the number of patterns and the area of their applications (distributed and parallel systems, real-time systems etc) has increased considerably.
The Java API helps to implement the Observer pattern by providing Observer
and Observable types (both are in
java.util package).
public void addObserver(Observer o)(there is also a method for counting registered observers)
public void deleteObserver(Observer o)
public void notifyObservers()(+ one overloaded with a single Object parameter)
protected void setChanged()(there is also a protected method
clearChanged())
public boolean hasChanged()
The application Clock consists of five classes:
update()to repaint the the display panel; registered with model as observer
All classes are implemented in a straightforward manner, and there is nothing surprising
here. We shall have a little to say at the end about Controller.java (meaning of
Timer object), so we spend most of the attention to the "drawing" class
AnalogClockPanel.java as it heavily uses the drawing utilities of
the Java2D package.
The Java 2D API allows to enhance GUI by supporting the following tasks:
The Java Tutorial has a section of
Java 2D, which can be
used for additional studies. Some Java 2D classes are
located in the package
java.awt.geom. The package provides resources for editing and rendering
(creating pixmap on screen or on printable media) line art, text, and images.
Two important classes used in "2D" programming are in the
java.awt package
java.awt.Graphics— the abstract base class for all graphics contexts that allow an application to draw onto components that are realized on various devices
java.awt.Graphics2D— the fundamental (also abstract) class for rendering 2-dimensional shapes, text and images; it extends the Graphics class to provide control over geometry, coordinate transformations, color management, and text layout.
paintComponent()
The class inherits from JPanel and "has-a" Model reference
to
model instance to know where to draw the clock
hands.
public class AnalogClockPanel extends JPanel { Model model; public AnalogClockPanel(Model m) { model = m; setPreferredSize(new Dimension(200, 200)); setBackground(Color.white); } public void paintComponent(Graphics g) { super.paintComponent(g); ...... ....... } ... ...
The constructor content is familiar (no comment is necessary). The rest is the overriding
paintComponent(Graphics g) method of JPanel class, which in turns is
inherited from javax.swing.JComponent. The call
super.paintComponent(g) is done
to call UI delegate's
paint method (which is responsible for
reproducing look-and-feel features). The rest of the
paintComponent method
defines the actual operations which result in clock face and hands being painted.
Remarks: avoid confusing with almost identical method paintComponents()
available from Component which is a part of AWT. We do not override
methods
paint() or
repaint(), since doing it would make
all sorts of things to go wrong (can't go into details, just take API instructions on
faith, and study the Swing programming — you will need a good book).
What is this argument Graphics g that gets passed? This is called a “graphics context”. It keeps track of all sorts of details of how we're doing graphics right now: the background colour, the foreground colour, the line thickness, the current font and so on. In the code that follows we sometimes change the state of the graphics object. Graphics is an abstract class with only two subclasses. One will be used — Graphics2D). Most methods of the Graphics class can by divided into two basic groups: draw and fill methods (enabling you to render basic shapes, text, and images), and attributes setting methods (which affect how that drawing and filling appears). When we actually draw something, the graphics object is the target, not the component we're drawing onto. This may seem to be quite confusing.
So, without calling
super.paintComponent(g);, as API warns, we will likely see visual
artifacts (doesn't happens here, but one has to be consistent). Next we need to get the dimensions
of the area we're drawing the clock face onto:
Rectangle bounds = getBounds();
The actual Graphics type we are working with here is Graphics2D, to get additional features we need to recast:
Graphics2D gg = (Graphics2D) g;
and use
gg 2D graphics context from this moment on. The next step
is to locate the co-ordinates of the centre of the panel.
int x0 = bounds.width / 2; int y0 = bounds.height / 2;
We want to draw the biggest clock face that will fit inside this window. The variable size will represent the radius of the largest circle that will fit.
int size = Math.min(x0, y0);
Graphics2D objects can perform co-ordinate transformations. Instead of having to write out the code for all sorts of complicated geometry (see below), we could just translate and scale everything so that the centre of the clock face was the origin and the radius was 1. It would be nice, but unfortunately it doesn't work for drawing text, only for lines and shapes. So we could use this for the hands and the tick marks, but not for the numbers. So in the end in the end co-ordinate transformations were not used. It would be even more confusing to have two different sets of co-ordinates in use at the same time. But it's a useful thing to know about, and it might come in handy for something else some time.
//gg.translate(x0, y0); //gg.scale(size, size); //gg.setStroke(new BasicStroke(0));
This next bit sets the line width for drawing. This gives you a thin line.
gg.setStroke(new BasicStroke(1));
Now the code to draw the tick marks around the outside of the clock. There's a bit of coordinate geometry here, but you should be able to understand it. The loop takes n from 0 to 59, so there's one iteration for each of the 60 points around the clock face. Each of those points is 6° around from the last one. Angles in mathematics are measured anti-clockwise from the positive x-axis, so the angle around the circle, in degrees, of the nth tick mark should be (90 - 6n). Java deals with angles in radians, so that has to be multiplied by 180/π. The small tick marks go from 0.7 to 0.75 of the size. The long tick marks go from 0.65 to 0.75 of the size. Finally, Java's coordinates have the x-axis as you would expect from mathematics, increasing to the right, but the y-axis is the opposite, it increases down the screen, rather than up. That's why the calculation for the y coordinates of the endpoints of the tick marks involves y0 - r⋅sin(Θ) , but not '+' as in the standard rotation formula.
double radius = 0; double Θ = 0; for (int n = 0; n < 60; n++) { Θ = (90 - n * 6) / (180 / Math.PI); if (n % 5 == 0) { radius = 0.65 * size; } else { radius = 0.7 * size; } double x1 = x0 + radius * Math.cos(Θ); double y1 = y0 - radius * Math.sin(Θ); radius = 0.75 * size; double x2 = x0 + radius * Math.cos(Θ); double y2 = y0 - radius * Math.sin(Θ); gg.draw(new Line2D.Double(x1, y1, x2, y2)); }
Now to drawing the numbers. We have to specify the font. Without going into too much detail, I choose a simple sans-serif font here, with the size increasing in proportion to the size of the window. The tricky thing here is drawing a string with its centre at a particular point. For convenience of writing text on the screen, strings have a reference point which is on the left edge at the baseline (the imaginary line that characters sit on, and that some characters like ‘g’ descend below). To be able to put the centre of a string at a particular point (0.9 of the size out from the centre of the window) we need to get all the dimensions of our string and do a translation.
Font font = new Font("SansSerif", Font.PLAIN, size / 5); gg.setFont(font); for (int n = 1; n <= 12; n++) { Θ = (90 - n * 30) / (180 / Math.PI); radius = 0.9 * size; double x1 = x0 + radius * Math.cos(Θ); double y1 = y0 - radius * Math.sin(Θ); String s = "" + n; // To centre the numbers on their places, // we need to get the exact dimensions of the box FontRenderContext context = gg.getFontRenderContext(); Rectangle2D msgbounds = font.getStringBounds(s, context); double ascent = -msgbounds.getY(); // not used here, but what's the hell double descent = msgbounds.getHeight() + msgbounds.getY(); double height = msgbounds.getHeight(); double width = msgbounds.getWidth(); gg.drawString(s, (new Float(x1 - width/2)).floatValue(), (new Float(y1 + height/2 - descent)).floatValue()); }
Drawing the clock hands is just more of the same. Here, a float argument to BasicStroke() is used to get finer control over the thickness of lines (and it's OK), but it doesn't have much effect. Those numbers are numbers of pixels, so one can't draw a line 1.5 pixels wide. Setting the thickness to zero doesn't give you an invisible line, it gives you the thinnest line the system can draw, which is (unsurprisingly) one pixel wide.
// Draw the hour hand gg.setStroke(new BasicStroke(2.0f)); Θ = (90 - (model.hour + model.minute / 60.0) * 30) / (180 / Math.PI); // model data are used radius = 0.5 * size; double x1 = x0 + radius * Math.cos(Θ); double y1 = y0 - radius * Math.sin(Θ); gg.draw(new Line2D.Double(x0, y0, x1, y1)); // Draw the minute hand gg.setStroke(new BasicStroke(1.1f)); Θ = (90 - (model.minute + model.second / 60.0) * 6) / (180 / Math.PI); // model data are used radius = 0.75 * size; x1 = x0 + radius * Math.cos(Θ); y1 = y0 - radius * Math.sin(Θ); gg.draw(new Line2D.Double(x0, y0, x1, y1)); // Draw the second hand gg.setColor(Color.red); gg.setStroke(new BasicStroke(0)); Θ = (90 - model.second * 6) / (180 / Math.PI); // model data are used x1 = x0 + radius * Math.cos(Θ); y1 = y0 - radius * Math.sin(Θ); gg.draw(new Line2D.Double(x0, y0, x1, y1)); } // end of paintComponent() method } // end of AnalogClockPanel class
The Model class uses Calendar instance which it recreates every
update()
to get the current values of the hour-minute-second. This class from
java.util package
also allows to compute all possible time and date related information (year, month, day-of-week, date,
AM or PM etc). Study the
java.util.Calendar API to learn how further to use this class, since
this will be required in the Assignment 2.
The Controller class uses Timer (from java.swing.Timer). After instantiating
the
listener, which implements ActionListener by telling the
model
to update, it creates the Timer object
timer, which "fires" every 100 msec,
and links it with the
listener. As the result, every time the
timer activates the
listener, the latter asks the
model to
update(),
which entails asking for the exact time using a Calendar object, storing the hour, minute and second in
model's fields, comparing them with the old second value, and, if different,
notifying the Observer
view, what finally causes it to repaint the display.
// constructor from Controller class public Controller(Model m, View v) { model = m; view = v; listener = new ActionListener() { public void actionPerformed(ActionEvent e) { model.update(); } }; timer = new Timer(100, listener); timer.start(); }
When compiled and run, the application displays the ticking "analog" clock just as you'd expected:
Threads in Swing applications
Any work which results in GUI modification that is initiated by an application must be processed on EDT. Every request (response to an event) is wrapped into an event object and posted onto the event queue.
Swing painting
It's a process of an application updating the display, either explicit
— executed through instructions from your code (custom painting) ,
or implicit — through Swing's internal code (window events of resizing etc
are coded this way). A paint request is posted on the EDT and results to methods
paint() (for asynchronous paint requests) and
paintComponent() (for synchronous ones).
The
paint() method shouldn't be normally called in a
Swing program, instead
Component.repaint() is to be used.
When the paint event is dispatched from the EDT,
it's sent to the RepaintManager object, which call
paint()
method(s) on the appropriate component. This paint call results in a component
first painting its own content, then borders, and then any components it may contain
(its children). The entire hierarchy of components, from the top JFrame down
to the last button and menu item, is rendered. This is a back-to-front method of
painting, where the "backmost" component (JFrame) is rendered first, then the items
in that component (eg, JPanel, JMenuBar…), then the items in those
components (JLabels, JMenus, JButtons…), and so on, until
finally the "frontmost" components are rendered too.
"The trick is figuring out where your application needs to plug into this system (of paint calls) to get the right stuff painted at the right time." (FRC, p. 21) Three important things:
JComponent.paintComponent(Graphics)— your application may need to override this method to achieve the custom rendering ("effects" like gradient, opacity change etc);
repaint()call inside it — otherwise EQ will be stuffed!
JComponent.paint(Graphics)— Swing applications do not normally override this method (unlike AWT old ones); but in some FRC apps this overriding is crucial since it allows you to set the graphics state (used by a components and its children)
JComponent.setOpaque(boolean)— may need to be called on a component depending on whether the component's rectangular bounds are not completely opaque (translucent); if so, Swing will do the right thing for translucent components by rendering contents behind the component as necessary (all Swing components except for JLabel are opaque by default)
The presentation by the authors, Chet Haase and Romain Guy, at JavaPolis 2006,
Filthy Rich Clients
The systematic techniques supported by various frameworks (like AnimatedTransitions and TimingFramework) were developed by the two authors and presented in their book Filthy Rich Clients.
JavaFX™ to some extend is a further evolution of this approach (albeit based on a new scripting language).
selected examples which are not captured in the podcast —
For storing and combining the colours of a drawing primitive into the destination (esp. AlphaComposite for translucency effects)
For visual enhancement, but also for more advanced effects like reflections and fade-outs
Blurs, reflections, drop shadows, highlights, sharpening
Motion, fading, pulsation, springs, morphing
Visual enhancements
More realistic motion simulation (in games, simulations etc) | http://cs.anu.edu.au/student/comp2100/lectures/gui/gui.html | crawl-003 | refinedweb | 6,459 | 55.95 |
Recent:
Archives:
This month, I will explore SSL as implemented by the JSSE (Java Secure Socket Extension), and show you how to build secure network applications in Java using SSL and JSSE.
Let's begin with a simple demonstration. JSSE provides an SSL toolkit for Java applications. In addition to the necessary classes and interfaces, JSSE provides a handy command-line debugging switch that you can use to watch the SSL protocol in action. In addition to providing useful information for debugging a recalcitrant application, playing with the toolkit is a great way to get your feet wet with SSL and JSSE.
To run the demonstration, you must first compile the following class:
public class Test { public static void main(String [] arstring) { try { new java.net.URL("https://" + arstring[0] + "/").getContent(); } catch (Exception exception) { exception.printStackTrace(); } } }
Next, you need to turn on SSL debugging and run the above application. The application connects to the secure Website that
you specify on the command line using the SSL protocol via HTTPS. The first option loads the HTTPS protocol handler. The second
option, the debug option, causes the program to print out its behavior. Here's the command (replace
<host> with the name of a secure Web server):
java -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal. -Djavax.net.debug=ssl Test <host>
You need to install JSSE; refer to Resources if you're unsure how.
Now let's get down to business and talk about SSL and JSSE.
The code in the introduction demonstrates the easiest way to add SSL to your applications -- via the
java.net.URL class. This approach is useful, but is not flexible enough to let you create a secure application that uses generic sockets.
Before I show you how to add that flexibility, let's take a quick look at SSL's features.
As its name suggests, SSL aims to provide applications with a secure socketlike toolkit. Ideally, it should be easy to convert an application that uses regular sockets into an application that uses SSL.
SSL addresses three important security issues:
SSL relies heavily on both public-key and secret-key cryptography. It uses secret-key cryptography to bulk-encrypt the data exchanged between two applications. SSL provides the ideal solution because secret-key algorithms are both secure and fast. Public-key cryptography, which is slower than secret-key cryptography, is a better choice for authentication and key exchange.
Thanks!By Anonymous on January 14, 2009, 4:32 amGreat start to poking around with SSL!
Reply | Read entire comment
View all comments | http://www.javaworld.com/javaworld/jw-05-2001/jw-0511-howto.html | crawl-002 | refinedweb | 427 | 55.54 |
The Q3ComboTableItem class provides a means of using comboboxes in Q3Tables. More...
#include <Q3ComboTableItem>TableItem.
The Q3ComboTableItem class provides a means of using comboboxes in Q3Tables.
A Q3ComboTableItem is a table item which looks and behaves like a combobox. The advantage of using Q3ComboTableItems rather than real comboboxes is that a Q3ComboTableItem uses far less resources than real comboboxes in Q33ComboTableItems.
Q3ComboTableItem items have the edit type WhenCurrent (see EditType). The Q33ComboTableItem will permit the user to either choose an existing list item, or create a new list item by entering their own text; otherwise the user may only choose one of the existing list items.
To populate a table cell with a Q3ComboTableItem use Q3Table::setItem().
Q3ComboTableItems may be deleted with Q3Table::clearCell().
Q3ComboTableItems can be distinguished from Q3TableItems and Q3CheckTableItems using their Run Time Type Identification number (see rtti()).
See also Q3CheckTableItem, Q3TableItem, and Q3ComboBox.3ComboTableItems cannot be replaced by other table items since isReplaceable() returns false by default.
See also Q3Table::clearCell() and EditType.
Q3ComboTableItem destructor.
Returns the total number of list items in the combo table item.
Reimplemented from Q3TableItem::createEditor().
Returns the index of the combo table item's current list item.
See also setCurrentItem().
Returns the text of the combo table item's current list item.
See also currentItem() and text().
Returns true if the user can add their own list items to the combobox's list of items; otherwise returns false.
See also setEditable().
Reimplemented from Q3TableItem::paint().
Reimplemented from Q3TableItem::rtti().
Returns 1.
Make your derived classes return their own values for rtti()to distinguish between different table item subclasses. You should use values greater than 1000, preferably a large random number, to allow for extensions to this class.
See also Q3TableItem::rtti().
Reimplemented from Q3TableItem::setContentFromEditor().
Sets the list item i to be the combo table item's current list item.
See also currentItem().
This is an overloaded function.
Sets the list item whose text is s to be the combo table item's current list item. Does nothing if no list item has the text s.
See also currentItem().
If b is true the combo table item can be edited, i.e. the user may enter a new text item themselves. If b is false the user may may only choose one of the existing items.
See also isEditable().
Sets the list items of this Q3ComboTableItem to the strings in the string list l.
Reimplemented from Q3TableItem::sizeHint().
Reimplemented from Q3TableItem::text().
Returns the text of the table item or an empty string if there is no text.
See also Q3TableItem::text().
Returns the text of the combo's list item at index i.
See also currentText(). | http://doc.qt.nokia.com/4.6-snapshot/q3combotableitem.html#count | crawl-003 | refinedweb | 447 | 52.97 |
MySQL Stored Procedure Programming
samzenpus posted more than 7 years ago | from the a-little-lite-afternoon-reading dept.
(3, Insightful)
ShieldW0lf (601553) | more than 7 years ago | (#18786829) (2, Insightful)
Andy Tai (1884) | more than 7 years ago | (#18786889)
Not really FUD (3, Interesting)
Anonymous Coward | more than 7 years ago | (#18787269) (5, Informative)
elp (45629) | more than 7 years ago | (#18788085):The parent comment is a classic example of FUD (4, Interesting)
cyphercell (843398) | more than 7 years ago | (#18787337).
Is 640kB enough to run a MySQL server? (1)
faramir_fr (831190) | more than 7 years ago | (#18786895)
Re:MySQL aren't trustworthy (3, Insightful)
bahwi (43111) | more than 7 years ago | (#18786927)..
Re:MySQL aren't trustworthy (2, Informative)
Overly Critical Guy (663429) | more than 7 years ago | (#18787615)
Re:MySQL aren't trustworthy (1)
morgan_greywolf (835522) | more than 7 years ago | (#18787963) having to run to the forums or google for answers every 5 minutes. The key to being able to figure out something as complicated as an RDBMS is documentation.
Put another way: how useful would [insert your favorite distro] Linux be to even a seasoned UNIX administrator with no Linux experience if it had either no manpages or poorly written ones?
Re:MySQL aren't trustworthy (1, Interesting)
Anonymous Coward | more than 7 years ago | (#18787667)
I have been using PostgreSQL for over 6 years and I've always found all the documentation I've needed (mostly on postgresql.org actually).
You call shenanigans...I'm sorry but I have to call incompetence on your part...
Re:MySQL aren't trustworthy (3, Informative)
XorNand (517466) | more than 7 years ago | (#18787739) (3, Insightful)
LizardKing (5245) | more than 7 years ago | (#18788871) (4, Insightful)
ClosedSource (238333) | more than 7 years ago | (#18787215)
Re:Names matter sometimes (2, Funny)
Sloppy (14984) | more than 7 years ago | (#18787603)
Re:Names matter sometimes (0)
Anonymous Coward | more than 7 years ago | (#18788917)
Re:MySQL aren't trustworthy (0)
Anonymous Coward | more than 7 years ago | (#18787247)
isnt it the same for ALL the stuff that took off : (1)
unity100 (970058) | more than 7 years ago | (#18787265)
age old concept - cheap, easy, simple thing that works. almost all tech stuff took off like that.
Emulated SP's (1)
vivin (671928) | more than 7 years ago | (#18787653)
Re:Emulated SP's (1)
Ajehals (947354) | more than 7 years ago | (#18788849)
For the record on the MySQL (The world's most popular open source database) vs PostgreSQL (The world's most advanced open source database), I think Prefer flat files and grep.
Wait, this sounds familiar... (1)
Mr. Underbridge (666784) | more than 7 years ago | (#18787661)
Sounds like they're violating a patent for "Method and Implementation of Field-Based Reality Distortion" held by Apple, Inc.
Re:MySQL aren't trustworthy (5, Interesting)
CoughDropAddict (40792) | more than 7 years ago | (#18788459)).
MySQL vs Firebird (0, Offtopic)
BuR4N (512430) | more than 7 years ago | (#18786857).
Re:MySQL vs Firebird (4, Insightful)
PCM2 (4486) | more than 7 years ago | (#18786979):MySQL vs Firebird (1)
otis wildflower (4889) | more than 7 years ago | (#18787549)
Trying to show columns from table in Sybase? I'd rather stick a fork in my balls.
Re:MySQL vs Firebird (1)
gnuman99 (746007) | more than 7 years ago | (#18788483)
\d [table name]
or \l to list all tables in database.
Very handy and fast.
Re:MySQL vs Firebird (1)
aled (228417) | more than 7 years ago | (#18788567)
Firebird CLI (as of version 1.0.3 which is not a recent one but is what I use) is as cool to use as eating rocks. It made me have remember fondly the old Informix dbaccess utility...
Re:MySQL vs Firebird (1)
newt0311 (973957) | more than 7 years ago | (#18788689)
\d <table_name>
pretty easy.
Re:MySQL vs Firebird (1)
kpharmer (452893) | more than 7 years ago | (#18788663)
> for the job", a few possible reasons:
1. maybe you don't want to waste time testing for exceptions that should be reported in a more robust fashion
2. maybe you need a large reporting database - and don't want to waste $100k+ on extra hardware to make up for mysql's lack of partitioning, parallelism, automatic summarization and mature optimization.
3. maybe you need multiple databases, and one of them is a reporting database - so decide to go for a consistent other option to save on labor (which is more expensive that licensing costs these days)
4. maybe you want free online backups
5. maybe you want to avoid licensing costs
6. maybe you want to avoid having to talk to a lawyer to deal with mysql's obfuscated license
7. maybe you need better optimization for complex queries
8. maybe you want to ensure that clients can't override your data quality constraints
9. maybe you find that there are many great programmers who would prefer not to work with mysql
10. etc,etc,etc
So, quite a few reasons why a person might think that mysql has a way to go before being good enough for their project.
Re:MySQL vs Firebird (0)
Anonymous Coward | more than 7 years ago | (#18788001)
Between Firebird and Postgres, much of the same capabilities are there, but the philosophy is different. Firebird was originally meant to be an embedded database. Its ancestor can be found in the Ahbrams tank. Its intended to be self-optimizing. Therefore there is not a lot of settings that you can tweak like in Postgres (and Oracle and DB2). I generally use Firebird first.
If I'm in the situation that I need to tweak the performance, then I go with Postgres (or Oracle or DB2). So why not just go with Postgres? The usage between the two os obvious when your using it. Firebird is so simple. Its just easier if you don't need the control. As always, use the right tool for the job
Re:MySQL vs Firebird (3, Insightful)
LurkerXXX (667952) | more than 7 years ago | (#18788397):MySQL vs Firebird (0)
Anonymous Coward | more than 7 years ago | (#18788603)
I think it's more a 'what ya wanna do?' thing. For web, MySQL is great, it comes preinstalled pretty much everywhere, is easy to manage for small DB's. I would not feel comfortable building a 'serious' software application with it though - but I might be biased there, because featurewise, I don't think MySQL is far behind. These days I use an abstraction layer that does away with all the SQL as well (ofcourse I CAN use it if I need to do something overly complex - though so far I have not needed that yet for webdevving), so I wouldn't know how the newest MySQL compares SQL-dialect wise.
What's your opinion (3, Interesting)
CastrTroy (595695) | more than 7 years ago | (#18786863)
It isn't about speed (4, Insightful)
Tony (765) | more than 7 years ago | (#18787195) (5, Insightful)
sammy baby (14909) | more than 7 years ago | (#18787221):What's your opinion (2, Interesting)
PRMan (959735) | more than 7 years ago | (#187889:What's your opinion (1, Insightful)
Anonymous Coward | more than 7 years ago | (#18787497).
Re:What's your opinion (2, Insightful)
arivanov (12034) | more than 7 years ago | (#18787781).
Re:What's your opinion (1)
F1re (249002) | more than 7 years ago | (#18788141)
Re:What's your opinion (2, Insightful)
shatfield (199969) | more than 7 years ago | (#18788555)
case study (1)
kpharmer (452893) | more than 7 years ago | (#18788915) show trends. The results have been queries that returned incorrect data, that scanned 4 *trillion* rows over 6 hours rather than 1 million in 5 seconds, etc, etc, etc.
The solution that we settled upon was to encapsulate all of their sql within stored procedures. These procedures then:
1. validated all arguments - to ensure that they didn't mix them up and ask for the wrong data
2. logged each call along with argument values, rows returned, and time to return
3. returned the result set along with some useful metadata
4. processed everything in a highly consistent way
Now, I don't typically use stored procedures heavily - and often prefer to encapsulate the physical data model in views to save time. But in this case the availability of this option was really a life-saver. And note that these stored procedures are also allowing us to more easily change the underlaying data model, measure and tune each query, maintain the queries, etc, etc.
All good stuff, though your mileage may vary.
Re:What's your opinion (1)
nuzak (959558) | more than 7 years ago | (#18788937). Anything that a user can do with different privileges than their own pretty much has to be a SP.
Bulk inserts usually can't leverage SP's easily, and using SP's just to give names to ad hoc queries isn't usually appropriate (it's ok in if you put it in another user's schema, it just doesn't belong in the same schema).
If you're using an ORM like hibernate, there's no point in putting basic CRUD operations into SP's. In fact, most of the time, you just use the DB as a storage layer then.
Re:What's your opinion (1)
Just Some Guy (3352) | more than 7 years ago | (#18788941) (5, Informative)
karavelov (863935) | more than 7 years ago | (#18786873)
Re:Stred pocedures (1)
Just Some Guy (3352) | more than 7 years ago | (#18787415)
I can only think that was a poorly written sentence, and what they really meant was:
The way you interpreted it makes no sense at all, even though you parsed it correctly. I have to assume they didn't really mean it that way.
Re:Stred pocedures (0)
Anonymous Coward | more than 7 years ago | (#18787425)
While the end result between select dothisstuff(); and call dothisstuff(); may be the same, the way the system goes about doing it may be different thanks to the overhead of a select query that has to get results. Of course, in the grand scheme of things, this difference is negligible.
Stored procedures BAD... story (0, Flamebait)
Travoltus (110240) | more than 7 years ago | (#18786911)
I warned my boss NOT to keep stored procedures and switch to front ends instead, and just after we switched to ActiveX front ends (a mistake in and of itself) we found we needed to move from MS Sql Server to Oracle. Well, that migration was about as complex as dumping the database into an ascii file and reimporting it into the new server. The front ends didn't even cough. Back up in 2 hours.
Had we kept the stored procedures? Holy downtime and bug infestation, Batman!
As a manager now, I would fire anyone who uses stored procedures. Even if it is "faster."
Re:Stored procedures BAD... story (1)
zappepcs (820751) | more than 7 years ago | (#18787027)
Re:Stored procedures BAD... story (5, Insightful)
drmerope (771119) | more than 7 years ago | (#18787135)
Re:Stored procedures BAD... story (1)
guruevi (827432) | more than 7 years ago | (#18787639)
Re:Stored procedures BAD... story (2, Interesting)
gnuman99 (746007) | more than 7 years ago | (#18788725)
Re:Stored procedures BAD... story (5, Insightful)
dedazo (737510) | more than 7 years ago | (#18787041):Stored procedures BAD... story (2, Informative)
RedElf (249078) | more than 7 years ago | (#18787189)
Stored procedures have added benefits such as additional security, and forcing application developers to implement database functionality properly, not sloppily.
Re:Stored procedures BAD... story (0, Redundant)
Shados (741919) | more than 7 years ago | (#18787429)
there are douzans of ways to use dynamic SQL in maintainable, efficient ways. Stored procedures have quite a few advantages that can't be brushed off either, so it really comes to the people in charge to make an enlightened decision, but its NOT as simple as "SP good, everything else bad!". Both sides of the spectrums have their good points, and everywhere in between (a mix of both methods).
Re:Stored procedures BAD... story (5, Funny)
Anonymous Coward | more than 7 years ago | (#18787621)
Re:Stored procedures BAD... story (1)
dedazo (737510) | more than 7 years ago | (#18788095)
And then a few years ago I had a developer in one of my teams that was a freakin' SQL guru. I mean, this guy was just fantastic. He showed us how to do the most amazing things with SPs and functions without sacrificing speed, integrity or maintainability. I'm really grateful that I had the (humbling!) experience of working with him for a year, because I learned a hell of a lot about a topic that previously I had found mostly fastidious. Trust me that whetever we were paying him at the time it wasn't nearly enough.
I'll give you an example where inline SQL is not only problematic but simply just flat out impossible. At a previous project I was in charge of a rather large application for a financial services company that shall not be named at this time. Aside from actually designing and writing the thing, part of the mandate was to be able to pass a SOX audit with flying colors. The database for this app was secured so that the confgured identity we were using only had permission to execute SPs and views. No direct table access. This enables the architect (moi) to assert that there is a clear audit trail in the form of source control for the SPs and the database changelogs that can tell them (the auditors) at what point who decided that writing or reading from/to TableX or TableY was a good idea. In a scenario like this, not only would inline SQL simply fail for lack of permissions, but it would cause me a few week's delay and a good chunk of the client's budget (and likely my job thereafter) to fix because I'd fail the audit.
The world of enterprise corporate software development can be a bitch, but it pays very well =)
Re:Stored procedures BAD... story (1)
Cyberax (705495) | more than 7 years ago | (#18787053)
Re:Stored procedures BAD... story (4, Insightful)
Tet (2721) | more than 7 years ago | (#18787055):Stored procedures BAD... story (1)
shaitand (626655) | more than 7 years ago | (#18787345) compliant SPs you can use and still not be locked into a vendor. There will still no doubt be proprietary choices as well, the young and stupid will use them for their whizzbang features, the wise will avoid them until they become ubiquitous.
Re:Stored procedures BAD... story (2, Interesting)
Tet (2721) | more than 7 years ago | (#18788039)
Demonstrably false. The ANSI standard for stored procedures already exists. MySQL has merely implemented this standard. You can port stored procedures to any other database that supports the standard (which admittedly didn't give you a lot of choice last time I looked). PostgreSQL initially).
Re:Stored procedures BAD... story (1)
shaitand (626655) | more than 7 years ago | (#18788599):Stored procedures BAD... story (0)
Anonymous Coward | more than 7 years ago | (#18787057)
Re:Stored procedures BAD... story (2, Insightful)
DavidpFitz (136265) | more than 7 years ago | (#18787081).
Re:Stored procedures BAD... story (0, Offtopic)
sfkaplan (1004665) | more than 7 years ago | (#18787537)
>
> And you'd get sued shortly thereafter for unfair dismissal
Ummmm, what? Do a little research on our `at-will employment' system. There are only a few reasons that an employer may *not* use in firing you (e.g. member of a protected group like minorities, women, etc.). Otherwise, your employer is welcome to fire you because he thinks your voice is too high, that pick you pick your nose too much, or that you are a Dallas Cowboys fan. A manager could fire you for using stored procedures, and the `unfairness' of his evaluation doesn't even begin to point towards a law suit.
That said, I agree that any manager who categorically rejects the use of a useful tool without consideration of the context is a twit for whom I would not want to work either.
Re:Stored procedures BAD... story (0, Offtopic)
MBGMorden (803437) | more than 7 years ago | (#18787677)
This is beside the fact that many, many states are "right to work" states now. Translated: in many states there's no such thing as unfair dismissal. They can fire you for ANY reason. You bought a standard transmission car and your manager thinks good programmers only drive automatics? Fired, and legally.
Re:Stored procedures BAD... story (1)
Tim Browse (9263) | more than 7 years ago | (#18787917)
Also, I hear tell that some people work in places that are not 'states' at all!
(And I'm not talking about D.C.)
Stored procedures and data integrity (2, Insightful)
Tony (765) | more than 7 years ago | (#18787093)
As a database engineer, I would *definitely* fire anyone who didn't use these tools to maintain data integrity.
Re:Stored procedures and data integrity (1)
CastrTroy (595695) | more than 7 years ago | (#18787253)
Re:Stored procedures and data integrity (1)
jaydonnell (648194) | more than 7 years ago | (#18787987) it is to write t-sql or whatever. I know that my assumption is a big one, and that it's not true for many, but at the same time it is applicable to many people. Myself included.
Re:Stored procedures and data integrity (1)
LurkerXXX (667952) | more than 7 years ago | (#18788557)
I write/debug/test/and version control my stored procedures just fine, thank you very much.
Re:Stored procedures and data integrity (1)
Electrum (94638) | more than 7 years ago | (#18788681) checks correct in all of those places? What if the constraint needs to change later? What if someone runs some SQL manually and accidentally uses the wrong value?
Re:Stored procedures BAD... story (0)
Anonymous Coward | more than 7 years ago | (#18787113)
This is the dumbest thing i read here for a while. Good luck with your manager job, you sure ain't a techie. Stored procedures are great vs dynamic sql in many ways (speed, security etc).Stored procedures are not always right but your comment is just stupid.
Re:Stored procedures BAD... story (1)
CastrTroy (595695) | more than 7 years ago | (#18787127)
Re:Stored procedures BAD... story (0)
Anonymous Coward | more than 7 years ago | (#18787133)
1. Dismissing technology out of hand for the simple reason of portability ignores significant advantages of what stored procedures offer. Instead of throwing more hardware at a problem, the work can be split among the frontend and backend.
2. You would have been fired also for the significant downtime you experienced in the migration.
If you are migrating platforms more than once in a blue moon, you have bigger issues.
Re:Stored procedures BAD... story (3, Insightful)
PCM2 (4486) | more than 7 years ago | (#18787141):Stored procedures BAD... story (1)
LurkerXXX (667952) | more than 7 years ago | (#18787251)
Re:Stored procedures BAD... story (2)
nuzak (959558) | more than 7 years ago | (#18787339):Stored procedures BAD... story (2, Insightful)
RedElf (249078) | more than 7 years ago | (#18787413)
Re:Stored procedures BAD... story (1)
Chicken04GTO (957041) | more than 7 years ago | (#18787469)
You decide an entire methodology for development is stupid because of one bad experience and you would fire anyone who dare challenge your AUTHORITAY!
Re:Stored procedures BAD... story (0)
Anonymous Coward | more than 7 years ago | (#18787505)
Pick a database suitable for your task and use it as optimally as possible; easy portability be damned.
Re:Stored procedures BAD... story (1)
doom (14564) | more than 7 years ago | (#18787757) (1)
barjam (37372) | more than 7 years ago | (#18788709)
We were using EJBs without stored procedures and the only reason it took as long as it did was because some of the more exotic queries we were using at the time.
Re:Stored procedures BAD... story (0)
Anonymous Coward | more than 7 years ago | (#18787559)
Here's why stored procs are bad, it includes some information like stored procs don't even run faster:
And my response to that article
Ad-hoc SQL Script is brittle
"changes to a relational model will have always an impact on the application". so you could update your procs which are all in one place, or search for and hope you changed all of your ad-hoc queries. Either way you have to change something, the only benefit is not involving a DBA.
Security
Instead of applying security through stored procs, do it through roles. Oh yeah that's basically the same thing too? Oh I didn't think of that. What did you say about Parameterized queries? Totally secure? then this guy's an idiot.
Performance
So, procs have their execution plans cached like dynamic SQL? Great, that's the third thing that's basically the same. Oh yeah and stored procs are bad because of cursors. (wtf?) And a database with 100 tables, with 7 fields per table. "You can't create stored procedures for all possible combinations either, that would require 100*7! procedures." Yeah, I can do it in SQL and C# and ASP 3.0 and probably some other stuff. Who writes their own add/update/delete procs these days?
So his argument is Don't use stored procs because dynamic SQL is exactly the same. And disregard SQL injection, that's not important, it's much better to spend time validating all of your input. And apparently his DBA doesn't like him. And he changes his data model far too often, he needs better design discipline.
The only part of this I agree with is the comment:
I would hate to run into this type of code personally. I mean, you are basically writing a stored procedure at that point and hard coding it into your app.
Re:Stored procedures BAD... story (1)
Hemogoblin (982564) | more than 7 years ago | (#18787647)
"Uh, I can reinstall the procedures, I have the SQL Server CD with me."
"Get OUT."
Re:Stored procedures BAD... story (1)
Bob9113 (14996) | more than 7 years ago | (#18788863).
Deciding if MySQL is an option (3, Insightful)
moore.dustin (942289) | more than 7 years ago | (#18786965)
Re:Deciding if MySQL is an option (5, Funny)
gusx (898415) | more than 7 years ago | (#18787019)
return (estimated_rows_in_table($table) < 100000);
Re:Deciding if MySQL is an option (0)
Anonymous Coward | more than 7 years ago | (#18788107)
return estimated_rows_in_table($table) < MAX_ROWS;
Re:Deciding if MySQL is an option (1)
suggsjc (726146) | more than 7 years ago | (#18788601)
Re:Deciding if MySQL is an option (1)
ak3ldama (554026) | more than 7 years ago | (#18788789)
Re:Deciding if MySQL is an option (4, Insightful)
coyote-san (38515) | more than 7 years ago | (#18787699):Deciding if MySQL is an option (1)
markhahn (122033) | more than 7 years ago | (#18788323)
I don't follow your argument on security - using the values() syntax is an easy way to avoid concatenation. the premise of trusting the DB to handle all security seems terribly mistaken to me.
Glad some database noobs modded this up (0)
Anonymous Coward | more than 7 years ago | (#18787943)
I run a huge mysql database with billions of table rows. Such an ignorant comment suggests you know about indexes and how to optimize databases in general. My select speeds on a billion row table in Mysql? less than 1 tenths of a second returning 10000 rows. Get back to me when your done fiddling around with your wordpress and phpbbs. Thanks!
The management
Re:Deciding if MySQL is an option (2, Informative)
LordLucless (582312) | more than 7 years ago | (#18788045)
Re:Deciding if MySQL is an option (4, Informative)
consumer (9588) | more than 7 years ago | (#18788079)
Re:Deciding if MySQL is an option (3, Informative)
kpharmer (452893) | more than 7 years ago | (#18788771)
>:Deciding if MySQL is an option (0)
Anonymous Coward | more than 7 years ago | (#18788099)
"any other open source system"? (0)
Anonymous Coward | more than 7 years ago | (#18787317)
What does MySQL's lack of features have to any other open source system to do?
"Oh. Since MySQL doesn't have stored procedures, you shouldn't use PostgreSQL!"
Good one Ploppy (2, Funny)
Tim Browse (9263) | more than 7 years ago | (#18787993)
my_replace( 'We love the Oracle server', 'Oracle', 'MySQL').
The long Winter evenings must just fly by.
PostgreSQL is not the one-size-fits-all (0, Troll)
Karaman (873136) | more than 7 years ago | (#18788021)
Pain in the ass to debug (1)
not already in use (972294) | more than 7 years ago | (#18788575) | http://beta.slashdot.org/story/83483 | CC-MAIN-2014-42 | refinedweb | 4,079 | 69.52 |
Two years ago I came up with an idea (Russian only) of making a generic library for creating testcases. Months have passed, thoughts circulated in my mind over and over, and finally I sculpted something in code. Far many things are yet not implemented, but I already frequently use ones which are.
Here it is:. You can download the library itself (its single header jngen.h) here.
Jngen works with arrays, graphs and trees. It also can generate some strings and geometry and provides command-line options parser and cool SVG drawer. Here are some working examples.
cout << Array::id(10).shuffled().add1() << endl; // permutation of elements from 1 to 10 cout << Tree::random(100000, 20) << endl; // "long" tree with elongation 20 pair<string, string> test = rnds.antiHash({{mod1, base1}, {mod2, base2}}, "a-z", 10000); // should be self-describing :) cout << rndg.convexPolygon(1000, 1e9) << endl; cout << Graph::random(100000, 200000).connected() << endl; cout << rndm.randomPrime(1e18, 1e18 - 10000000) << endl;
Almost all code is documented, there are some real-world examples.
Getting started is very easy. If you work with testlib.h and use in your generators only registerGen and rnd.next, replace
#include "testlib.h" with
#include "jngen.h" and you'll see no difference. Compilation will last a bit longer, but there is a workaround which makes it compile even faster than testlib.
I'll be happy if you try it and share your feelings and feedback. Everyone finds his code and interfaces perfect until shows them to the community.
Currently the library has much more "basic" things and primitives than "real content" – I mean there are more bricks than practical testcases. We're working on it: soon several "test suites" will be added, and you'll be able to create reasonable tests for your, say, LCA-like-queries problem, in several lines of code.
I'd like to thank zemen, Endagorion and Errichto for useful discussions and advice, Endagorion, GlebsHP and CherryTree for their libraries from which I could
borrow code learn upon and MikeMirzayanov for testlib which was a massive source of inspiration on early stages. | http://codeforces.com/blog/ifsmirnov | CC-MAIN-2017-51 | refinedweb | 349 | 67.04 |
28, 2007 1:06 pm Jesse Barnes wrote:
> On Friday, September 28, 2007 12:51 pm Ian Romanick wrote:
> > > No, I'm not sure what should happen in this case. Doing a vblank
> > > sync'd buffer swap or vblank wait on an offscreen drawable
> > > doesn't make much sense does it? In what cases might those calls
> > > occur?
> >
> > The spec doesn't say that an application can't call
> > glXGetViewSyncSGI when a pbuffer is bound, so you can be sure that
> > someone does.
>
> Yeah, the question is: what should it do? With the posted code, I
> think it'll get either the primary pipe's counter (if the drawable
> has never been a window) or the last pipe it was associated with.
> That seems sufficient...
Sorry for the delay, got sidetracked for a few weeeks with other stuff.
Any comment on the "driDrawableGetMSC32() on pbuffer" case? Maybe
returning GLX_BAD_VALUE (or some other EINVAL eqivalent) makes more
sense?
> > >> I was thinking of something like:
> > >>
> > >> if (pdraw == NULL) {
> > >> return GLX_BAD_CONTEXT;
> > >> }
> > >>
> > >> if (pdraw->getMSC != NULL) {
> > >> ....
> > >> } else if (psc->driScreen.getMSC != NULL) {
> > >> ....
> > >> }
> > >>
> > >> return (ret == 0) ? 0 : GLX_BAD_CONTEXT;
> > >
> > > Ok, that looks good. I'll fix it up.
> >
> > I take that back. I looked at the unpatched code (instead of just
> > looking at the patch). The code already returns GLX_BAD_CONTEXT if
> > the return from __glXGetCurrentContext is NULL. This means that
> > pdraw *cannot* be NULL.
>
> Yeah I looked again right after posting the last patch and the
> current code seems ok. I'll remove the pdraw == NULL checks.
I fixed this. The patch is a little cleaner for it.
> > > No, in that case the MSC will change and possibly decrease. But
> > > drivers can handle that case by tracking which output a given
> > > drawable is on (or mostly on), so that the drawable is sync'd to
> > > the right value.
> >
> > That's bad. The MSC for a drawable should never decrease. I can
> > easily envision cases where that would cause problems for apps.
> >
> > Drivers will have to make sure that getMSC returns values that only
> > increase. We can easily do that by keeping two values in the
> > drawable private. One value tracks a base MSC, and the second
> > value tracks the initial MSC on the current pipe when the base MSC
> > was set. The driver's getMSC would then return "base +
> > (pipe_current_MSC - pipe_base_MSC)".
>
> Wouldn't we want to increment the base value by the difference
> between the last pipe value and the current one?
>
> But yeah, handling a drawable that moves between outputs with
> different vblank counters is a little tricky, I think we could handle
> making it monotonic in driDrwableGetMSC32 by using per-drawable,
> per-pipe vblSeq values as you suggest.
Thinking about this more, I think we can make the counter not decrease,
but I don't think we can avoid bad behavior. There are two possible
failure modes:
1) counter goes backward when the window moves to another screen
In this case, unless the application continuously updates its
internal vblank counter (used for later calls to VideoSync), this may
cause the next VideoSync call to timeout in the DRM (3s iirc). This is
a fairly obvious failure.
2) we fix (1) and the counter jumps a large amount when the window
moves to another screen
In this case, the app may or may not see the same timeout as (1),
depending on refresh rates and the size of the jump. The real problem
here is two screens running at different refresh rates, since we can
avoid large jumps when the refresh rates are the same.
Since the VideoSyncSGI extension was designed with genlocking in mind,
I'm inclined to leave it alone. At the very least, it seems like it
should be dealt with in a different patch from this one, but more
likely we'll just have to warn application developers that the vblank
value they see is associated with the screen their window is on, so
they need to be careful to properly deal with changes...
Any other thoughts? Any objections to me pushing the attached?
Thanks,
Jesse
View entire thread
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/dri/mailman/message/17108683/ | CC-MAIN-2017-04 | refinedweb | 721 | 72.97 |
The following is a guest post by David Clark. I think David's new Sass library "Scut" is pretty interesting. It's like a design utility library, which is distinct from a design pattern library in that it enforces no particular structure or particular visual design. I've always found this kind of thing fascinating, largely because I've never been able to pull it off in a way that feels good to me. I always end up leaning too far into visual design, or too abstract to the point of it not being all that useful. I think David just might be on the right track here. I'll let him explain in detail.
I've started an open-source Sass utility library with a straightforward mission: to ease and improve our implementations of common style-code patterns. I'm calling it Scut.
Scut is a collection of Sass mixins, placeholders, functions, and variables that are generic enough to be widely reusable — within any project, any design — and easy to integrate into diverse workflows and coding conventions. Every Scut utility is an effort to reduce repetition, increase organization, and encourage the reuse and sharing of style code.
Scut is not a frontend framework, and offers no default styling: it does not concern itself with the gradients on your buttons, the padding of your boxes, the font-size of your headers, or the color of your skin. And it won't provide your vendor-prefixes: Scut's unique focus differentiates it from other preprocessor libraries. It should help you build websites — especially if you, like me, work on a lot of sites, rather than a single large app — but it doesn't do everything. It is a companion to, not a replacement for, other popular tools and practices.
I've written this article to explain my motivation, intention, and method in starting Scut, and, most of all, to seek your collaborative input.
So as you read, please keep in mind that Scut is in its infancy, and that you, dear reader, have the power to alter and improve it, whether by adding and upgrading utilities or by clarifying the principles behind them. If at any point you decide that you're ready to try it out or throw in some ideas, please head to Scut's documentation or the repository on Github.
How We Share Style-Code Now, and Why There's Room for Scut
Reusable Components: Insert Pretty Button Here
Consider Bootstrap, Foundation, PureCSS, etc. — whether we call them frontend frameworks, UI kits, design systems, or whatever else, their purpose is clear: to help developers build functional, attractive, reliable interfaces, quickly and easily, from pre-crafted components.
Even if we don't use these frameworks often, we should recognize their value and learn from them. Above all, they demonstrate the virtues of a systematic approach to site design. Mark Otto's exhortation to "Build your own Bootstrap" and Brad Frost's description of "Atomic Design" remind us that if we don't want to adopt someone else's reusable components, we should build our own bits and pieces to be equally systematic, equally reusable. Mailchimp's Pattern Library and Mapbox's Base serve as large-scale examples of that approach.
This variety of style-code sharing and reuse — the component collection, the design system — has garnered a lot of attention, and that's a good thing. But it is not the only variety; and I write all this in order say that Scut is different.
A good frontend framework helps us in many ways, but the scope of its reusability across diverse projects and designs is limited. Scut aims at a broader, more rudimentary kind of reuse — reuse not of polished components, but of the abstract, generic patterns and practices that underlie those components. (At least, those patterns and practices that are not clear and simple in vanilla CSS.)
Abstract, Generic Patterns and Practices: "Unfinished" Styling
Another way to share and reuse style code — Scut's way — involves the transmission of useful maneuvers, clever tricks, and best practices, but not finished components.
Here's the basic idea: Create and share modules that are as generic, flexible, naked as possible, so they can be used in any project to implement a useful pattern, without demanding or determining a particular environment for it.
This kind of sharing happens in two ways: tutorials and utility libraries.
Tutorials
For a paradigmatic example of The Tutorial, I refer you to this very blog, CSS-Tricks, where the eminent Chris Coyier explains and exemplifies patterns we can all apply in our own work. Then there are other blogs, books, articles, Stack Overflow answers, resources divers and sundry — more tutorials on this Internet then we know what to do with.
The writing and reading and sharing of tutorials is an indispensable practice, especially excellent because tutorials teach while they share. However, they provide practices we can reproduce rather than tools we can reuse: they disseminate knowledge, not utilities.
Utilities
The Reusable Generic Utility, Scut’s ideal constituent, is a kind of extension of The Tutorial. It turns out that many (if not most) of the styling tricks, tips, and best practices we read or write about can be abstracted into reusable utilities.
For a fine model of what I mean by "utility," consider the many functions of Underscore, the JavaScript "utility-belt" — and its offspring Lodash, of course (for this article, please just assume that "Underscore" = "Underscore or Lodash, whatever you prefer"). Let me explain: I've been reading Eloquent Javascript, by Marijn Haverbeke, and the other night I encountered a common, useful pattern called the "reduce" or "fold" function. In the tutorial tradition, Haverbeke explains what a "reduce" function does and shows me how to make one. So I could write my own — we could all write our own ... But Underscore already has a "reduce" function that we can all use — and since Underscore's function has run the open-source gauntlet, it's going to be better than whatever I might produce on my own (though I can't speak for you, in all your wisdom). As much as I benefit from the knowledge gained, I often gain even more by pairing that knowledge with an open-source utility.
In the world of style code, the best way to collaboratively create a similar utility collection is with a preprocessor library. (Two significant advantages of preprocessor tools over class collections are (1) that they have variability built in, and (2) that they only impact your final stylesheet, what's served to the client, when they are actually used.) So: enter Scut.
Let's parallel the JavaScript "reduce" example above with some style code. On CSS-Tricks, there's an immensely useful article, "Centering in the Unknown," about centering elements with indeterminate dimensions. The trickiest part is the vertical centering. After reading this article, I know about the method of setting
display: table; on the parent element and
display: table-cell; vertical-align: middle; on the to-be-centered child. And that's fantastic: it's a valuable trick to learn. But let's not stop there. To extend that tutorial and create a reusable, shareable utility, I can write a Sass mixin — something like this:
@mixin vertically-center ($child: ".vcentered") { display: table; & > #{$child} { display: table-cell; vertical-align: middle; } }
Apply this mixin to the parent; pass the to-be-centered child's selector as the argument (or give that child the default class
vcentered); and you have achieved vertical centering — and done so by creating a tool that can be reused and shared.
Essentially, we're doing the same thing with CSS (by way of Sass) that Underscore does with JavaScript. Put together a bunch of these utilities, expose them to the open-source community, and you should end up with a helpful library.
(By the way, Scut provides three different methods of vertical centering, each one fitted for different contexts.)
I'll explain more about the methodology of Scut's utilities below; but first, you may be asking ...
What About Existing Preprocessor Libraries?
If you're a regular reader of CSS-Tricks, you've probably heard of Compass and Bourbon. There are other Sass libraries, and LESS and Stylus have spawned their own. These libraries exist already, bolstered by strong communities, and work splendidly; they do offer "abstract, generic patterns and practices" — so why build another? Because, from what I've seen, the existing preprocessor libraries have focused heavily on vendor-prefixing and legacy-browser support, without offering many reusable style patterns. (Some, yes, but not many.) Valuable as they are, they are also, like all things under the sun, limited.
Their limitations jumped out at me when I started using Autoprefixer. (If you haven't done so already, I suggest reading Andrey Sitnik's guest post on CSS-Tricks.) I had tried Compass and was using Bourbon regularly; but with my vendor-prefixing taken care of by Autoprefixer, Compass and Bourbon no longer seemed very useful. They offered a few helpers that I would invoke now and again, but not regularly.
I started to wonder what else a preprocessor library might be good for. And that led to the idea behind Scut — a preprocessor library that ignores vendor-prefixing in order to focus exclusively on abstract styling patterns.
The Principles and Purposes of Scut
What Problems do Scut Utilities Solve?
Scut utilities should epitomize the key benefits of CSS preprocessors. I'll list my favorites:
The Key Benefits of The CSS Preprocessor — which are also The Key Benefits of The Scut Utility:
- It helps me avoid repetition. Instead of typing the same code in various places, I use a mixin, extend, function, or variable, and my code becomes less annoying to type; more accurate — less vulnerable to typos and inadvertent variations; and easier to change and maintain — since each important part resides in one place only.
- It helps me organize code, by grouping associated rules into named patterns — so instead of tangled lists of various rules contributing in various ways to a component's appearance, I see which rules relate to which specific effects.
- It helps me reuse code (as explained above).
Additionally, the pattern that a Scut utility implements should suffer from one or more of the following problems — and the utility should, of course, solve that problem:
1. The pattern is non-intuitive
The CSS rules required don't explain themselves. There's some kind of trick involved: you must have been initiated to decipher the code. Also, because there's a trick, the pattern is hard to remember. Unless you've executed the operation a hundred times already, you probably have to look up instructions on somebody's blog; and even then, you'll need to do some thinking, experimenting, and tweaking to get it right again.
To illustrate: You may want to create an element of fluid dimensions with a fixed aspect ratio — let's say 16/9. After some searching, you've found a method that works — but you may not see why just by looking at the CSS:
.parent-element { overflow: hidden; position: relative; } .parent-element:before { content: ""; display: block; height: 0; /* Huh? */ padding-top: 56.25%; /* Wha? */ } .parent-element > .child-element { position: absolute; left: 0; top: 0; width: 100%; height: 100%; /* Filling a container with zero height? */ }
Use a Scut mixin, instead, and a glance at your code will make sense:
.parent-element { @include scut-ratio-box(16/9, ".child-element"); }
The mixin organizes and names the pattern — and also, of course, saves you from repeating the complicated mess if you need a different ratio-box elsewhere.
For another example, consider the renowned CSS triangle. Without some explanation, the required style code is obscure. To make a blue right-pointing triangle 50px tall and 50px wide:
.triangle-right { width: 0; height: 0; /* A shape with no dimensions? */ border-top: 25px solid transparent; /* Why 25px here? */ border-bottom: 25px solid transparent; /* Who needs invisible borders? */ border-left: 50px solid blue; /* My right-pointing triangle is a left border? */ }
The trick is ancient and venerable, and well documented in tutorials around the web. (Chris Coyier recently produced a clever animation to explain how and why it works at all.) So maybe you've read some things, you get it, you pull it off yourself. Still, despite your magnificence, the benefit of a good mixin should be clear, to transform the code above into a single intelligible line:
.triangle-right { @include scut-triangle(right, 50px, blue); }
And what if you want to build a more complex shape that involves multiple triangles — triangles that are themselves a little more complicated? Then the mixin becomes even more valuable:
2. The pattern deserves a shorthand
The pattern may be easy enough to write yourself — not complicated, plenty intuitive — but it consists of a set of rules that can be usefully and regularly grouped into a named shorthand.
(Of course, vanilla CSS already incorporates some shorthands. Scut just adds more.)
For example, Scut includes some positioning mixins: instead of —
position: absolute; top: 1em; right: 2em; bottom: 3em; left: 4em;
— you can use
scut-absolute and write —
@mixin scut-absolute(1em 2em 3em 4em)
3. The pattern involves some important best practices
You may think you know how to do it yourself — but unless you're In The Know and have read all the right things, you may not be doing it the best way. And even if you knew the best way once, in your heyday, you may have since forgotten or missed some game-changing innovations.
There's nothing like an open-source library to take care of this problem. In fact, best practices is one of the areas where existing preprocessor libraries are pretty strong. So Scut's best-practice utilities — like
scut-font-face,
scut-clearfix, and
scut-hd-bp (for resolution-based media queries) — resemble some mixins you'll find in Bourbon and Compass.
4. The pattern is extremely common and a little annoying
You use the pattern consistently — every project, usually multiple times per project. And every time, something in your mind mutters "Again?" and a dark psychic cloud passes over your psychic sun, a transient awareness that you're a few keystrokes closer to death.
If I had a dime for every time I nullified
margin,
padding, and
list-style-type on an unstyled-list — O! the sandwiches I could buy —— So some of Scut's first utilities were
scut-list-unstyled and its common variations,
scut-list-inline and
scut-list-floated, exemplified below (with various "skins" applied, to demonstrate how an abstract utility should be able to apply in all kinds of design situations):
How Do You Make a Scut Utility?
In short: maximize reusability. Reusability is what distinguishes a library-ready utility from a project-specific one.
Include sufficient detail to implement the pattern, but no more. The utility alone should not produce a passable component. Again, Scut isn't about passing around well-constructed, finished designs: it's about facilitating the construction and finishing of unique designs.
Use arguments to allow for typical variations on the theme. Whenever reasonable, include conservative default values for those arguments — so users may not have to enter every argument every time — and arrange those arguments according to the order in which they're likely to be changed. Additionally, use
@content blocks, when they make sense, if you expect regular customizations that won't fit into arguments.
Namespace, to prevent conflicts with other libraries and project-specific code. Scut adds a
scut- prefix to all its pieces. That way, we can include a "clearfix" utility in Scut without worrying that it will conflict with Bourbon or Compass clearfixes (which aren't namespaced). And we can use generic utility names like "size" (
scut-size), generic variable names like "circle" (
scut-circle), without disturbing the natural balance.
Lastly: document thoroughly, document well. I'm trying hard to do that with Scut's docs — and I would, of course, appreciate your input and advice. We've all been frustrated by documentation — we've all known that pain — so we all recognize that the effective reusability of a tool directly relates to the quality of its documentation.
Now To Address Some Reservations
I don't use Sass
Whatever your workflow, whatever choices you've made, good or bad, Scut can probably help, at least a little. If you don't use Sass, you might still look into the open-source code and either port it (to your preprocessor-of-choice) or read it, along with Scut's documentation, as a series of mini-tutorials, a kind of style-pattern reference.
I Love OOCSS and Cannot Serve Two Masters
Object-Oriented CSS (OOCSS) and Scut address similar problems with similar solutions: namely, extendable patterns (or "objects"). But they are by no means the same. Perhaps you're an OOCSS aficionado, and you consider all these mixins and extends to be inefficient nonsense. You want a "clearfix" class, not a mixin that will duplicate code, or a bunch of `@extend` directives that will clutter your compiled CSS. You want to make your triangles with classlists like
triangle triangle-large triangle-down triangle-red, not one triangle mixin invoked multiple times with different arguments.
Well, that's OK. There's no need to argue here over the virtues of preprocessors versus those of class-heavy coding conventions, semantic versus presentational classnames, etc., because Scut doesn't preclude OOCSS-style coding, or any other style: simply summon Scut's utilities as needed to help create the classes for your objects and their extensions.
I Don't Like Some of Scut's Utilities
Let me know what needs to change (file an issue on Github), and we can work together to build a better Scut.
Keep in mind, also, that some of the current utilities are more experimental than others. As Scut stumbles through its unstable youth (v0.x.x), I'm looking for collaborators who are interested in figuring out what works and what doesn't, which utilities will improve a project's codebase and which might make it more cryptic and harder to maintain.
I Think This Whole Idea Is Stupid
Again, you're welcome to tell me what you would do differently. Show me how it's done. Or else you can go your separate way, do something you enjoy to cheer yourself up again — eat some pie, ride a bicycle — and forget you ever read this.
Curious? Convinced? Confused? Try Using and Contributing to Scut
I hope I've said enough, by now, to convince you to look into Scut, maybe tinker with it a little — or even, dare I wish, contribute.
If you're ready for a trial run, Scut's documentation will tell you how to install and apply the library. (Basically, use Bower or download the latest release on Github, then
@import into your Sass. Easy as can be.)
And if you're thinking you may want to donate some modicum of your own brilliance to the project, please don't hesitate. Go for it. Scut is a simple library, an easy open-source contribution — which could be especially nice for those of us who work primarily in HTML and CSS and feel wary of wading into other Github projects. Scut is all about making your work, my work, and the work of other developers easier, maybe even a little bit better; extending tutorials into reusable utilities; encouraging best practices; and sharing good ideas — goals we can agree on. I hope you'll find it a worthy experiment.
Nice article! Thank you.
Ah this looks like a great idea going to see if I can implement any of these soon! :) Thanks!
I have a feeling this is going to go down as a monumental article. It combines useful practices that are well thought out and easy to understand, implement, and extend. It’s a bit like taking the torch from SMACSS by Jonathan Snook and running with it in a very practical manner. Thanks David. I’m looking forward to helping Scut grow.
Nice !
It reminds me my Compass Recipes :)
Thanks for the tip — I hadn’t seem your collection of recipes before. I’ll take a look.
I was about to comment the same, you two should probably merge your efforts!
I’ve been working on a similar one myself, it’s called veRepo.
This to me seems to be the missing piece from the sass ecosystem. I am not sure how much value I can add but i will definitely be eager to dig into it.
Lovely stuff… I’m building up my own library of useful snippets. Absolutely love using SASS, really enjoying thinking of new things to build. Here’s a position short hand mixin, inspired by Hugo Giraudel’s offset mixin, I took a different approach though
I don’t really understand why I have to count to 5 in my loop..
anyhow, it does this
awesome!
It counts from 1 to 5, so it runs 4 times which is the length of
$args ()
Great! Here are the positioning mixins I’ve made for Scut, which are fundamentally similar to what you have going:
I use the mixin
scut-coordinatesto deal with the list of four coordinate values, then separate mixins extending that functionality for specific position values (
scut-absolute,
scut-relative,
scut-fixed).
I use these mixins all the time when I make sites. Simple as they are, I think they embody some of the key benefits of abstract Sass utilities.
I think this is a fantastic idea. Having read the documentation but not used Scut yet, I can see right away a few useful ideas, such as shapes, typography, functions and some of the layout ones.
However, I wanna caution against using shorthands such as the ones for margin, padding and positioning. While it does help us developers save a few lines of code, it comes at the expense of maintainability, when a new person coming on the project reading through the code, they might get confused at the unfamiliar syntax. The full CSS syntax is simple enough, albeit overly verbose.
I get your concern. I’m not yet sold on the margin and padding mixins, because, as you say, they add a layer over CSS that is already very simple, just a couple of lines — but they do reduce repetition, for the situations in which you want to add the same value to multiple margins; and I like being able to enter multiple margins in one line without overriding all the margins. You’re welcome to continue this conversation on Github — I’m very interested in hearing what other people think about this theoretical point.
(What would you think about making a margin/padding mixin that is just like the vanilla shorthand but with an
nvalue to avoid overwriting a side, e.g.
@include scut-margin(1em n)or
scut-margin(1em 2em 1em n)?)
However, I am sold on the positioning mixins: I find myself using them all the time — I think they make the code more organized, more readable, and the added layer (above vanilla CSS) is so thin and transparent that I don’t think it’s really a barrier for maintainability.
I must say that a part of me really likes this.. I can truly empathize with the feeling of a dark psychic cloud over my face almost every single time I style a meny. I just started using SASS and I will download SCUT and try it out..
On a different note; What I don’t like about this approach is the automatisation of knowledge. Of course to each his own but I want to really know what my code does and what it outputs. Using SCUT, SASS, LESS, Compass etc.etc. kind of takes away some of that. For someone who’s been in the business for some time this might not be so much of an issue but lets say a newbie comes along, decides to start coding and immediately installs SASS, Compass and SCUT. They’ll have so many solutions handed to them by non-explaining mixins etc. that they wont understand whats really going on (unless they actually open these up and check it out).
I’m just getting started with SASS and will try SCUT and I’m sure I’ll love it, but if a friend of mine ever comes along and asks me how to start learning coding website I’m not going to recommend any of these utilities until they’ve passed the intermediate-status.
I definitely get your concern. I’ve seen new programmers write entire JavaScript-heavy sites by cobbling together snippets and examples that they found online. And the site pretty much works! Later, when helping them debug something, it becomes clear that they don’t even understand what a for-loop is, or how to do the simplest string manipulation.
Then again, that’s exactly how I learned to write code.
It is easy to forget that we learn by copying examples and correcting mistakes. We don’t learn to write code by generating a solid understanding of all the extremely abstract concepts involved and then sit down and start writing perfect code.
Scut adds a really thin layer over the “real style code” that’s practically transparent. Furthermore, when you’re debugging something you wrote with Scut in a browser, you are looking at CSS code, driving home the knowledge that what you originally wrote is not “real code”, and at the same time teaching you something about the utility of utilities and what dependency really means.
Absolutely love your idea and admire that effort, infact looking forward for more for scut, as usaing regularly Compass/Sass i’m seriously confused and Scut sound really awsome , reusable thing is plus but it would be graet idea if scut define feature scope like copmass eg. @import “compass/css3” would import only those style for css3 that we wanna use , i guesss you understand what i’m asking it would be great if scut do same support. Moreover i’m worried about generated CSS styles, bcz if i use both compass and scutt they gonna creat too much their css and if i use foundation afterward then it’s gonna expand more, So, i’m looking more about scut with compass and foundation.Thanks
Glad to hear your enthusiasm. To address your concern: Since Scut only includes Sass mixins, placeholders, variables, and functions, no actual classes, it will not increase the bulk of your final compiled CSS with unused stuff — so you don’t really need to pick and choose which modules you import. (For instance, if you don’t use
scut-triangle, that code will not be found anywhere in your compiled CSS.) This is part of how Sass works — one of the nice things about preprocessors.
Frameworks like Foundation offer a whole bunch of classes because that makes it easier to plug-in their finished components, directly in your markup. So if you’re concerned about excess CSS, it’s a good idea to be specific about which Foundation modules you import (or with Bootstrap, you probably want to create a custom build when you know what you need).
That’s the whole behind these libraries, it’s to avoid situations like these:
You only use what you need.
I’m liking the concept (and well written article!). Just wondering if you’d consider adding some compatibility setting type logic… So for instance, if I don’t care about IE8, I can set that in a setting and
@mixin scut-center-absolutelywould use something like that instead:
Also, is there a way in SASS to reference the same mixin with 2 different names without duplicating the mixin? Back in the days, I made a textmate CSS bundle that used tab triggers like
lstnfor
list-style-type: none;(before Zen coding thank you very much… ;)
I think it would make Scut way better if we could use things like
@include scut-ca;in addition to the long version.
Thanks!
You could just create a mixin which references the scut mixin, passing in the same arguments.
A few interesting points here. I’ll respond to each one:
I would prefer not to establish “settings” unless they are really necessary and/or significant. With the utilities in Scut so far there really isn’t much that would change to drop IE8 support — so I don’t think a compatibility setting would be worth it at this time. Whether or not that changes down the road, we’ll see.
I hadn’t really thought about the
translatetechnique you bring up (looked it up on CSS-Tricks). Looks like the unique usefulness is in absolute vertical centering of elements with unknown height — right? Interesting … We would have to discuss what might be the best way to include vendor-prefixed properties in a Scut mixin …
I’ve also been thinking about short nicknames for mixins. Dave is right that it would be easy to do. It’s something worth bringing up on Github and seeing what other people have to say. I can see immediate objections similar to what Tri mentioned above: a nickname would add another layer between devs new to the code and the actual CSS. But it’s also true that you wouldn’t have to use the nickname if you were concerned about that in your situation … I wonder what other people think.
Yann, I just wanted to notify you that someone posted a pull request about this method. The conversation is here:. Feel free to participate!
Boom! You had me at scut-list-unstyled. :)
This is incredibly awesome. I’ve been amassing my own collection of similar stuff, but having it all documented, in one place and maintained by the community is just amazing.
I love you. And not even just in the Platonic sense!
Going through the project, I found one real candidate: reverse indent. It already surprised me once going back through my code, why would I do it this way? Then I needed it again, it’s useful to guide the eye in lists, inlined definition lists, and titles.
For example
Should be something like:
I’ll try to create an account on github sometime soon, but if someone comes around to it earlier, feel free to add.
I think that’s a fine idea — in fact, I believe that Scut already has what you’re looking for, by a slightly different name: “hanging indent”. Have a look:
Here’s the source code on Github. Feel free to offer suggestions for changes or additions. Thanks!
Really great utility library there David. If you don’t mind I’d like to suggest an improvement to the
scut-side-linedmixin. scut-side-lined mixin
I like that horizontal line effect on text, BUT what if you wanted to fade those lines instead of a solid color? I just added an option to have a gradient line if you wanted it.
Here’s the codepen:
Codepen Demo
Basically if you wanted that fade at the very least you type this.
Note: The arguments
$style, and
$doublehave no effect since it’s a background image and not a border, but the other arguments should still work.
Good tip, thank you!
I would say yeah for vertical centering. But the positioning mixin is less clear than the css in that you have to remember the order of sides rather than having named properties. That is clearly going in the wrong direction in my opinion, for little gain.
here’s mine position mixin – I absolutely love to work with it
Somehow the documentation on is crashin my ipad (safari) browser.
I had this problem early on but “fixed” it — in that I was no longer able to reproduce it, so believed it to be gone. I still can’t reproduce it — and I do know other people have accessed the site on iOS browsers without crashing. So … weird. I have received one other complaint about this problem, though, so I’m opening up an issue:
If anybody who knows more than me can figure out what’s going on and fix this issue, or offer some clues, your help would be much appreciated! | https://css-tricks.com/introducing-scut-new-sass-utility-library/ | CC-MAIN-2016-07 | refinedweb | 5,395 | 60.24 |
I first got interested in build tools implemented as embedded DSLS (Domain Specific Languages) by Martin Fowler's article on Rake [[1]]. Build languages like make or nant are classic DSLs, although the term 'little language' [[2]] has been around a lot longer and in fact is an important part of the Unix development philosophy of specialized tools that do one thing well..
I've always considered Lua to be a good language for embedded DSL applications, which leads to Bou. Bou (pronounced like 'beau') is a build system based on pure Lua - the only external dependency is on the LuaFileSystem? (lfs). It is deliberately similar to
make in philosophy and uses the same language of targets, rules and dependencies. However, it brings two powerful things to the party; the ability to use arbitrary Lua code and a great deal of canned knowledge about some common compile tools.
The English language is rapidly running out as a resource for good open-source project names - 'lake' would have been perfect, but alas there's already a build system called that! 'bou' is Afrikaans for 'build'; you put your targets and rules in a 'boufile'.
Consider an old friend:
#include <stdio.h> int main(int argc, char**argv) { printf("Hello, World - %d parms passed\n",argc); return 0; }
Writing a makefile for the canonical "Hello, World!" program is overkill, but the equivalent boufile is very straightforward:
c.program 'hello'
Alternatively, you can get Bou to deduce that you have a C program, and say this:
program 'hello.c'
Executing Bou will give the following output:
> bou gcc -c -O1 -DNDEBUG hello.c gcc hello.o -o hello.exe > bou bou: up to date
Which is not in itself very impressive. But this simple boufile gives you features for free: it already knows about 'clean', knows how to use the Microsoft command-line compiler (at least on Windows), and knows how to make a debug build:
> bou clean removing 1 hello.exe 2 hello.o > bou CC=cl cl /nologo -c /O1 /DNDEBUG hello.c hello.c link /nologo hello.obj /OUT:hello.exe > bou CC=cl DEBUG=1 cl /nologo -c /Zi /DDEBUG hello.c hello.c link /nologo hello.obj /OUT:hello.exe
Observe that it was not necessary to invoke 'bou clean' before doing a debug build, because Bou is intelligent enough to know that the build has changed. This is done using a specfile:
> cat boufile.spec link /nologo $(DEPENDS) /OUT:$(TARGET) cl /nologo -c /Zi /DDEBUG $(INPUT)By comparing the existing specfile to the commands generated, Bou can deduce that the commands have changed, and therefore require rebuilding.
For such a simple case, you can do without a boufile entirely, and let Bou deduce the tool needed to compile and run the file you specify:
> del hello.exe > bou hello.c 10 20 30 gcc hello.o -o hello.exe hello.exe 10 20 30 Hello, World - 4 parms passed
Notice that
hello.o was not regenerated!
Consider a program with two files,
one.c and
two.c, which is called
first.
c.program {'first',src='one,two'}
Running Bou, we get:
> bou gcc -c -O1 -DNDEBUG one.c gcc -c -O1 -DNDEBUG two.c gcc one.o two.o -o first.exe
This is not a very realistic situation - in practice, the source files will at least depend on some header files, and you will need to specify libraries. To specify more optional parameters, we use a common table idiom for passing 'named' parameters - note the curly braces:
c.program{'first',src='one,two', compile_deps='common.h',libs='user32,kernel32'}
We will now link properly against the required libraries, and if
common.h changes, the source files will be recompiled:
> bou gcc -c -O1 -DNDEBUG one.c gcc -c -O1 -DNDEBUG two.c gcc one.o two.o -luser32 -lkernel32 -o first.exe > bou CC=cl cl /nologo -c /O1 /DNDEBUG one.c one.c cl /nologo -c /O1 /DNDEBUG two.c two.c link /nologo one.obj two.obj user32.lib kernel32.lib /OUT:first.exe
libs gives Bou a list of libraries; it then decides how to format this list in the way appropriate for the particular tool. Other parameters include
incdefs, for setting a list of include paths, and
defines, for defining macros.
It is possible to say
src='*.c', but this doesn't handle the fact that each source file has individual dependencies.
One very common format for expressing dependencies is the 'deps' format emitted by tools like GCC, suitable for inclusion into a makefile. Bou can process such a format explicitly. Consider the following boufile:
-- bonzo.bou ]]}
The
rules parameter can be set to a filename, but if the string contains newlines it's assumed to be verbatim. Bou will do three things from this specification:
* generate targets based on the implicit rules it knows * extract the include paths * construct the dependency list for each target
> bou -f bonzo.bou
Notice how global library and defines settings can be set using
cpp.defaults.
Consider the common task of needing to build and run a number of test programs. These may require compilation (like C/C++) or can be directly interpreted. A boufile for a directory containing both C and Lua test programs could look like this:
target('all','c,lua') target('c',forall_results('*.c',go)) target('lua',forall_results('*.lua',go))
The first target 'all' explicitly depends on the targets 'c' and 'lua'; the dependencies for 'c' are the result of generating program build-and-run targets for all C files in this directory, individually handled by
go().
forall_results() is rather like
map, except that it can take a wildcard instead of an explicit list and can collect multiple results from each invocation of the function.
The
rule function is passed the input extension, the output extension, and a command to turn the input into the output file; the standard variables
INPUT and
TARGET are set for you. Rather than setting a global rule, it returns a rule set to which you add target names. In this example,
progs 'one' is short for
progs:add_target 'one'.
rule:add_target also has a second argument which can be used to pass explicit dependencies.
! progs = rule('.c','.o','gcc -c $(INPUT)') progs 'one' progs 'two'
The
target function takes three arguments, a name, any dependencies, and a command to be executed. The dependencies can be a list (a string will be converted automatically) or a set of dependencies, using
depends. If the dependencies argument is nil, then the target is unconditional. The command can either be a Lua function, or a string, in which case it is interpreted as a command to be run using the shell.
The
depends function is useful for defered calculation of dependencies. Here is a target which depends on the results of two target sets, which are only populated later:
progs = rule('.c','.o','gcc -c $(INPUT)') files = rule('.gif','.jpg','convert $(INPUT) $(TARGET)') target('all',depends(progs,files),function() print 'yes' end) progs 'one' progs 'two' files 'pool'
At the height of the XML craze, it would have been natural to encode build rules something like this:
<program name="first" compile_deps="common.h" libs="user32,kerner32"> one, two </program>
This is also a tool-agnostic notation, but it is not a very good programming notation. By making the build language a subset of a real programming language, doing non-standard extra things doesn't require 'jumping out of the DSL'.
Bou has a way to go before it can handle all the tasks expected of a build environment, including support for installation. But hopefully it is a good starting base, and also I hope it shows that Lua is excellently suited to this kind of 'little language' application.
[[3]] contains
bou.lua and some small example projects. Unzip this somewhere, and make sure that you have
lfs on your package cpath.
lua bou.lua -f hello.bou should now work; if no boufile is provided it will look for
boufile in the current directory. Then create a batch file
@lua <path-to-bou.lua> %*or script file, depending on your religion:
#!/bin/bash lua <path-to-bou.lua> "$@"(the
"$@"ensures that quoted parameters will be passed properly.) | http://lua-users.org/wiki/LuaBuildBou | crawl-001 | refinedweb | 1,377 | 65.62 |
Hi All,
This is my question:
Write a function that counts the number of times it is called. Name the function count_it(). Do not pass it anything. In the body of count_it(), print the following message:
The number of times this function has been called is: ###
where ### is the number. (Hint: Because the variable must be local, make it static and initialize it to zero when you first define it.)
Here is what I did... Is there any way to make it better? different way?
Thank you
Code:#include <iostream> using namespace::std; count_it(); //prototypes second(); main() { count_it(); second(); return 0; } count_it() // this function counts how many time it has been called { static int count = 0; count++; cout << "The number of times this function has been called is " << count << "\n"; return 0; } second() //another function that calls count_it() { count_it(); return 0; } | http://cboard.cprogramming.com/cplusplus-programming/66848-variable-scope.html | CC-MAIN-2014-35 | refinedweb | 141 | 79.19 |
#include <db.h> int DB->remove(DB *db, const char *file, const char *database, u_int32_t flags);
The
DB->remove()->remove() method should not be called if the remove is
intended to be transactionally safe; the
DB_ENV->dbremove() method
should be used instead.
The
DB->remove() method may not be called after calling the
DB->open() method on any
DB handle. If the
DB->open() method has already
been called on a DB
handle, close the existing handle and create a new one before calling
DB->remove.
()
The DB handle may not be
accessed again after
DB->remove() is called, regardless of its
return.
The
DB->remove()
method returns a non-zero error value on failure and 0 on success.
If the database was opened within a database environment, the
environment variable
DB_HOME may be used as the path of the
database environment home.
DB->remove() is affected by any database directory specified using the
DB_ENV->set_data_dir()
method, or by setting the "set_data_dir" string in the environment's
DB_CONFIG
file.
The
DB->remove()
method may fail and return one of the following non-zero errors:
If the method was called after DB->open() was called; or if an invalid flag value or parameter was specified.
Database and Related Methods | http://docs.oracle.com/cd/E17275_01/html/api_reference/C/dbremove.html | CC-MAIN-2015-18 | refinedweb | 208 | 58.62 |
Good evening,
Is it possible to use an onClick method as a prop in a mapped component? Here is the code:
const newArr = [ { name: 'John', age: 25 }, { name: 'Sam', age: 23 } ] const {useState} = React const ListOfPeople = () => { const [display, setDisplay] = useState('') return ( <div> <h1>{display}</h1> {newArr.map(person,id) => <ShowNames name={person.name} id={person.id} age={person.age} onClick ={() => setDisplay(person.age)}/>} </div> ) } const ShowNames = ({name, age}) => { return ( <div>{name} is {age} years old</div> ) }
As a result, I would like to see a small list of ‘x is x years old’ as well as being able to click on a child component and see its age. Am I going about this the right way? | https://forum.freecodecamp.org/t/onclick-on-mapped-components/491445 | CC-MAIN-2022-05 | refinedweb | 116 | 62.88 |
Hi,
My problem is that any program that I create involving entering of data by the user,in other words,programs having command line, std::cin>> turn themselves off and the dos window shuts down before the printing of the final calculated answer.
Note that this is not the case where the window pops for a split second,I am aware of the cin.get(); command.
For example,
#include <iostream>
int main()
{int x;
int y;
std::cout<<"I no.:";
std::cin>>x;
std::cout<<"\nII no.:";
std::cin>>y;
std::cout<<"\nSum is:<<add(x,y)<<std::endl;
cin.get();
return 0; }
int add(int x, int y)
{return (x+y) }
The program will shut itself before showing the sum.However,this will not happen if I assign values to x and y in the program itself.
Please suggest me a remedy or else all my hopes of learning c++ will be in vain. | http://cboard.cprogramming.com/cplusplus-programming/37306-disappearing-act.html | CC-MAIN-2015-35 | refinedweb | 155 | 71.85 |
I figured it’d be neat to show you how my plasmoid works so you could use it when developing your own plasmoids. Here’s the main.py of my data engine. The indentation is off, in case you try to copy and past this in.
Here are the imports:
from PyQt4.QtCore import *
from PyKDE4.kdecore import *
from PyKDE4 import plasmascript
#for flickr
import views
Those are pretty standard. The last one is the part of my engine that interacts with flickr. Right now I have some work to do to get that presentable, but all you need to know is that it outputs XML to this main part of the data engine.
class PyFlickrEngine(plasmascript.DataEngine):
def __init__(self,parent,args=None):
plasmascript.DataEngine.__init__(self,parent)
def init(self):
self.setMinimumPollingInterval(333)
#for flickr
views.initialize()
The above is mostly standard. Below are the sources. These are the sources you’ll present to any plasmoids that want to grab from your data engine.
def sources(self):
sources = [“25”, “50”, “75”, “100”, “200”, “300”, “400”, “500”, “600”, “700”, “800”, “900”, “1000”, “1250”, “1500”, “1750”, “2000”,”3000″, “4000”, “5000”, “10000”]
return sources
The following is also pretty standard:
def sourceRequestEvent(self, name):
print “source request event” #debugging
return self.updateSourceEvent(name)
Here’s the main part of the engine. This is how the data actually ends up in the data engine. So I’m updating all of my sources here:
def updateSourceEvent(self,group):
print “updateSourceEvent”
#grouplist = []
if group == “25”:
print “i’m @ 25” #debug
grouplist = views.analyzeviews(views.views25, views.views50)
#self.setData(grouplist, “Group List”, QVariant.List) #original line
self.setData(“25”, “Group 25”, grouplist)
elif group == “50”:
print “i’m @ 50” #debug
grouplist = views.analyzeviews(views.views50, views.views75)
self.setData(“50″,”Group 50”, grouplist)
elif group == “75”:
print “i’m @ 75” #debug
grouplist = views.analyzeviews(views.views75,views.views100)
self.setData(“75″,”Group 75”, grouplist)
elif group == “100”:
print “i’m @ 100” #debug
grouplist = views.analyzeviews(views.views100,views.views200)
self.setData(“100″,”Group 100”, grouplist)
elif group == “200”:
print “i’m @ 200” #debug
grouplist = views.analyzeviews(views.views200, views.views300)
self.setData(“200″,”Group 200”, grouplist)
elif group == “300”:
print “i’m @ 300” #debug
grouplist = views.analyzeviews(views.views300, views.views400)
self.setData(“300″,”Group 300”, grouplist)
elif group == “400”:
print “i’m @ 400” #debug
grouplist = views.analyzeviews(views.views400, views.views500)
self.setData(“400″,”Group 400”, grouplist)
elif group == “500”:
print “i’m @ 500” #debug
grouplist = views.analyzeviews(views.views500, views.views600)
self.setData(“500″,”Group 500”, grouplist)
elif group == “600”:
print “i’m @ 600” #debug
grouplist = views.analyzeviews(views.views600, views.views700)
self.setData(“600″,”Group 600”, grouplist)
elif group == “700”:
print “i’m @ 700” #debug
grouplist = views.analyzeviews(views.views700, views.views800)
self.setData(“700″,”Group 700”, grouplist)
elif group == “800”:
print “i’m @ 800” #debug
grouplist = views.analyzeviews(views.views800, views.views900)
self.setData(“800″,”Group 800”, grouplist)
elif group == “900”:
print “i’m @ 900” #debug
grouplist = views.analyzeviews(views.views900, views.views1000)
self.setData(“900″,”Group 900”, grouplist)
elif group == “1000”:
print “i’m @ 1000” #debug
grouplist = views.analyzeviews(views.views1000, views.views1250)
self.setData(“1000″,”Group 1000”, grouplist)
elif group == “1250”:
print “i’m @ 1250” #debug
grouplist = views.analyzeviews(views.views1250, views.views1500)
self.setData(“1250″,”Group 1250”, grouplist)
elif group == “1500”:
print “i’m @ 1500” #debug
grouplist = views.analyzeviews(views.views1500, views.views1750)
self.setData(“1500″,”Group 1500”, grouplist)
elif group == “1750”:
print “i’m @ 1750” #debug
grouplist = views.analyzeviews(views.views1750, views.views2000)
self.setData(“1750″,”Group 1750”, grouplist)
elif group == “2000”:
print “i’m @ 2000” #debug
grouplist = views.analyzeviews(views.views2000, views.views3000)
self.setData(“2000″,”Group 2000”, grouplist)
elif group == “3000”:
print “i’m @ 3000” #debug
grouplist = views.analyzeviews(views.views3000, views.views4000)
self.setData(“3000″,”Group 3000”, grouplist)
elif group == “4000”:
print “i’m @ 4000” #debug
grouplist = views.analyzeviews(views.views4000, views.views5000)
self.setData(“4000″,”Group 4000”, grouplist)
elif group == “5000”:
print “i’m @ 5000” #debug
grouplist = views.analyzeviews(views.views5000, views.views10000)
self.setData(“5000″,”Group 5000”, grouplist)
elif group == “10000”:
print “i’m @ 10000” #debug
grouplist = views.analyzeviews(views.views10000, views.views10000)
self.setData(“10000″,”Group 10000”, grouplist)
return True
And, finally, initializing the engine – a standard part:
def CreateDataEngine(parent):
return PyFlickrEngine(parent)
As you can see, writing a data engine in python is pretty simple. Most of the work is done in the other python file, but the data engine part is so simple, eh? Between this and the official tutorial you should be in pretty good shape. | http://www.ericsbinaryworld.com/2012/02/15/developing-my-first-plasmoid-the-data-engine-in-python/ | CC-MAIN-2020-05 | refinedweb | 760 | 58.58 |
In this tutorial we’ll discuss and implement iOS UI Navigation Controller. It’s another common UI element that’s used as the base for many iOS apps.
Table of Contents
A Navigation Controller also holds a UIView class instance. The primary use of a navigation controller is to create and hold a hierarchy of view controllers in a stack(officially termed as navigation stack). In others words the Navigation Controller maintains a history of View Controllers the user has browsed through. A Navigation Controllers view consists of many subviews that include a navigation bar at the top ( which contains the optional title, back button and other bar buttons), a custom content view and an optional toolbar at the bottom.
To setup a navigation controller, select the initial view controller in your storyboard and go to Editor>Embed In>Navigation Controller. The storyboard would look like this:
We’ll need to add View Controllers to the storyboard to bring the Navigation Controller in use. Before we do that we’ll discuss segues that are an important component for moving across View Controllers.
Segues
Segues provide a mechanism to connect two View Controllers/scenes. There are many kinds of segues.
- Show/Push : This pushes the next View Controller onto the navigation stack thereby allowing the user to click the back button to return to the previous screen through the back button on the top left of the Navigation Bar.
- Show Detail : The next view controller content is present in the details area if it’s a master detail screen (UISplitViewController). Else if it’s not the master detail type then the current content is replaced with the new one.
- Present Modally : This animates the next transition on the screen in a presentation style that is chosen from the list of styles present( or a custom one). Typically the next views transitions into the screen from bottom to upwards. In cases of iPad it centers itself in the middle of the screen with the previous view controller content in background.
- Popover presentation : On an iPad, this shows the new View Controller over the previous one in a smaller box, usually with an arrow pointing to which UI Element created the popover. When used on an iPhone, it is not much different than the Present Modally segue by default, but can be configured to act more like an iPad one.
- Custom : We can define our own behaviour for this type of segue.
The Segue object belongs to the class UIStoryboardSegue.
To pass data from one ViewController to another, we’ll have to override
prepareForSegue function.
The show/push type of segue has a default back button in the navigation bar of the Child View Controller.
For the other type of segues we need to add an Unwind Segue method (more on this in later tutorials). The unwind segue method is created by adding an IBAction button with parameters as UIStoryboardSegue in the Parent View controller.
In this application we’ll add a Second View Controller that comes up from the first View Controller using segues. We’ll add a UITextField where the user enters the value that’s passed and displayed in the next view controller.
Control+ click and drag the button to the Second View Controller. Chose push as the manual type of segue.
The screen should look like the one given below.
Notice the segue symbol between the two View Controllers. The symbol is different for different type of segues.
Focus the segue symbol and name the segue identifier as “mySegue”.
Add a new Cocoa class file for the Second View controller (it should be a subclass of UIViewController. We’ve named it here as
SecondScreen.swift. Select the Second View Controller and link the class name in the Identity Inspector as shown in the image below.
Project Structure
The
SecondScreen.swift file is for the Second View Controller.
The
info.plist file is a list of properties and it provides another method for storing information for our app.
Code
ViewController.swift
import UIKit class ViewController: UIViewController,UITextFieldDelegate { @IBOutlet var textToPass: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. textToPass.delegate=self } override func viewWillAppear(animated: Bool) { self.navigationItem.title = "First Screen" } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { self.navigationItem.title = nil if segue.identifier == "mySegue"{ let s = segue.destinationViewController as! SecondScreen s.studentName = self.textToPass.text } } func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. { textField.resignFirstResponder() return true; } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { textToPass.resignFirstResponder() self.view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
In the above code we’ve added the UITextFieldDelegate Protocol for handling the UITextField methods.
We’ve handled the UITextField such that the keyboard should be dismissed if tapped outside or return key is pressed. Notice the difference in the code from the one we wrote for Objective-C.
@IBOutlet var textToPass: UITextField!
The ! mark means that the var value is strictly of type UITextField and it cannot be null.
textToPass.delegate=self
The above statement programmatically assigns the delegate of the UITextField to the view controller itself. It’s similar to Control+dragging the textfield to the dock in the storyboard.
The prepareForSegue is the most important method in this class. Let’s look into it.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { self.navigationItem.title = nil if segue.identifier == "mySegue"{ let s = segue.destinationViewController as! SecondScreen s.pass = self.textToPass.text } }
The next screen shows a back button by default only when the previous screen doesn’t contain a title. Else the back text of the next screen would be replaced with the title of this screen.
Hence we’ve assigned the title to null. The segue identifier string should be the same as the one declared in the storyboard.
s.studentName = self.textToPass.text
The
pass string is an instance variable of the SecondScreen.swift. What we’ve done here is assign the instance variable of the
SecondScreen.swift class to the text the user types in the textfield here.
SecondScreen.swift
import UIKit class SecondScreen: UIViewController { var pass:String? @IBOutlet var textReceived: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if let name = pass { if name.characters.count>0 { textReceived.text = name } } } }
This class just displays the
pass string in the UILabel on the screen only if the user had typed in the UITextField widget, else it shows the default label string.
The output of the application in action is given below.
This brings an end to this tutorial. You can download the iOS NavController project from the link below. | https://www.journaldev.com/10602/ios-navigation-controller-and-segues | CC-MAIN-2021-25 | refinedweb | 1,123 | 57.87 |
- 23 Mar, 2018 17 commits
Update Prettier Print Width to 100 See merge request gitlab-org/gitlab-ce!17953
Resolve "Limit number of failed logins using LDAP for authentication" Closes #43525 See merge request gitlab-org/gitlab-ce!17886
Request Chinese Traditional proofreader permissions. See merge request gitlab-org/gitlab-ce!17762
Show gitaly address instead of disk path See merge request gitlab-org/gitlab-ce!17954
Fix issuable state indicator Closes gitlab-ee#4683 See merge request gitlab-org/gitlab-ce!17878
- Jacob Vosmaer authored
Resolve "Indicate supported image formats in avatar error" Closes #43771 See merge request gitlab-org/gitlab-ce!17747
- Tim Zallmann authored
- Kamil Trzciński authored
Merge branch '43482-enabling-auto-devops-on-an-empty-project-gives-you-wrong-information' into 'master' Resolve "Enabling Auto DevOps on an empty project gives you wrong information" Closes #43482 See merge request gitlab-org/gitlab-ce!17605
Route path lookups through legacy_disk_path See merge request gitlab-org/gitlab-ce!17743
- Filipa Lacerda authored
Rename modal.vue to deprecated_modal.vue See merge request gitlab-org/gitlab-ce!17438
- Jan Provaznik authored
Increase the memory limits used in the unicorn killer Closes gitlab-com/infrastructure#19 See merge request gitlab-org/gitlab-ce!17948
-
- DJ Mountney authored
These limits were updated in our docs, and in omnibus some time ago. But the defaults in the source-install were missed.
- 22 Mar, 2018 23 commits
- Kamil Trzciński authored
Use porcelain commit lookup method on CI::CreatePipelineService Closes charts/helm.gitlab.io#291 See merge request gitlab-org/gitlab-ce!17911
Added prettierignore file Closes #44483 See merge request gitlab-org/gitlab-ce!17907
- Jacob Schatz authored
Disable webpack scope hoisting in development See merge request gitlab-org/gitlab-ce!17942
- Toon Claes authored
When the database is in a read-only state, display a banner on each page informing the user they cannot write to that GitLab instance. Closes gitlab-org/gitlab-ce#43937.
UI breakdown of message of the last pushed branch for Create merge request Closes #44382 See merge request gitlab-org/gitlab-ce!17821
- Jacob Schatz authored
Resolve "Some dropdowns have two scroll bars." Closes #43273 See merge request gitlab-org/gitlab-ce!17665
- Dennis Tang authored
- Fabian Schneider authored
Fix the other "A copy of ..." error for ReadOnly Closes #44365 See merge request gitlab-org/gitlab-ce!17935
Add the /help page in robots.txt Closes #44433 See merge request gitlab-org/gitlab-ce!17928
make a little more obvious what operations might need downtime or enhanced migration techniques See merge request gitlab-org/gitlab-ce!17927
- rubyjunkie authored
- Lin Jen-Shin authored
Same strategy with: See: Frankly I don't really understand how this works and I don't really care either. However I tried it and it does the job. To try this, make sure you have pending migrations, and run the server, hit the site. It would tell you that there's pending migrations, and then run migrations, and then hit the site again. Without this patch, Rails would complain that "A copy of ...", with this patch, it works without problems.
Tracks the number of failed attempts made by a user trying to authenticate with any external authentication method
- Takuya Noguchi authored
- Phil Hughes authored
Poor UX with branch whose name is very long on Branches Closes #44386 See merge request gitlab-org/gitlab-ce!17832
Backport 4006 add weight indicator to issues board See merge request gitlab-org/gitlab-ce!17923
Merge branch 'leipert-42037-long-instance-names-group-names-covers-namespace-dropdown' into 'master' Prevent overflow of long instance urls during Project creation Closes #42037 See merge request gitlab-org/gitlab-ce!17717
- Lukas 'Eipi' Eipert authored
- Alejandro Rodríguez authored
Before we were using a "plumbing" Gitlab::Git method that does not go through Gitaly migration checking. | https://gitlab.com/gitlab-org/gitlab-foss/commits/5b6931b8e70dbd1c67233cb5f64a553e3ce7e465 | CC-MAIN-2019-43 | refinedweb | 634 | 57.98 |
Mail::Box-Overview - objects used by Mail::Box
The MailBox package is a suite of classes for accessing and managing email folders in a folder-independent manner.
This package is an alternative to the
Mail::Folder and
MIME::* packages.
It abstracts the details of messages,
message storage,
and message threads,
while providing better performance than older mail packages.
It is meant to provide an object-oriented toolset for all kinds of e-mail applications,
under which Mail User-Agents (MUA) and mail filtering programs.
This package is modular --parts of it can be used independently of the rest. For example, the Mail::Box::Manager can automatically determine that a folder is in Mbox format and return an object of the Mail::Box::Mbox class, or the user program can bypass the manager and create Mail::Box::Mbox objects directly. Similarly, if the user program is only manipulating a single message, a Mail::Message.
The Mail::Box package has special features to help MUA's access folder data quickly in random order. You will not really benefit (neither slower) if you need the full folder sequentially.
You may want to have a look at the sample scripts in the
scripts directory.
Mail::Box::Manager objects play a central role in any program which is built with MailBox. Each program will create one manager, and then open folders via that manager. Besides folders, the manager can also be used to discover message threads: sequences of messages with their follow-ups.
<has-a> Mail::Box::Mbox Mail::Box::Manager <---------* (Mail::Box::MH) ^ : (Mail::Box::Maildir) | (maintains) (Mail::Box::POP3) | : | : `---------------------* Mail::Box::Thread::Manager (<has-a>)
Each folder maintains a list of messages. Much effort is made to hide differences between folder types and kinds of messages. Your program can be used for MBOX, MH, Maildir, and POP3 folders with no change at all (as long as you stick to the rules).
Mail::Box::Mbox <-----------* Mail::Box::Mbox::Message ^ <has-a> ^ | <isa> | <isa> | | Mail::Box ............. Mail::Box::Message ^ | <isa> | Mail::Message / \ <has-a> / \ Mail::Message Mail::Message ::Body ::Head
The situation for MH and Maildir folders is a little more complicated, because they have an extra intermediate level of abstraction: Mail::Box::Dir. The POP3 folder has an intermediate Mail::Box::Net.
In the future, when more Mbox-like folder types get implemented, there may be a Mail::Box::File level too. The following is also true for the mail boxes
MB::MH::Message MB::POP3::Message \ MB::Maildir::Message / \ / / \ / MB::Mbox::Message / \ / | / MB::Dir::Message | MB::Net::Message \ | / \ | / MB::Message | | Mail::Message
The mailbox manager Mail::Box::Manager encapsulates folder management issues. It maintains a set of open mail folders (mailboxes), and provides methods for opening and closing them, efficiently moving messages between folders, and efficiently appending messages to folders. It contains Mail::Box objects which may be of different types. Most folder types can be detected automatically.
The main manager also manages message-thread detector objects, and informs them when the contents of a folder have changed. This manager class is the only one you instantiate yourself: objects of all other classes will be provided by your folder manager.
You are strongly advised to use this object, but you can often do without it and open a specific folder-type directly.
A base class that defines an interface for manipulating the head and body of a message. There are various header object types (Mail::Message::Head's) and a bunch of body object types (Mail::Message::Body's).
The Mail::Message::Construct package is loaded when more complex tasks have to be performed on messages, like creating replies, bounces, or a forward message. These functionalities are described and implemented in the ::Construct file, but are automatically added to the Mail::Message namespace when used.
Message types which are foreign to MailBox can be used in the MailBox environment: there are some converters implemented via Mail::Message::Convert. Particularly the popular Mail::Internet and MIME::Entity are supported.
An abstract base class which defines an interface for mail messages which are stored in any folder. It inherits from Mail::Message, and adds the basic idea of location to a message.
This is the base class for all message bodies. It describes what you can do with any kind of body. The body types differ on the way how the keep the body content during the run of your program.
One special case of the body types is the Mail::Message::Body::Multipart, which contains a set of Mail::Message::Part objects. These are just like normal messages, except that they are contained in an other message. The Mail::Message::Body::Nested body type is comparible, but contains only one message: they are used for
message/rfc822 message encodings.
When needed, the functionality of the body objects is extended with Mail::Message::Body::Construct and Mail::Message::Body::Encode. The former package implements things like concatenation, the later controls message encoding and decoding. In the current implementation this is limited to transfer encodings (implemented in the Mail::Message::TransferEnc packages). Automatic character and mime recodings are on the wish-list.
The header for a single message. Maintains a set of Mail::Message::Field objects, each containing one header line. Fields are the only objects which have no logging and tracing facilities, purely for reasons of performance.
The header object has three sub-classes: the Mail::Message::Head::Complete version knows all lines for sure, Mail::Message::Head::Subset maintains an unknown subset of lines, and the Mail::Message::Head::Delayed has no lines yet but knows where to get them.
The latter two will automatically get the missing header lines from the mailbox files when needed, and so transform into a
::Complete header. It is fully transparent to the user of MailBox in which shape the header really is on the moment.
A base class that defines a standard interface for mail boxes which is independent of mailbox type. Objects of this class contain a Mail::Box::Locker and a list of Mail::Box::Message objects.
The base class for all folders which use a directory organization: each message is a separate entity (file) grouped in a directory. Each Mail::Box::Dir::Message represents one message, one such entity.
The base class for all folders which have the messages outside direct reach of the MailBox library, for instance on a remote system, or in a database.
This class derives from Mail::Box, and implements its interface for mbox-style folders. It maintains a set of Mail::Box::Mbox::Message objects, which are derived from a Mail::Box::Message.
Mbox-style folders have one file containing multiple messages per folder. When folders get large, access tends to get slow.
This class derives from Mail::Box::Dir, and implements its interface for MH-style folders. It maintains a set of Mail::Box::MH::Message objects, which are derived from a Mail::Box::Dir::Message.
MH-style folders are represented by a directory, where each message is stored in a separate file. The message files are sequentially numbered. It is fast to open one single message, but hard to get an overview.
The base class for MH mailbox indexes which provides methods for reading, writing, and managing message indexes. These indexes are used to speed-up access to directory based folders.
Also for efficiency reasons, a separate file is maintained which contains flags about the messages. This file for instance lists new files. This way, the MH message files do not have to be opened to find that out.
Like the MH folder type, this class derives from Mail::Box::Dir. It implements its interface for Maildir-style folders. It maintains a set of Mail::Box::Maildir::Message objects, which are derived from a Mail::Box::Dir::Message.
Implements the POP3 protocol based on Mail::Box::Net. The Mail::Transport::POP3 implementation handles the protocol details. In this kind of folders, you can only read and delete messages.
Maintains a set of message-threads over one or more folders. A message-thread is a start message with all the replies on it. And the replies on replies, and so on. This object is used to construct the thread for a set of open folders.
This object maintains linked lists of Mail::Box::Thread::Node objects. Mail::Message::Dummy's fill-up some holes.
Provides a folder locking interface which is inherited by the Mail::Box class. Currently it supports dot-file locking (
filename.lock), flock filehandle locking, and locking over NFS. Each is implemented in a separate class. A multi-locker, using a set of lock-methods at the same time is also available.
The set of search packages implement various search techniques in an uniformal way. Although implementing your own search algorithm is simple in general, in practice multiparts, encodings, and mime-types complicate things.
The parser reads messages, and transforms them into data-structures such that the content of header and body can be used within the program. The first parser is implemented in pure Perl. A second parser is under development, and will written in C, to gain speed.
Provides hash (Mail::Box::Tie::HASH) or array tied (Mail::Box::Tie::ARRAY) access to any mail folder derived from Mail::Box. This beautifies your code in some applications.
Various ways of sending and receiving messages are implemented. Sending is possible via external programs, like
Mailx,
sendmail, or autonomously with direct SMTP. Receiving is currently only implemented via POP3.
A debugging and logging class which is inherited by most of the Mail:: modules. For each object, you can say what log and error reports must be kept or directly presented to the user. This way you can decide to have Mail::Box report about problems, or do it all yourself.
All classes are written to be extensible.
This module is part of Mail-Box distribution version 2.118, built on February 26, 2015. Website:
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See | http://search.cpan.org/~markov/Mail-Box/lib/Mail/Box-Overview.pod | CC-MAIN-2015-18 | refinedweb | 1,680 | 56.86 |
cannot ping any neutron router interface
I am trying to install openstack using the instructions given in this link...
I am not able to ping the subnet from my controller node. I have a three node setup, all of which are virtual machines with single nics. I am running these VMs on VMware workstation. On my controller node, I can see that all the agents are active, as mentioned in the document. On the network node, I have 3 namespaces, a router namespace and two dhcp namespaces. The setup is as follows
I can ping the gateway to the external net from router namspace. I can also ping the subnet interface from router. However, I am not able to ping the subnet (192.168.1.1) from controller. Neither could I ping controller from router.
The output of 'ip a' is at The output of 'ovs-vsctl show' is at
Can someone help me fix this issue?
Whats your ICMP rule, make sure it's not disabled, Check Access- Security Tab
I checked that! It is enabled :) | https://ask.openstack.org/en/question/61418/cannot-ping-any-neutron-router-interface/ | CC-MAIN-2021-04 | refinedweb | 177 | 84.37 |
Subject: [boost] [function] new implementation
From: Domagoj Saric (dsaritz_at_[hidden])
Date: 2010-10-30 08:53:42
Hi,
<...those that followed the latest function related discussions can skip the
first paragraph...>
For about a year and half now (or even more but that's about how long I've
been involved in the matter) there have been repeated
discussions/requests/complaints about various aspects of Boost.Function.
Most of those fall into one or more of these categories:
- overall code speed overhead
- overall code bloat overhead
- lack of configurability
- dependencies on RTTI and exception handling
with the most frequently brought up specific issue being the various
implications (in all of the above mentioned areas) of the hardcoded
throw-on-empty behaviour...
Unfortunately Boost.Function code remained virtually unchanged (except for
the added RTTI emulation for platforms w/o RTTI support) with all of the
issues still remaining...
The new implementation proposal @:
Objects
solves or at least provides drastic improvements for all of the mentioned
issues.
It is intended as a drop in replacement for the current implementation and
as such I have so far tested it in the following ways:
- compiling some real world code: VC10, GCC 4.2.1, LLVM-GCC 4.2.1, GCC
4.5.1, GCC 4.6, Clang 2.0, Clang 2.8
- compiling and running a real world project: VC10, Clang 2.8
- building Boost trunk: VC10, GCC 4.2.1, GCC 4.5.1, Clang 2.0
- running Boost regression tests for Function, Signals, Signals2, Thread,
Program Options and Graph libraries: VC10, GCC 4.2.1, Clang 2.0.
(All of the tests passed except for two bogus assertion failure boxes that
pop up with VC10 and the Program Options tests during the automated
regression test procedure that OTOH do not popup when I run the same tests
manually through the VC10 IDE, i.e. the tests finish successfully...I tried
to make sure all the relevant compiler switches were the same in both cases
so I am out of ideas what else can make the difference.....)
Next, let me give you a comparison of for-size-optimized code generated by
VC10 with both the current and the proposed implementation for a short code
snippet demonstrating invocation, construction and assignment:
struct X
{
int foo( int const x ) const { return x + y; };
int y;
};
int main( int /*argc*/, char * * /*argv*/ )
{
using namespace boost;
X x;
function<int(int)> foof( boost::bind( &X::foo, &x, _1 ) );
foof( 0 );
function<int(int)> barf;
barf = foof;
barf( 1 );
return 0;
}
Notice in new_function_code_listing.txt how all of the wrapper code in the
new Function was completely transparent to the compiler and was completely
inlined to relatively simple machine code with direct calls to/through the
vtable pointers...while OTOH in current_function_code_listing.txt the code
generated for the "barf = foof;" assignement alone is several times larger
than the entire code generated for the new Function implementation.
The small asm snippet of the generated invoker/'thunk'/'trampoline' code
also demonstrates the effects of various tweaks done to minimize or all
together remove the need for any stack adjustment on the invoker side...
The new implementation of course has the same semantics and exception safety
guarantee levels as the original/current one.
Listing all of the improvements and detailed implementation changes here in
the first post would be quite cluttering as they are quite numerous. Those
that desire more tests and details right now, can follow this trail:
As for the dependencies issue this is solved in several ways:
- use of exception handling: new code uses guard objects instead of
explicit exception handling and provides a way to change on-empty-behaviour
so that the EH code/dependency can easily be removed/disabled
- use of RTTI (for getting the type of the stored function object): this
can be globally disabled with the BOOST_FUNCTION_NO_RTTI macro.
BOOST_NO_RTTI is not used for this purpose for backward compatibility
reasons: in the current implementation it actually turns on RTTI
emulation...The idea is to also add per instantiation RTTI on-off
configurability...
'Configurability' will probably be the most controversial issue/change
because it required the addition of an extra template parameter through
which an MPL list of policies can be specified at compile-time. This
parameter is properly defaulted to allow existing code to compile without
changes while providing current Boost.Function behaviour (e.g. on-empty-
behaviour). As all the performed tests showed this to also be true in
practice the proposed code should IMO go in as a straight drop-in
replacement but, of course, I might have missed some important higher level
detail/concern so this is open to discussion...
Currently two policies are supported:
- on throw behaviour (with throw-on-empty, nop-on-empty and assert-on-empty
handlers provided)
- whether the function instantiation should mark itself (i.e. its
operator()) as nothrow.
Additional policies my be added later, for example:
- sizeof and/or alignment of the SBO buffer
- default allocator
- per instantiation RTTI on/off
...
Finally, there is one more addition, somewhat 'unholy' as it brings in the
concept of binding into Boost.Function but considering its efficiency and/or
verbosity benefits (and the fact that the first issue can be 'explained
away' by saying that this is not actually 'binding' but a workaround for the
lack-of-delegates-support C++ language deficiency).
The addition is in the form of two more assign() member function overloads
(one for a free function that has the exact signature as the Boost.Function
instantiation, and one for a member function that has a matching signature
with the addition of a this pointer) that allow assignment of (suitably
typed) plain (free or member) functions specified as non-type-template
parameters. This allows for the removal of the extra
indirect-call-through-function-pointer otherwise incurred by traditional
assignment of function pointers (not functors), which is actually a rather
common use case. For example, in the above example given, one can now write:
foof.assign<X, &X::foo>( x );
and get a trivial invoker with the X::foo() target function inlined straight | https://lists.boost.org/Archives/boost/2010/10/172593.php | CC-MAIN-2020-29 | refinedweb | 1,017 | 50.57 |
csKeyboardDriver Class Reference
Generic Keyboard Driver. More...
#include <csutil/csinput.h>
Detailed Description
Generic Keyboard Driver.
Keyboard driver should generate events and put them into an event queue. Also it tracks the current state of all keys.
Definition at line 99 of file csinput.h.
Constructor & Destructor Documentation
Initialize keyboard interface.
Destructor.
Member Function Documentation
Call this routine to add a key down/up event to queue.
- Parameters:
-
Query the state of a key.
All key codes are supported. Returns true if the key is pressed, false if not.:
Example: Test if the right Ctrl key is pressed:
bool pressed = (KeyboardDriver->GetModifierState(CSKEY_CTRL_RIGHT) != 0);
- Parameters:
-
- Returns:
- Bit mask with the pressed modifiers.
Call to release all key down flags.
Call to get the key down flags in sync with the actual pressed keys.
Set key state.
For example SetKey (CSKEY_UP, true). Called automatically by do_press and do_release.
Generates a 'cooked' key code for a 'raw' key code from some simple rules.
Fills in the 'cooked' key code of an event with only a 'raw' key code.
Member Data Documentation
The documentation for this class was generated from the following file:
Generated for Crystal Space 1.4.1 by doxygen 1.7.1 | http://www.crystalspace3d.org/docs/online/api-1.4/classcsKeyboardDriver.html | CC-MAIN-2017-17 | refinedweb | 202 | 62.24 |
Loops in Python – comparison and performance
Python is one of the most popular programming languages today. It’s an interpreted and high-level language with elegant and readable syntax. However, Python is generally significantly slower than Java, C#, and especially C, C++, or Fortran. Sometimes performance issues and bottlenecks might seriously affect the usability of applications.
Fortunately, in most cases, there are solutions to improve the performance of Python programs. There are choices developers can take to improve the speed of their code. For example, the general advice is to use optimized Python built-in or third-party routines, usually written in C or Cython. Besides, it’s faster to work with local variables than with globals, so it’s a good practice to copy a global variable to a local before the loop. And so on.
Finally, there’s always the possibility to write own Python functions in C, C++, or Cython, call them from the application and replace Python bottleneck routines. But this is usually an extreme solution and is rarely necessary for practice.
Often performance issues arise when using Python loops, especially with a large number of iterations. There is a number of useful tricks to improve your code and make it run faster, but that’s beyond the scope here.
This article compares the performance of several approaches when summing two sequences element-wise:
- Using the while loop
- Using the for loop
- Using the for loop with list comprehensions
- Using the third-party library numpy
However, performance isn’t the only concern when developing software. Moreover, according to Donald Knuth in The Art of Computer Programming, “premature optimization is the root of all evil (or at least most of it) in programming”. After all, “readability counts”, as stated in the Zen of Python by Tim Peters.
Problem Statement
We’ll try to sum two sequences element-wise. In other words, we’ll take two sequences (list or arrays) of the same size and create the third one with the elements obtained by adding the corresponding elements from the inputs.
Preparation
We’ll import Python built-in package random and generate a list r that contains 100.000 pseudo-random numbers from 0 to 99 (inclusive):
import random
r = [random.randrange(100) for _ in range(100_000)]
We’ll also use the third-party package numpy, so let’s import it:
import numpy as np
And we’re ready to go!
Simple Loops
Let’s first see some simple Python loops in action.
Using Pure Python
We’ll start with two lists with 1.000 elements each. The integer variable n represents the length of each list. The lists x and y are obtained by randomly choosing n elements from r:
n = 1_000
x, y = random.sample(r, n), random.sample(r, n)
Let’s see what is the time needed to get a new list z with n elements, each of which is the sum of the corresponding elements from x and y.
We’ll test the performance of the while loop first:
%%timeit
i, z = 0, []
while i < n:
z.append(x[i] + y[i])z.append(x[i] + y[i])
i += 1i += 1
The output is:
160 µs ± 1.44 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Please, note that the output of timeit depends on many factors and might be different each time.
The for loop in Python is better optimized for the cases like this, that is to iterate over collections, iterators, generators, and so on. Let’s see how it works:
%%timeit
z = []
for i in range(n):
z.append(x[i] + y[i])z.append(x[i] + y[i])
The output is:
122 µs ± 188 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In this case, the for loop is faster, but also more elegant compared to while.
List comprehensions are very similar to the ordinary for loops. They are suitable for simple cases (like this one). In addition to being more compact, they are usually slightly faster since some overhead is removed:
%%timeit
z = [x[i] + y[i] for i in range(n)
The output is:
87.2 µs ± 490 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Please, have in mind that you can’t apply list comprehensions in all cases when you need loops. Some more complex situations require the ordinary for or even whileloops.
Using Python with NumPy
numpy is a third-party Python library often used for numerical computations. It’s especially suitable to manipulate arrays. It offers a number of useful routines to work with arrays, but also allows writing compact and elegant code without loops.
Actually, the loops, as well as other performance-critical operations, are implemented in numpy on the lower level. That allows numpy routines to be much faster compared to pure Python code. One more advantage is the way numpy handles variables and types.
Let’s first use the lists of Python integers x and y to create corresponding numpy arrays of 64-bit integers:
x_, y_ = np.array(x, dtype=np.int64), np.array(y, dtype=np.int64)
Summing two numpy arrays x_ and y_ element-wise is as easy as x_ + y_. But let’s check the performance:
%%timeit
z = x_ + y_
The output is:
1.03 µs ± 5.09 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
That’s almost 85 times faster than when we used list comprehensions. And the code is extremely simple and elegant. numpy arrays can be a much better choice for working with large arrays. Performance benefits are generally greater when data is bigger.
It might be even better. If we’re OK with using 32-bit integers instead of 64-bit, we can save both memory and time in some cases:
x_, y_ = np.array(x, dtype=np.int32), np.array(y, dtype=np.int32)
We can add these two arrays as before:
%%timeit
z = x_ + y_
The output is:
814 ns ± 5.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
The results obtained when n is larger, that is 10_000 and 100_000 are shown in the table below. They show the same relationships, as in this case, with even higher performance boost when using numpy.
Nested Loops
Let’s now compare the nested Python loops.
Using Pure Python
We’ll work with two lists called x and y again. Each of them will contain 100 inner lists with 1.000 pseudo-random integer elements. Thus, x and y will actually represent the matrices with 100 rows and 1.000 columns:
m, n = 100, 1_000
x = [random.sample(r, n) for _ in range(m)]
y = [random.sample(r, n) for _ in range(m)]
Let’s see the performance of adding them using two nested while loops:
%%timeit
i, z = 0, []
while i < m:
j, z_ = 0, []j, z_ = 0, []
while j < n:while j < n:
z_.append(x[i][j] + y[i][j])z_.append(x[i][j] + y[i][j])
j += 1j += 1
z.append(z_)z.append(z_)
i += 1i += 1
The output is:
19.7 ms ± 271 µs per loop (mean ± std. dev. of 7 runs, 100 loops each
Again, we can get some performance improvement with the nested for loops:
%%timeit
z = []
for i in range(m):
z_ = []z_ = []
for j in range(n):for j in range(n):
z_.append(x[i][j] + y[i][j])z_.append(x[i][j] + y[i][j])
z.append(z_)z.append(z_)
The output is:
16.4 ms ± 303 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In some cases, the nested for loops can be used with lists comprehensions, enabling an additional benefit:
%%timeit
z = [[x[i][j] + y[i][j] for j in range(n)] for i in range(m)]
The output is:
12.1 ms ± 99.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
We can see that in the case of nested loops, list comprehensions are faster than the ordinary for loops, which are faster than while.
In this case, we have 100.000 (100×1.000) integer elements in each list. This example is slightly slower than the one with 100.000 elements and a single loop. That’s the conclusion for all three approaches (list comprehensions, ordinary for, and while loops).
Using Python with NumPy
numpy is great to work with multi-dimensional arrays. Let’s use x and y to create corresponding numpy arrays of 64-bit integers:
x_, y_ = np.array(x, dtype=np.int64), np.array(y, dtype=np.int64)
And let’s check the performance:
%%timeit
z = x_ + y_
The output is:
69.9 µs ± 909 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
That’s about 173 times faster than list comprehensions. But it might be even faster if we use 32-bit integers:
x_, y_ = np.array(x, dtype=np.int32), np.array(y, dtype=np.int32)
The performance check is done as before:
%%timeit
z = x_ + y_
The output is:
34.3 µs ± 44.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
which is twice faster than with 64-bit integers.
Results Summary
This table summarizes the obtained results:
Conclusions
This article compares the performance of Python loops when adding two lists or arrays element-wise. The results show that list comprehensions were faster than the ordinary for loop, which was faster than the while loop. The simple loops were slightly faster than the nested loops in all three cases.
numpy offers the routines and operators that can substantially reduce the amount of code and increase the speed of execution. It’s especially useful when working with single- and multi-dimensional arrays.
Please, have in mind that the conclusions or relations among the results obtained here are not applicable, valid, or useful in all cases! They are presented for illustration. The proper way to handle inefficiencies is to discover the bottlenecks and perform own tests." /> | https://www.blog.duomly.com/loops-in-python-comparison-and-performance/ | CC-MAIN-2020-05 | refinedweb | 1,692 | 73.88 |
calender working in struts - Struts
calender working in struts when i execute the following code ,that is working properly
if i convert to struts html tags that code is not working
please help me to rectify the problem
code not working properly
code not working properly protected void doPost(HttpServletRequest...);
}
}
in the above code if i enter a valid username and password i am redirected to the correct page but if i enter an invalid details at the first attempt.1 Hi
I/O Program output error
I/O Program output error Hello All,
I am working on a program... of the program in that it reads the text file and analyzes it, however I need it to take... is pValue), however the output just shows each Agent ID and then each pValue. I do
JSP Tutorials Resource - Useful Jsp Tutorials Links and Resources
working. The early examples might
seem very simple; please have patience... by progressing from very simple
examples to complex examples.
For best progress...-building tools you normally use. You then
enclose the code for the dynamic - Jboss - I-Report - Struts
Struts - Jboss - I-Report Hi i am a beginner in Java programming and in my application i wanted to generate a report (based on database) using Struts, Jboss , I
Why this is not working...?
Why this is not working...? import java.util.*;
public class Family... Person[size_of_family];
for ( int i = 0; i < size_of_family; ++i )
{
members[i] = new Person();
System.out.println(members[i want code for these programs
i want code for these programs Advances in operating system
Laboratory Work:
(The following programs can be executed on any available and suitable platform)
Design, develop and execute a program using any
Help Very Very Urgent - JSP-Servlet
Help Very Very Urgent Respected Sir/Madam,
I am sorry..Actually the link u have sent was not my actual requirement..
So,I send my requirement again..
Actually my code needs the following output:
There is a combo box which
html dropdown not working firefox
html dropdown not working firefox I am writing a Dropdown code in HTML which is not working in firefox. What could be the reason as it's perfectly working in IE and Crome.
Thanks
very important - Kindly help
very important - Kindly help I am creating web page for form registration to my department ..I have to Reprint the Application Form (i.e Download... sample code
Struts Code - Struts
Struts Code Hi
I executed "select * from example" query and stored all the values using bean . I displayed all the records stored in the jsp using struts . I am placing two links Update and Delete beside each record .
Now I Articles
;
Strecks is built on the existing Struts 1.2 code base, adding a range of productivity... it.
Struts is a very popular framework for Java Web applications... can be implemented in many ways using Struts and having many developers working
myJSF,Hibernate and Spring integration code is not working. - Hibernate
myJSF,Hibernate and Spring integration code is not working. the code given in this url :
i have tried but it does not work.
when i write - Struts
Struts Dear Sir ,
I am very new in Struts and want... validation and one of custom validation program, may be i can understand.Plz... and specify the type.
5
6
Zip Code needs to between am Getting Some errors in Struts - Struts
i am Getting Some errors in Struts I am Learning Struts Basics,I am Trying examples do in this Site Examples.i am getting lot of errors.Please Help me
Struts Interview Questions
Struts Interview Questions
Question: Can I setup Apache Struts to use
multiple... are the disadvantages of Struts?
Answer: Struts is very robust framework and is being
Dynamic-update not working in Hibernate.
Dynamic-update not working in Hibernate. Why is dynamic update not working in hibernate?
Dynamic-update is not working. It means when...
org.hibernate.Transaction class ,start your transaction and commit it. Here I
Struts hi
can anyone tell me how can i implement session tracking in struts?
please it,s urgent........... session tracking? you mean session management?
we can maintain using class HttpSession.
the code follows
calender in struts - Struts
calender in struts when i execute the following code ,that is working properly
if i convert to struts html tags that code is not working
please help me to rectify the problem
i need program or code for this program
i need program or code for this program out should be in this form
1 2 3 4 5 6
3 5 7 9 11
8 12 16 20
20 28 36
48 64
112
i want to retriev and update in same form but its not working pls help....
i want to retriev and update in same form but its not working pls help.... <p><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<html></p>
<p>
Working Example for Spring AOP - Spring
Working Example for Spring AOP Hi All,
I need a complete working Java example /Code/Logic for Spring -Aspect Oriented Programming.
Code provided will be highly appreciated.
--
Deepak Lal
Struts Tutorials
is provided with the example code. Many advance topics like Tiles, Struts Validation... and develop them with WebSphere Studio
Struts is a very popular framework that adds... will show you how to use the Struts Validation Framework. This framework is very
struts
struts i have one textbox for date field.when i selected date from datecalendar then the corresponding date will appear in textbox.i want code for this in struts.plz help.
Can i insert image into struts text field
Can i insert image into struts text field please tell me can i insert image into text field
Can i write JavaScript code in AjaxResponse Code ?
Can i write JavaScript code in AjaxResponse Code ? Hai Every Dynamic's
We can't write JavaScript code in Ajax Response Code.Why because it takes...'s not working.rather than that i try to created on innerHtml document.
here
Developing Simple Struts Tiles Application
To Create Tiles Application
Tiles is very useful framework for the development of web...
Developing Simple Struts Tiles Application
Introduction
In this section
struts
the checkbox.i want code in struts...struts I have no.of checkboxes in jsp.those checkboxes values came from the databases.we don't know howmany checkbox values are came from
getElementById not working
getElementById not working I have to get value from a hidden input. When I try using document.getElementById("issuer").value it gives me null but when I use document.forms[0].issuer.value it gives me the value of the field.
Your hibernet tutorial is not working - Hibernate
Your hibernet tutorial is not working Hi,
I am learning hibernate from your tutorial.
when i execute the 1st hibernate example at following location it working
I want detail information about switchaction? - Struts
I want detail information about switch action? What is switch action in Java? I want detail information about SwitchAction
JQuery-JSP AJAX example not working
started with AJAX)), I was able to get it working. Just recently, I have been working on some additional development code using AJAX and I was getting some....
The only change in the source code that was copied was that I changed
what should i do next?? - Java Beginners
. i think first u should go through servlet bcoz at last ur jsp code...what should i do next?? I know java basics.actully i passed the SCJP exam.Then now i have no idea about what should i do next.I like to come
Java i/o opearations
Java i/o opearations "FOLLOWING IS MY LAST QUESTION ON JAVA I/O... STREAM BUT IT IS NOT WORKING WELL WITH RANDOM ACCESS FILE" i.e.,how to WRITE integer... to a file in java using random access file object or file writer or data outputstream i
Working With File
Working With File
... provide a simple model for reading and writing data. However,
streams don't support... to work with a file using the non-stream file I/O.
The File class deals
I need your help - Java Beginners
I need your help For this one I need to create delivery class for a delivery service .however, this class should contain (delivery number which... of 20100076). (Code to representing the delivery area either 1 for local delivery am
StringIndexOutOfBoundException problem, What is mean in this code | first.charAt(i)) |
StringIndexOutOfBoundException problem, What is mean in this code | first.charAt(i)) | import java.io.*;
public class Sort{
public static void...++){
for( i=0;i<11-1;i++){
if((byte)c==(byte)first.charAt(i))
{
count1 file uploading - Struts
Struts file uploading Hi all,
My application I am uploading files using Struts FormFile.
Below is the code.
NewDocumentForm... can again download the same file in future.
It is working fine when I
I want code below mention programe
I want code below mention programe Create a web application using any technology that accepts a keyword and displays 10 relevant tweets from Twitter in real-time for that keyword
struts
Am i convetrting the code right ? - Java Beginners
Am i convetrting the code right ? C#
private void button... (IOException ex) { }// i also tried the code below// try... a led on it. The LED blinks on the C#'s code. I think the code i have written
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...
Reduce Java Code commenting effort using JAutodoc (eclipse plugin
SubCombo box not working - Development process
SubCombo box not working Hi, in the following code subcombo box is not working and while storing combo box numbers(1,2,3) are stored instead...;
document.forms["form"].elements["combo2"].options.length=0;
for (var i=0;i
Hi.. - Struts
Hi.. Hi,
I am new in struts please help me what data write........its very urgent Hi Soniya,
I am sending you a link. This link... useful in the creation of HTML-based user interfaces.
struts-logic.tld
How jQuery works?
from
the server.
So, jQuey is very useful tool. Let's see how it works....
The jQuery is designed to do more work in less coding. It's very easy...
technologies. You can use JSP,Servlets, Struts, Spring MVC, ASP, .NET, CGI
query in simple code..i had described all...........
query in simple code..i had described all........... SAME HERE...[])
{
B b1=new B();
b1.callmetoo();
}
}
WHEN I AM COMPILING javac AbstractDemo.java,I receives en error:
AbstractDemo.java:5:cannot find symbol
symbol: class B
Add color to background but I can't labels or textfields
JTextField(10);
con.add(l1);
con.add(tf1);
I am very new to Java, I...Add color to background but I can't labels or textfields Please help... need to import javax.swing.*
So the code must contain the following lines to add
working wit string - Java Beginners
working wit string accept a paragraph of text. consisting... code:
import java.util.*;
import java.util.regex.*;
public class...);
for(int i=0;i Hi Friend,
import java.util.*;
import
<
File I/O
posted below:
here is the code to what i have done thank you looking forward...File I/O i am trying to write a program that reads a text file... the text file then read it and write it into as a comma delimitade file. i have
HTML - I tag example.
HTML - I tag example.
Description :
It is a text formatting tag. It display the text font into italic format.
Code :
<html>
<...>HTML -- I tag Example. </h1>
<p>
Roseindia Technology Pvt
File I/O
File I/O i have a problem i am trying to print on a new line every time i reach a certain condition "if(line.startsWith("Creating"))" i want... this
Creating
Finally, its time to write some code. Bookmark the Google APIs | http://www.roseindia.net/tutorialhelp/comment/7043 | CC-MAIN-2015-14 | refinedweb | 1,994 | 67.45 |
I am new to unity and I have no idea how to add a force to an object at a position that is not (0,0,0) Relative to the object. When i started adding forces i used the function Ridgedbody.AddForce this just added a force that was relative to the game maps center location. I then used Ridgedbody.AddRelativeForce this gave the object a force but it was only able to be applied from the objects center. I have heard about AddForceAtPosition but i don't know how to apply it, and i think it might just give a force relative to a point on the map. Here is what i have so far for my object controller.
using UnityEngine;
using System.Collections;
public class Driver : MonoBehaviour {
// Use this for initialization
void Start () {}
// Update is called once per frame
void Update ()
// roll controls
{if(Input.GetKey(KeyCode.W))
{rigidbody.AddRelativeTorque(15, 0, 0);}
if(Input.GetKey(KeyCode.S))
{rigidbody.AddRelativeTorque(-15, 0, 0);}
if(Input.GetKey(KeyCode.A))
{rigidbody.AddRelativeTorque(0, 0, 10);}
if(Input.GetKey(KeyCode.D))
{rigidbody.AddRelativeTorque(0, 0, -10);}
if(Input.GetKey(KeyCode.RightArrow))
{rigidbody.AddRelativeTorque(0, 5,0);}
if(Input.GetKey(KeyCode.LeftArrow))
{rigidbody.AddRelativeTorque(0, -5,0);}
// forward and backward controls
if(Input.GetKey(KeyCode.UpArrow))
{rigidbody.AddRelativeForce(0,0,10);}
if(Input.GetKey(KeyCode.DownArrow))
{rigidbody.AddRelativeForce(0, 0,-10);}
}}
Im Ok with my torque forces being applied from the objects center but i want my regular forces to be applied 1.5 unity distance units below the objects center. So to be spesific i want a force with a magnitude of (0,0,10) applied from a transform location of (0,-1.5,0) relative to the objects center, and another force with a magnitude of (0,0,-10) applied from a transform location of (0,-1.5,0) relative to the objects center.
I would also like to know how to how to apply torques from a none central position relative to the object as there is a good chance i will have to do this later on.
@Jonny_$$anonymous$$ Did you ever find the answer to this? I am having the exact same problem :(
Answer by kingcoyote
·
Oct 26, 2015 at 05:34 PM
You should be able to use RigidBody.AddForceAtPosition for this. I'm not sure why you had trouble with it. Maybe the nature of the position Vector3 was problematic?
The position Vector3 is in world space, so if you want to offset it from your object's position, you just need to do a little math You say you want the force to be offset by a certain amount, so try this:
rigidbody.AddForceAtPosition(
new Vector3(0, 0, -10),
transform.position + new Vector3(0, -1.5, 0)
);
That will create a force with a magnitude of (0, 0, -10) and apply it just near your transform.position. If you don't offset it to your transform.position, it will be relative to the global (0, 0, 0), which is not what you.
C# Check If Gameobject is within Collider
1
Answer
C# Preserving GameObjects' Previous Meshes
1
Answer
C# Plane Detecting a Gameobject
1
Answer
C# Reverting GameObject to Original
1
Answer
Problems with Transform.Find and GameObject.find
1
Answer
EnterpriseSocial Q&A | https://answers.unity.com/questions/601235/how-to-add-forces-and-torques-relative-to-an-objec.html | CC-MAIN-2022-27 | refinedweb | 550 | 57.98 |
build tool for node.js projects
build tool for node.js projects.
The primary motivation for this project is to watch a dependency graph of file timestamps, and react to updates automatically. The usecase is editing the code of a long-running application, such as a server, and having the code automatically rebuilt, and the server restarted.
not cool yet.
Jake is synchronous by default. boon runs everything in parallel when possible.
require('jake') pollutes the global namespace. boon does not touch the global namespace.
A Jakefile must be JavaScript. boon has no magic file names, so the build script can be run with any interpreter.
coffee -w
coffee -w gives no clear indication that it is done with everything it sees to do.
boon supports callbacks when files are built, which allows an application to wait to start
until after everything has had a chance to build once.
Race conditions when saving files with vim causes
coffee -w to start ignoring the file.
boon supports runtime file discovery and dependency graph modification, which will not only
reacknowledge files when they come back into existence, but discover new files in a directory
without having to restart boon. | https://www.npmjs.com/package/boon | CC-MAIN-2015-40 | refinedweb | 197 | 66.84 |
CGTalk
>
Software Specific Forums
>
Autodesk Maya
>
Maya Programming
> need code review for a code snippet
PDA
View Full Version :
need code review for a code snippet
DEVILSAN
11-22-2012, 08:34 AM
Today, after finishing chapter 7 of Maya Python for Games & Film, book I started practicing on the code, since I also have made some python tools this chapter showed me the real way of doing things, specially building a py module that we can import in any tool as a base for GUI to startup and override methods to add more controls to it..
since code ()might not display properly here so I pasted onto pastebin ()
the code is compatible with version below 2010 as floating window and Maya 2011 onwards as Docked to what convention I usually stick to while making my tools for maya... I agree with starks whats the point of floating windows when we can dock...
So in this code I made a BaseGUI class that has createUI method that has some common functionality in to which i call the method self.commonLayout() to which I add controls and a second method after commonLayout() into which I editTabsLayoutcontrol as per requirement.
I would really appreciate if you leave your comments and suggestion and any update you can make feel free,
I saved it as DockedGUI.py
and run this in maya script editor paste
from DockedGUI import BaseGUI
BaseGUI.showUI()
vBulletin v3.0.5, Copyright ©2000-2013, Jelsoft Enterprises Ltd. | http://forums.cgsociety.org/archive/index.php/t-1081245.html | CC-MAIN-2013-20 | refinedweb | 247 | 61.6 |
Index
Links to LINQ
This.
If you would like to receive an email when updates are made to this post, please register here
RSS
You've been kicked (a good thing) - Trackback from DotNetKicks.com
What's the usability scope of the "dynamic" keyword? If it's only inside method/property members, that will be quite limiting on its use.
Interesting concept. I imagine the runtime will do all sorts of nice optimizations to make sure that this runs nicely.
However, given what you have now, what's to stop you from implementing this as a compiler trick? What is integration with the CLR going to give you over having reflected calls emitted by the compiler?
casperOne,
The biggest thing that this gives you over reflection is ease of use. This is a much simpler syntax than we had through reflection as we know it today.
Also, there is new functionality here in terms of COM interop and interaction with dynamic languages. Today those features are either missing altogether, or are very hard or awkward to use.
I think it is a little early to start talking about performance. We are really giving you an early look at this technology, and it will be some time before we see it in more depth. Certainly I hope the performance will be great, but it is too soon to start making any claims.
Jimmy,
The scope in the current plans would be to have it work only inside a method or property implementation, as shown in the article above. But our plans are still under development.
Tell me what you are thinking about. Would you like to see it have class scope? Would you extend the scope across an entire namespace?
It would be very wrong of me to give the impression that this is your chance to design a feature. That is not the case. But this is a chance for you to give us feedback. What would you like to see?
- Charlie
The intention is indeed for this to be efficient. A big part of the DLR's job is to provide efficient execution infrastructure for code that is looked up at runtime - such as that of dynamic languages - Python, Ruby etc.
/Mads
Hi all, it's me again. For those who don't know me, I'm a tester on the C# IDE team at Microsoft. I already
@Charlie
Our typical use for late-binding was Interop/Office scenarios. We would create a single class to act as a facade over these COM resources.
Sometimes COM classes can be expensive to instantiate. In these cases, we would instantiate them at the constructor and set a private field.
Also, COM references would frequently cross method (but not class) boundaries as we would do normal internal refactoring.
For anything but dead simple scenarios, it would be difficult to accomplish what we need in one method. As large as the Office interfaces are, there's not a whole lot you can accomplish inside a single block before it gets complex and unmaintainable.
In these cases, I wouldn't necessarily need namespace-scoping, but file or class scoping would be sufficient.
Hi all, it's me again. For those who don't know me, I'm a tester on the C# IDE team at Microsoft
I have been searching for any clue about the next version of C# and what the features to be included,...
Great news that you are considering changing the access to Office Automation. I hate the optional parameters and the "missing, missing, missing" throughout the C# code.
:-)
Klaus
First of all, I think it is a great idea to give us an early insight in your future plans and let us give early feedback.
My suggestion is to limit the scope of the dynamic-block to a particular variable or property and also to allow it in the declaration of (local) variables or maybe even properties and fields. This is, because in most cases you don't want every lookup in your dynamic block to be dynamic, but only to some variables that e.g. contain COM-objects.
So in the example above, I would rather see:
object myDynamicObject = GetDynamicObject()
dynamic(myDynamicObject)
{
...
}
or:
dynamic object myDynamicObject = GetDynamicObject();
...
Of course something like myDynamicObject.Foo.Bar would also work, but something like:
object foo = myDynamicObject.Foo;
foo.bar
would not work and would require another dynamic modifier on the foo declaration.
If you allow the dynamic flag on property or public field declarations, you could do it with some sort of attribute, but I'm not sure if this is a good idea, because developers using these properties or fields may not be aware of the fact that they are opting in for dynamic lookup. Also this may encourage bad programming style, where someone exposes lots of "object"-properties and relying on the dynamic lookup, where he could use other mechanisms to give the caller a statically typed way to access these properties.
A compromise would be to allow this flag only in private property or field declarations, which would make a class scoped dynamic keyword (as suggested above) unnecessary and still allow for static typing for everything not marked dynamic in the class.
I would love to hear your feedback on this.
What kind of control do I have over it?
That is, do we have a method missing hook?
Finally, some news for next version coming up...
Interesting ..., i ll give my feedback ...
at first sight it seems to provide easy way for reflection...but there can be some interesting talks to it, like scoping or performance related..
would be awesome of this worked on anonymous types
Charlie Calvert has posted an article that is co-authored by Mads Torgerson on one possible implementation
What about the return types of the members you call dynamically. If we write something like:
string x = (string)myDynamicObject.SomeStringMethod();
would the runtime call SomeStringMethod and then try and cast the result to a string or check that the result can be cast to a string when it dynamically binds and throw an exception at bind time if it found that it was not possible?
Would the runtime attempt to bind the entire dymanic block before it executes it (better since this would be more defencive) or dive in and try its best to perform the calls (and possibly cause an exception after only some of the calls had run)?
Adding to the Scoping of the Dynamic Object. We too use the object at the class level. For example we write an export class that has a single handle into Excel. Having the scoping at the method level will severly limit the cross method calls. Unless we can declare the object as DynamicObject in the calling method.
private void CreateHeaders(dynamic object excelObject, string[] headers) {
dynamic(excelObject) {
}
Jimmy and others who addressed the scoping issue:
Taking into account the fact that our plans are still fluid, and nothing is finalized yet, the current thinking is that there will be no reason to consider a dynamic variable as anything special, and so it can be declared as we would in standard C# 3.0 code. For instance:
class MyClass
{
object myDynamicOfficeObject;
public void Method01()
{
dynamic
{
myDynamicOfficeObject = GetMyDynamicOfficeObject();
myDynamicOfficeObject.Format();
}
}
public void Method02()
myDynamicOfficeObject.SelectRange();
If one calls Method01() first, then myDynamicObject will still be fully initialized and in scope when one calls Method02().
The idea of declaring an entire object as dynamic is also in play, but there is a concern that a broad granularity of that type is not right for C#. So currently we are leaning toward the syntax shown above.
But all of your suggestions are being taken into consideration and we appreciate your feedback. It is valuable.
Mmmm that sounds so VB... does it mean that the F# tunics have left the team and hand been replaced again by the VB Ties?
It's interesting because there's a C9 video where Anders goes on record saying that he'd think twice before putting this kind of feature into C# rather than leaving it to VB.NET. I guess market pressures are such that MS need to ensure they have something that ticks the Dynamic Box. Given that the CLR is meant to be all about using the best language for the job I don't quite see why MS don't put more effort into promoting *mixed* language solutions - rather than trying to shoehorn every language idiom and school into C#...
What I don't understand:
If everything inside the "dynamic"-block uses dynamic lookup, then you'll loose type safety for everything inside this block, not just the objects you're really needing it for. This is a much broader granularity IME than declaring a single object as dynamic and leaving all the other objects typesafe.
In a typical scenario you'll need every access to a specific object to be dynamic. If you just declare this single object dynamic, you'll have fewer dynamic lookups than having many dynamic blocks in a class that contain dozens of other objects that would normally be just fine with static lookup, but now use dynamic lookup, just because a single object in this block needs it.
Thomas,
Thank you for this helpful comment. As you know, this is one of the subjects that is still very much under discussion. For instance, the team is considering first attempting to resolve all code in a dynamic block statically, and using dynamic lookup only if the static calls can't be resolved at compile time. The team will take your feedback into account and I'll work to get updates to the community if and when the status on these issues changes.
Welcome to the fortieth issue of Community Convergence. This week we have two new releases of note: We
I agree with Thomas. I think that the typical scenario has us using dynamic lookup for all references of a single object, so it makes sense to declare the object as dynamic rather than a block of code. Something like this:
class SomeClass
dynamic object _myLateBoundMemberObject;
object _myStaticallyBoundMemberObject;
private void SomeMethod()
dynamic object myLateBoundLocalObject;
object myStaticallyBoundLocalObject;
~Steve
How about using -> instead of . for dynamic lookup? I'm only half joking!
I agree with Tom (and Anders, apparently). It is silly to try to make C# everyman's language. Why can't the C# language team admit that it's ok to have statically typed languages for some purposes and dynamically typed languages for other purposes? You don't have to take EVERY SINGLE programming convention or idea or trick and find a way to squeeze it into C# somewhere. Personally, I WANT C# to stay away from dynamic language features; I use it because I want a statically typed language. When I want a dynamically typed language, I can reach for one of the many available. You don't have to try to be everything to everyone.
That said, if you are hell-bent on doing this regardless of its advisability, then I also agree with Thomas. If you take a step back from the technology and look at the typical use cases, usually the only times you need to use dynamic invocation is because you have created an object for which you do not have static access to its members, i.e. it was constructed from a dynamic language library, or through reflection. Therefore, it would make a lot more sense for the dynamic keyword to be used at the variable declaration level, allowing all calls on that variable to be dynamic without having to clutter up all of the code that might use that variable with dynamic blocks.
If I understand what your doing, this is really just another C# compiler trick where your just going to replace it in IL with a reflection version.
If got that right, then I also prefer a new Dynamic Lookup method operator instead.
'->' might cause many C++ refuges some heartburn, so how about:
myLateBoundLocalObject'Method1()
or
myLateBoundLocalObject~Method1()
or
myLateBoundLocalObject@Method1()
myLateBoundLocalObject..Method2()
or even reverse it to make them stand out more
aka
Method1() of myLateBoundLocalObject
Method1()@myLateBoundLocalObject
I think if a good operator is found it would make the code much cleaner.
I personnally like the '..' version as it would be easy to remember.
One period for Static bound calls,
Two periods for Dynamic lookup.
-Pablo
Quick suggestion: could the "dynamic" modifier be implemented as an attribute? That way the attribute could be applied to a variable, class, function, etc. That would address the scope issues presented earlier, and it would be easier to read and comprehend the code.
Kinda OT, but since somebody important could be reading this...
Can we /please/ have something like ':' operator, so that following could be written:
string greatGrandFatherName = person:Parent:Parent:Parent:Name;
...instead of tedious...
if (person.Parent == null) return null;
if (person.Parent.Parent == null) return null;
if (person.Parent.Parent.Parent == null) return null;
return person.Parent.Parent.Parent.Name;
OK, this isn't the best example, but there are many uses for this (especially in ORM) and it makes syntax so much cleaner, IMHO.
LP,
Dejan
This reminds me of the times when Delphi first added late binding features in order to support COM automation scenarios...
I often rethink or have additions to my posts. This topic of what's coming in C# vNext is definitely
Hi. Thanks for a great post Charlie and Mads!
I'll post some of my feedbacks here.
What about a dynamic block and a new late bound operator (.. for example):
object myObject = GetDynamicObject();
dynamic
int i = myObject..GetValue();
string s = myObject.ToString();
This way you spesifically choose to do late binding and show exactly here you want it. But this kind of breaks the nice typesafe static nature of C# I guess...
This is so fun I have to put out another idea...
What about some kind of inline interface declaration?
interface (myObject)
{
void SomeMethod();
int GetSquare(int v);
}
catch
myObject.SomeMethod();
int i = myObject.GetSquare(100);
This way you both declare a dynamic section and declare the exact members you need.
There's actually no real late binding, just a syntactic sugar for reflection lookups.
Another nice feature here I think is the possibility to catch if the lookup fails.
You could even start a new interface failover declaration inside the catch.
David,
Thank you for your comments. The team will consider them carefully. Please note that the proposed C# features discussed in this post are not designed to convert C# into a dyanmic language, only to make it possible to call code written in a dynamic language and to make COM interop simpler.
I and others on the team hear and appreciate what you are saying in your second paragraph about the declaration of dynamic variables and I will pass that information on to everyone on the team.
After posting the -> 'suggestion' I decided that '..' would be a reasonable looking alternative. So there you have it - independent evolution of the same syntax idea from multiple people - it must be a good idea :)
The whole thing reminds me a bit of the old VB syntax for accessing fields on a recordset:
Sn!FieldName 'instead of Sn.Fields("FieldName")
I vote strongly in favour of Thomas Krause's suggestion.
I think a tagged block (similar to "unsafe") that changes the language rules for all code inside it would be a bad idea.
Firstly, if you made it affect all types within the block, that's too coarse-grained - what if some calls could be static? This immediately leads to the idea of mixing dynamic and static lookup, as mentioned.
Secondly, the main reason for using that tagged block approach is because you want to clearly call it to the attention of someone reading the code, but in fact if all the code in the block happens to be statically resolvable then the dynamic block would not make any difference, and so would be completely misleading to anyone reading the code. It's like a worrying comment that might have genuine implications, but might not.
Far better to have a pseudo keyword made of two tokens, "dynamic object", which declares a reference type on which method/property access is always dynamic. This can then be used on local variable or member declarations.
As for making it clear to the reader of the code, Visual Studio can do a much better job of this by highlighting all method/property accesses on dynamic objects. It would be great if they had a grey background or something like that - they'd stand out a mile and it would give instant feedback to explain why there was no intellisense happening.
Thomas, Daniel, Commenter, others,
Thanks for these suggestions. This is great feedback and it is very much the type of thing we were hoping to see. I'll make sure all your ideas are passed on.
I have to agree with Thomas on this one
I think that c# should remain explicit when it comes to this new feature of dynamic objects. I much rather declare an object as dynamic.
Imagine a scenario where I have a private member variable that is dynamic. If we state it as such on the declaration we will not have to litter our code with
dynamic {
...
on each of the 10 functions that we require to use that object.
This also has the added benefit that you can specify a return value of dynamic object on functions. You would then have the ability to know which functions return dynamic objects on that 3rd party API that I am consuming as a programmer.
I think it is important for c# to remain a language that is explicit in telling the compiler how to do things. I would not like to see the compiler trying to get overly smart and trying to guess within a dynamic region what really *is* dynamic and what is *not*
On a side note I think Dejan has brought up an important missing nicety in c#. I too would like to see a null dereferencing operator of some sort in the form of myobj.?property or with a symbol of your choice
Thanks,
Anastasios
Wouldn't it be cool to support both late binding and intellisense.
I think optionally declaring methods and properties in the variable declaration could do.
public class Program
{
// Without intellisense
dynamic object dynObject = GetDynamicObject();
// With intellisense
dynamic object dynObject = GetDynamicObject()
{
void SomeMethod();
}
This way you can opt for intellisense according to own needs.
And it could also be possible to declare inline:
dynamic (dynObject)
int GetSquare(int value);
int i = dynObject.GetSquare(100);
This is kind of off-topic, but since we're talking about C# future I would like to suggest an implementation for optional parameters.
I understand why C# doesn't allow them since this transfers control from the user of a method to the implementor,
and the implementor can choose to change default values at any time, possibly breaking the code using it.
But what about declaring default values and letting intellisense auto-insert them for you?
Here's a code example:
public void PlaceOrder(int orderID, int price = 100);
Then, when you write PlaceOrder intellisense will autofill the price param to be 100 if you want it to.
This doesn't make a lot of sense when there's one parameter defining a default value,
but with 10 it could really boost productivity.
I hope this just uses reflection under the hood and doesn't alter the .NET framework to accomodate late binding in anyway. Much like var in C# is just a compiler trick
Maybe this syntax instead:
var myDynamicObject = p as dynamic;
myDynamicObject.SomeMethod(); // call a method
myDynamicObject.someString = "value"; // Set a field
myDynamicObject[0] = 25; // Access an indexer
I do this today by using a PythonEngine instance in my C# applications. It's clunky but it works. The PythonEngine instance acts as the scope for the dynamic code. I can inject scripts into the engine using Execute() and fetch objects from the engine with Evaluate(). I use this sort of "dynamic layer" at the lower edge of my client applications to dynamically generate ClientBase<T> derived instances from WS-MetadataExchange using classes from the System.ServiceModel.Description and System.CodeDom namespaces. Imagine a SVCUTIL-free lifestyle. No proxy generation at all. It's nirvana, really.
I like Thomas Krause's proposed model where the objects to be used within a dynamic scope could be obtained outside of that scope because it would make what I'm doing with Python embedded in C# much simpler. Of course, I probably wouldn't be using Python to glue the WCF clients and services together with C# 4.0 if it supported what Charlie's talking about. But it would need to be done as Thomas describes to make it really fluid. Thomas' reply on 28 Jan at 13:29 seems to indicate that the C# team might be leaning this way. And that's good because the main problem I have today is making the dynamic Python code reach out of the dynamic scope to access object references obtained in the static scope. It's possible but really messy.
While I'm in here and on the topic of language futures, how about a policy attribute that I can attach to a class that forces it to be instantiated within a using statement? In other words, for a class that implements IDisposable, give me an attribute that I can mark the class with so that any attempt to instantiate the class in a way that would not invoke IDisposable::Dispose would simply not compile. Man, would that be helpful?!
- Kevin
Personally, I have to side with the guys that like C# to stay static. LINQ is about the extent of "dynamic-ness" that I can tolerate.
Class Libraries written in IronPython callable by C#? I honestly can't see many truly indispensible class libraries written in IronPython that couldn't otherwise be rewritten in a much more performant way in C#.
Granted, usability is key here, but are we in the community asking for this? My assertion is "USE VB" since VB frankly is so close to C#, yet still has the late binding techniques built in.
Eric, there's a language for people like you (the instinctively conservative).
It's called Java. ;-)
Eric, I understand your thinking about keeping C# statically typed. I sometimes wonder if the current duck typing pendulum has just swung to the far end of its period as it's known to do every few years. But I don't think so. This time, I think there is enough maturity in the marketplace that people are beginning to wonder why they can't have the best of both worlds.
My response above about my experiences embedding Python in C# is an expression of the fact that I love the type safety of C# most of the time. But when it's time to do something dynamic, I regret having to step out of C# (or into deep reflection and lots of CodeDom trickery) to do it.
Speaking of performance: for the dynamically-generated ClientBase<T> invocation of a WCF service in a tight loop versus using a statically-bound, SvcUtil-generated proxy called directly from C# that I described above, there is no difference in performance. The only real difference is that I never had to use SvcUtil in the former case and I really like that. So I can envision a world where static, early-binding and dynamic, late-binding get along just fine.
C# Futures - Dynamic Code Blocks
This is an exciting feature. I have several comments.
1. I really like the .. operator idea either instead of or in addition to a dynamic block. This is even more important in a maintainence scenerio than in new code. If one is adding 2 dynamic calls to some existing code the choices are a) 2 dynamic blocks or b) subtly changing the semantic of all the method calls between them. I really want more control over when I use dynamic invocation.
2. I hope you will expose the the name lookup logic through system.Reflection as well. I have been trying to write a generic "accessor" class that uses reflection to allow unit tests to access private and protected members of production classes. Doing the name resolution, based on a string member name, is easy to do wrong, and proving very difficult to do right. I would enjoy being able to give reflection a name and say "find me the member, public / private ... etc, that this name would map to."
3. WHat is going to happen when you do a Dynamic call on a RealProxy descendent. I hope that it just calls Invoke with the method name and arguements, and lets me work it out. (This would let me define some test objects with a very flexible interface.)
4. Add another vote for the : operator proposed by Dejan Stanic. I see this pattern all the time, especially when using Linq.
John Melville
I've had a policy against posting on big news that's likely to be common knowledge in the Microsoft development
This is the kind of feature that should be introduced with extreme care, since a) it's too easy to implement (so the temptation to include it will be high, even if consequences have not been considered thoroughly) and b) if badly done, it can spoil forever our beloved language.
Strongly agree with others that a dynamic {} block is not the best solution, whether dynamic in that context means "every member access will be dynamically looked up" (too coarse-grained) or "access to members not found at compile time" (also coarse-grained and may complicate understanding of the code).
Explicitly supporting "dynamic" in front of "object" in declarations (as Daniel proposes) seems much better to me. For instance, in the example of wkhazzard one could define a method:
public class ProxyGen
dynamic object GetProxy() { /*...*/ }
and then the client would use:
ProxyGen p = new ProxyGen();
dynamic object cli = p.GetProxy();
cli..Whatever();
I also support having a special operator (I'd prefer ->, but it's already used in unsafe blocks), so that these dynamic method calls are explicitly marked in code.
Best regards,
Octavio
The idea of adding late binding to C# is a good one, but am not sure that going down the path of using a block marked by the dynamic keyword is a good idea.
The rationale seems to be that "dynamic" would clearly flag a block of code that will have special rules, but the problem as I see it, is that there will be no way for the programmer to go back and forth inside this block to get strong typing (without doing plenty of gymnastics).
By using the 'dynamic' block, everything inside this block that happens to be an object will be treated as a dynamic path and some errors that could have been caught will not be (accidental uses of it, return values that should really have been strongly typed).
My preference would be to additionally declare variables with a keyword, an attribute or a new type, like this:
dynamic p = GetDynamic ();
p.Hello (d.World.DoSomething ());
This has the advantage that dynamic support will only be offered for "p" in this particular context, but still get full type checking with d, d.World and d.World.Something.
Miguel.
Give us an interface we can implement on our own classes that allows us to implement method dispatch! The Boo lanaguage has IQuackFu - silly name but very powerful.
Something like this would be cool for C#:
class MyFoo : IDynamicDispatcher
object IDynamicDispatcher.Invoke(string methodName, object[] args)
// ...
// similar for properties here...
then use as:
dynamic foo = new MyFoo()
foo.Bar()
Compiler translates into:
foo.Invoke("Bar", null);
Miguel, what about scoping? Consider this:
ShoppingCart cart = new ShoppingCart();
dynamic jabberwocky = GetDynamicObject();
Product P = jabberwocky.SomeUnknownMethod( cart );
To do this today, I have a couple of options:
(1) I can use reflection and find the SomeUnknownMethod signature for jabberwocky that best accepts a ShoppingCart, then call it, coercing the result into a Product reference.
(2) I can instantiate a ScriptScope from the DLR, inject the ShoppingCart object using SetVariable, invoke some Python, for example, to do the work, then use GetVariable<T> to fetch the Product out of the script context.
Personally, using the DLR seems like a better, long-term, more flexible option but it us certainly heavier than using simple reflection.
I suppose the question I have for Charlie and others on the C# team is: how will late-binding in C# make it easy to write code like that above. I need to move data easily in and out of the dynamic scope from the surrounding static scope, whether it's a single object marked dynamic or a whole block. And it needs to be predictable with respect to the scoping rules in both forms. I can't help but think about how statement lambda expressions and anonymous methods reach out into the surrounding scope as needed. The problem with dynamism though is know which references should reach out and which ones should not.
I suppose the more I think about this, the more I wish that the DLR were injectable into the statically typed scope, making (2) that I described above a bit easier to write.
One last thought: assuming that it comes down to marking an object as dynamic (not a block), what would be the harm in enhancing the var "type" to do this, allowing:
var jabberwocky = GetDynamicObject();
instead.
-- Kevin
First impression:
WOW
Second impression:
I am not entirely sure... i still go "wow" but I have maybe a few concerns. The dynamic{} code might look a bit awkward. Also what about totally prototype like code, like where objects are not tied to a particular class, but instead can be shaped lateron? And aside from this, what happens when objects are modified or extended at runtime, can these changes be reflected back upon the C# world?
Anyway dont get me wrong, so far it looks great
Maybe I have an oversimplified view of this subject, but have you considered something like this?
static void Main(string[] args)
interface IMyInterface
void SomeMethod();
string someString { get; set; }
int this[int index] { get; set; }
dynamic IMyInterface myDynamicObject = GetDynamicObject();
if (myDynamicObject != null)
myDynamicObject.SomeMethod(); // call a method
myDynamicObject.someString = "value"; // Set a field
myDynamicObject[0] = 25; // Access an indexer
where the dynamic keyword tells the compiler to emit code that at runtime compares the signature of the interface with the signature of the object. myDynamicObject would be set to an instance of the interface that is a proxy to the object if they are compatible otherwise it would be set to null. All the user of the object would compile and run as it does today.
For all the reasons Eric mentioned, and then some, please tread softly here. If you really need to do this, you can already do this. Make it too easy, and you'll have every idiot who thinks code reuse is done with ctrl-c,ctrl-v making every single call dynamically. This is the problem we currently have where people use generics willy-nilly thinking they are writing code in a generic fashion, not realizing what the compiler does when it comes across generics.
Speaking of generics, how do they match up with dynamic? Bit of an interesting topic, I'm sure.
Also, performance, performance, performance. The word Dynamic translates into "trading performance for developer convenience" in just about every case you come across. A lot of developers don't make the connection that doing things dynamically makes for extra load at run time most of the time.
Charlie Calvert blogged about dynamic support in C# 4.0 . I love this for two reasons. One it will enable
Firstly, I apologize for my negative comment. I realize that things are early and that there are surely many other announcements in the near future.
C#1 was a great start and C#2 was brilliant. Hands down the best thing about version 2 was the work done to support generics.
However, I was extremely disappointed with C#3. Almost everything introduced was nothing more than syntactic sugar. It enabled nothing that I could not already do before.
Now comes "dynamic lookup". Again, nothing that I can not already do with reflection.
I'd like to see new features that enable new scenarios. Two in particular that I have been really missing are support for 1) generic variance and a way to do 2) generic operator overloading (can't constrain T to a static method).
With that said, I'm looking forward to hearing more about the future of C#. Hopefully the next version will be more to my liking.
I agree with David. I use C# because it is statically typed. That is also why I stay away from VB and languages like IronPython etc. I do *not* want dynamic code in my C# code.
Carlie Calvert wrote:
"Please note that the proposed C# features discussed in this post are not designed to convert C# into a dyanmic language, only to make it possible to call code written in a dynamic language and to make COM interop simpler."
Understood. However, it should be put in a library, not built into the language. I think that reflection is sufficient, but now that we have the DLR, just extend it as needed.
Thank god!
I have recently written screeds of reflection based code - there was no other way. I was crying out for something like this. To those who say "use python" or whatever... I don't have the choice and guess most devs don't either.
Oh yeah, please give us something like Missing Method from smalltalk it adds a lot of power in dynamic dispatch use cases.
Any chance of having a similar keyword in Visual Basic? It's neat that I can already make dynamic calls in VB, but I believe it currently requires one to turn Option Strict Off. Something more fine grained would be awesome.
C#小组CharlieCalvert在其博客发了一篇有关C#语言未来方向的文章,这片文章介绍了一个叫做动态查找的特性,它为.NET语言(包括建立在DLR上的语言)能有一个统一的动态运行时名称绑定方案...
Quote: "Now comes "dynamic lookup". Again, nothing that I can not already do with reflection"
Might I suggest assembly language? There's nothing you can't do in it, and there's none of that nasty 'syntactic sugar' you seem to object to. Seriously.
I think it will be very cool but probably unnecessary if the .Net frameworks let using multiple planguages in a class. A special project type class extensions may be defined or may be a syntax like below can be used:
@Use Language=VB .Net
... Some VB .Net Code
@End
But by the way this may reduce readability and could make the code look uglier or messier.
Tali,
There would still be strong type checking on variables declared in a dynamic block. If a method declares that it is going to return a string, or a DataTime, then an exception would be raised if a compatible type were not returned.
Right now, it seems likely that each call in a dynamic block will be handled individually, so that some of them might execute and then an exception would be raised if one failed. These plans are not certain, but that is the most likely scenario.
Commenter,
You asked:
"How about using -> instead of . for dynamic lookup"
This type of thing was discussed in depth. Early drafts of the team's plans tended to include it, but now the team is leaning away from it. No decisions have been made at this point in time, of course. And there were various different characters proposed, not necessarily focusing on the C like syntax you suggest. But still in the same general vein.
I also strongly agree with Thomas.
I'll also throw one other option into the mix. What about something like this
object myDynamicObject = GetDynamicObject();
myDyamicObject."SomeMethod"();
The quotes around the method name make it clear that, as far as the compiler is concerned, the name of this method is just a string, to be looked up at runtime.
To me, the main thing is to find something that doesn't require a block to be wrapped around the code, and which lets me (any my IDE's syntax highlighing) tell exactly which calls are dynamic - either by the variable they are made against (as in Thomas's suggestion) or by the way the call is written.
This belongs in a library, not baked into the language.
We have reflection and we have DLR. You said that the DLR will be the "infrastructure on which the C# team implements dynamic lookup." If the existing DLR infrastructure is not sufficient, then why not just extend it? I fail to see what advantages special syntax will provide over a pure library implementation. It serves no purpose but to further pollute the language when a library is the appropriate place to be doing this.
I am strongly opposed to this.
Based on my experience with VB (which really already has this), I agree with Thomas & Miguel. Blocks are the wrong granularity. Either variable or call level would be great.
L'�quipe de C# d�voile un peu plus sur les principaux prochains ajout du langage avec l'aide de rubriques nomm�s Future Focus. La premi�re de la s�rie concerne le Dynamic Lookup....
@Charlie - "The idea of declaring an entire object as dynamic is also in play, but there is a concern that a broad granularity of that type is not right for C#."
I couldn't disagree more. Declaring an entire block to be dynamic is what is too broad. Declaring a single object is a more narrow approach that allows the developer to target the dynamic calls more appropriately. Perhaps even forcing individual calls to be made using a dynamic syntax would be the right way to go. But forcing a developer to use a dynamic block every time they want to make a dynamic call just makes the code harder to read.
@Thomas - "If everything inside the 'dynamic'-block uses dynamic lookup, then you'll loose type safety for everything inside this block..."
@Charlie - "...the team is considering first attempting to resolve all code in a dynamic block statically, and using dynamic lookup only if the static calls can't be resolved at compile time."
You're talking about early binding; Thomas is talking about type safety. They are two different things. Sure, you can still early bind to anything that is statically accessible; but for anything that is not, you turn it into a dynamic call. So the developer has no way of knowing that when he mistyped that method name, instead of getting a compiler error, it gets turned into a dynamic call instead, which results in a run-time error.
The more I think about this whole thing, the more I think it is a bad idea that will lead to long-term negative consequences. Giving developers a way to easily lookup and execute dynamic calls at runtime is a good idea; baking into the syntax of the language is not. Can you please explain why you feel it is necessary to make it a part of the language, when you could just make it a part of the reflection library, or its own library, and it would function just as well, not to mention be useful in other languages as well?
* Type safety
Good description. Further to the points you've made, I think it might actually be helpful if "dynamic object" is the only kind of dynamic variable that can be declared. E.g. you can't say "dynamic someOtherClass". That reduces the confusion that could arise from having a mix of early and late bound calls on the same variable, since so few early bound calls are actually possible on "object".
* Why not use a library?:
I presume that the desire to put it into the language is because that gives the cleanest and most compact syntax. I would imagine that the cleanest that a library-based approach could look would be something like this:
myDynamicObject.Dyn("SomeMethod")()
In this hypothetical example Dyn(string) is an extension method, that does the reflection and returns a delegate to the named method, which we can then invoke.
The problem is in passing parameters to the delegate, even though the compiler doesn't know it's type. That might require a language change to introduce some kind of "dynamic delegate", which is a delegate that you can call with any parameter list you like, without the parameters being checked at compile time. E.g. allow this
dynamic delegate d = ...
d("Foo", "Bar", 10, false);
instead of this
delegate d = ...
d.DynamicInvoke("Foo", "Bar", 10, false);
There might be no need to actually use the "dynamic" keyword on the delegate. Instead, it could be set up so that all calls on delegates typed as "delegate" are dynamic - i.e. d(params...) equates to d.DynamicInvoke(params...) - but all calls on strongly-typed delegates (i.e. subclasses of "delegate") are early bound as they are now.
While this involves less messing with the language, it still requires some change, it doesn't really support setting properties dynamically, and the syntax is a bit more ugly than a fully language-based solution.
I'd much rather see something like this (as others have already stated)
dynamic myDynamicObject = GetDynamicObject();
myDynamicObject.SomeMethod();
myDynamicObject.someString = "value";
myDynamicObject[0] = 25;
or perhaps
[dynamic] IMyInterface myDynamicObject = GetDynamicObject();
The block idea is a bad idea in my opinion. I'm sure it's easier to implement, but is that good for the language in the long run?
The idea of the interface posted by Hans gave me another similiar idea.
I like the fact that c# is 100% type safe and I like that i can rely on that.
But even so I do see where th Dynamic typing could be nice to have.
but instead of
object MyObject = GetDynamicObject
how about:
internal dynamic class MyDynamicBasedClass : DynamicClassIdentifier
public dynamic void SomeMethodOnDynamicObject(string someargument);
public void MyWonMethod(){
//do nothing and return
That would make the coding style the same as we have it today. It would be kinda type safe. It would meet the wishes of Thomas and others and it would be very readable and intellisense enabled (with a new icon for dynamic methods/properties o.c.)
Lots of ideas, issues, problems, solutions...
Its actually good taking feedback from community - such brainstrorming would help in getting it right the first time - a must for a language feature like this.
I too have my suggestion:
/// start
// define an interface normally as we do now
interface theDynamicObjectInterface
int theProperty {get; set;}
// Something of this sort we do currently as:
//
// theDynamicObjectInterface theDynamicObject = (ItheDynamicObjectInterface)new theDynamicObjectClass();
// the above syntax gives a runtime error "Unable to cast..." if iterface and class implementation do not match
//
// this behavior can be altered by an explicit interntion of developer as:
dynamic theDynamicObjectInterface theDynamicObject = GetDynamicObject();
// this syntax will automatically try to cast returned object as the specified interface and
// if there is an error, object will be set to null
// here after there are normal calls which otherwise also we do
if (theDynamicObject != null)
theDynamicObject.SomeMethod();
theDynamicObject.theProperty = 10;
/// end
I might me missing compiler internals here, but I guess the idea is communicated.
Points to note here:
1) One point resolution for member mapping, i.e. at the time of assigning object to specified interface
2) Full intellisense
3) No special delimiter required for call-to-call basis mapping (.. or ->, etc.)
4) No dynamic code block
what I'd really like similar to this is an infered duck typing. That way I get type safeness and intelisense but don't need adapters.
In my example the 2 methods (f1 & f2) have return types which do not implement IHasText, however they both honour the interface. A new *infer* keyword could behave like the *as* keyword and return null if a type cannot be coerced into the supplied interface. Under the hood the compiler can follow the adapter pattern or what ever clever stuff is required :-)
e.g.
IHasText{string Text {get;}}
Label f1(){}
TreeNode f2(){}
void func()
var ht = f2() infer IHasText;
// use ht.Text
Microsoft haven't committed to anything in C# 4 yet. However, there have been hints about what they've
C# 4 slicing index notation ala python.
var l = Enumerator.Range(1,100).ToArray();
for (var i in l[25:75])
Console.WriteLine(i); //prints ints from 25 to 75
including pythons start/end defaults
l[:5];// the first 5
l[96:];//the last 5
Heres an off topic question. Recently the C++ team has released a beta of the upcoming MFC changes. Included in this are some nice UI changes that incorrorate alot of the Office/Visual Studio UI enchancements, such as docking, theming, Ribbon Bar, and more...
Is there any plans to update WInForms to include these enchancements?
I proposed the idea on this topic a while back of using the type inferencing available through the "var" keyword to support reflective, late-bound lookup. Now, we all know that "var" isn't a type but the compiler could allow references obtained that way to bind late. For example, to reflect and find SomeUnknownMethod() at runtime, this would NOT be allowed:
MyClass m = GetMyClass();
// illegal b/c MyClass is not known
// to implement SomeUnknownMethod
m.SomeUnknownMethod();
However, this would compile:
var x = GetMyClass();
// legal b/c var allows for
// late binding on references
x.SomeUnknownMethod();
Being marked as "var", the reference x gets special dynamic treatment.
I like this better than anything else I've seen here because:
1. It is a simple extension of the type inference concept that already exists.
2. It would force certain C# developers who might use "var" a little too often (if you known what I mean) to avoid the possible dynamic side effects introduced by this enhancement.
--Kevin
What a terrible idea. It seems like we keep taking this circular path with languages that takes us back to exactly where we started, but with new toys.
So much for type safety and code that can be analyzed by external tools for issues
@John Rusk,
I can certainly see your point about dynamic calls being easier if the syntax is available in the language. However, I am VERY concerned about the long term effect this feature will have on the language. Much has been made in the past about new language features starting out with "minus 100 points" (), and that they must prove that they have significant enough value that they can overcome the inherent negative impact that adding any new feature has on a language. I am far from convinced that this feature meets that criteria. I would like to hear from the language team what they think about that issue, as well as other people in the community.
Una vez salidos al mercado .NET 3.5 y C# 3.0, el equipo de desarrollo ya ha comenzado a pensar en las
I think the best approach is using a special operator like ..
And how about constructing objects dynamically? Like:
Type t = typeof(SomeClass);
object dynamicObj = new t(10);
-or-
object dynamicObj = dynamic t(10);
And then the runtime call the correct constructor and create the object.
So, the proposed block syntax might have two motivations that I can think of:
* It's for implementation/performance reasons. Some context will be built up and held within the block in order to perform the dynamic lookup. This can then be discarded when the block is exited. If this is the motivation then I think the syntax gets in the way of usage and any performance considerations should be 'hidden' and not emphasised in a block syntax.
* It's to deliberately demarcate dynamic lookup code so that programmers can see it being used. If this is the case then I can see the point. But at the same time I think it might make the facility too annoying to use by introducing variable scoping issues and mixing up static and dynamic lookup.
My opinion is that dynamic lookup happens when you call a method/property/indexer on an object, so the syntax should be at that level, not at a block level.
Thanks for publishing this blog post by the way, even if it has resulted in us all annoying you with our impractical suggestions. :)
I welcome the prospect of being able to (easily) make late bound calls using C# and anything that makes COM/Office interop easier, without going the whole hog of introducing optional parameters into the languages, is particularly welcome in my opinion.
Although I do have some sympathy with those who would prefer C# to remain wholly static, I think the time has now come where the language can afford to relax a bit on this and that, if it doesn't, it may find itself losing popularity to languages which do.
Personally, I'd like to see the day where I can do all my programming in C# - it may be asking too much but that would be my ideal.
As this is going to be a .NET wide facility, I suppose the implementation which the C# team eventually settles on will need to be consistent with the DLR infrastructure but, if there's any choice in the matter, I agree with most of the other posters that having a dynamic block is not the best solution.
In fact if, as Charlie said, there is no reason to consider a dynamic variable as anything special, I see no reason to introduce a new 'dynamic' keyword or attribute at all!
All you need is a special operator for dynamic lookup and a rule which says that this can be applied to any variable or expression of type System.Object but not any other type. The compiler won't then check the call for correctness (except as potentially valid C#) and the onus will be on the programmer to get it right.
As for the choice of special operator, I'm not keen on .. which looks like a range operator and I don't like -> either because that's currently used only for unsafe code. I'd prefer something different such as:
objectExp~SomeMethod();
which would stand out more.
This will still make Office interop code very easy to write (with the help of Intellisense)and you won't have to decorate all your COM object variables with 'dynamic' or include them in a dynamic block.
It would in any case be difficult to use a common word such as dynamic as a new keyword (except perhaps as a contextual one) because it's sure to break some existing code which hitherto the C# team have been almost paranoid to avoid doing.
That's pretty cool, Alan. I wish I had thought of that. ;) Now, what happens when I do this?
===================================
string X = "kilroy";
objRef~SomeProp.SomeMethod( X );
What about the reference to string X? Should the dynamic call be able to reach into the local, statically defined context like this? What about?
Customer Z;
objRef~SomeProp.SomeMethod( out Z );
That's certainly what I'd like Kevin and I can't really see why it shouldn't be possible - the call, in it's entirety, will either succeed or fail at runtime.
However, given that the C# team have come up with this idea of a dynamic block rather than the (more obvious) ones of dynamic variables or a dynamic lookup operator, it makes me wonder whether we may be missing something here and that there are problems mixing dynamic and static contexts.
You can't really tell anything from the current implementation of late bound calls in VB.Net. If you set Option Strict to Off, the two examples you gave work fine but it appears that the whole context of the program is treated as dynamic. For example, even the following statement is allowed by the compiler:
Dim i As Integer = "Hello"
which is certainly not something we'd want to see in C#, however dynamic lookup is implemented.
If this is implemented, I am highly in favor of:
dynamic object myObject = ...
instead of the dynamic block. Having said, that I'm not really sure that we really need this at all. Static binding is your friend.
As for the Java suggestion earlier... the reason I like C# is that it IS like Java, except that it works correctly and isn't horribly slow (which is largely due to the fact that it is NOT dynamic.)
>>dynamic object myObject = ...
Im voting for that approach too.
Much better to attach the late binding to a specific variable than to a scope.
It should also apply late binding to the result of a late bound call.
eg.
dynamic object foo = GetSomeObject...
//traverse a latebound property path
foo.bar.harr.harr (1,2,3);
Maybe require that all uses of the "dynamic call" operator (whether it is written as .., -> or ~) appear only WITHIN UNSAFE BLOCKS?
After all, these are unsafe operations....
@Octavio
Your suggestion makes a certain amount of sense, however, in C# unsafe blocks are used to indicate code that might produce unverifiable IL (as opposed to normal C# code which is guaranteed by the compiler to produce verifiable IL). So there are two different meanings for unsafe here, and they don't really mesh well with each other.
Σε συνέχεια του post περί late binding , ας δούμε πως μπορούμε να πετύχουμε σωστό late binding, χωρίς
The syntax dynamic object myDynamicObject = GetDynamicObject(); is the best suggestion so far.
- The dynamic { ... } code block is too coarse as many people have already said.
- A dynamic object presumably would not have both, static and dynamic methods so why introduce a special dynamic call operator such as "..", "~", etc.? Can anyone ever envision calling myDynamicObject.GetName() (a static method with one dot invocation) and then calling a myDynamicObject..SomeUnknownMethod() (the two dots notation) on the same object? Not likely, dynamic objects will almost certainly be composed entirely of dynamic methods. If that is the case, then why introduce the extra calling syntax clutter? There is a certain aesthetic beauty and elegance to consistency that ought to be maintained. Ask C++ developers how they liked having two different calling operators in their language. This ex-C++ developer says NO.
- Those who think they can pre-declare interfaces on dynamic objects are forgetting that the objects are dynamic... ie. some languages allow methods to be added or removed from such objects at runtime. Indeed some languages allow objects to be fleshed out with method sets determined completely by runtime conditions. Take a look at look at the vast codebase of oo Javascript in use in the wild. Take a lot at the latest Ajax or JSON libraries. The whole point of Dynamic objects is that you can't predict or know ahead of time what methods or properties they will possess at any point before you acquire a runtime reference to them. As well, who in the heck would want to pre-declare some of the Office Automation objects before they use them? Have you seen some of the interfaces on these things? There are hundreds if not thousands of methods whose signatures you'd ahve to predefine. Besides, why would you even do this instead of using the COM type library that ships with the interop assembly? And this is describing a scenario of using COM objects who actually HAVE a statically defined interface to begin with. Forget about all that if you are actually dealing with objects coming from a dynamic language. Where pre-declared interfaces may be of use if one is using only a limited set of functionality on an incoming dynamic objects and wants to impose a statically bound interface on the interesting subset of methods. In this case, the interface acts as an intellisense-friendly facade to the underlying object which may in fact possess a much larger set of uninteresting or undesired methods. In this case, the runtime would have to enforce that there exists a way to coerce the underlying object to map onto the pre-declared interface. ie. All the pre-declared method signatures would have to have matching methods in the underlying object.
- For those who are concerned about C# straying from its statically typed roots, no need to worry. No one here is saying that C# will be equipped to MAKE dynamic objects, but rather CONSUME them... and given that, then what is the objection? Why not open the door of possibilities to using all that code in the wild from within C#? Doesn't seem to detract from the attractiveness and utility of the language one bit. If you are still ideologically opposed to this, then the answer is simple: just make sure you never use libraries that are created in dynamic .Net languages (like Python or Ruby, etc.) Simple. We can all live in peace and harmony.
In summary, my vote is for:
NO to dynamic { ... } code blocks, and NO to special dynamic call operators.
I would like the .. operator :-)
First, thanks for discussing future features with the community!
There is another scenario where a 'dynamic' keyword would be useful: in constraints on generic types. I would like to be able to say
public class Matrix<T>
where T: dynamic INumeric
Matrix<double> x = new Matrix<double>();
In this case 'double' does NOT implement our hypothetical interface INumeric, but if it has all the methods required by that interface, the compiler will allow the generic object to be created.
This is all static and the compiler should object if it can't verify the interface at compile-time.
Such constraints are what's missing in order to make C# truly great for numeric/scientific computations. Other scenarios include treating objects as collections even if they happen not to implement IList, etc.
/Sten
C# nelle future versioni di Visual Studio
Good information. Thank you.
I would like to request the ability to coerce anonymous types into interfaces. So you can use LINQ for more than just databinding, so you can actually return strongly typed objects from any method without having to declare all of your types. Something like:
public IExample[] GetExamples()
return (from e in examples select new IExample { P1 = e.Text }).ToArray();
If you had methods on the interface than either create an empty method that returns the default value or allow delegates to be attached to the interface at creation time.
maybe like:
public IExample GetExample()
return new IExample { P1=this.Text, Run=this.RunExample };
private void RunExample()
//do some stuff here.
I think they need dynamic types in C# because the other dynamic languages dont use the C style syntax(at least not popular/useable ones)
Second-
It sure would be nice to have some more dynamic behavior with Generic types even polymorphism. And while I am at it throw in interface property attributes recognizeable as [Column] in Linq so you can use linq more dynamically/genericly as well.
C# is a changing language. C# 1.0 was all about core component-support. With C# 2.0 generics have been...
I feel like I haven't had a chance to respond to comments in the last few days. As a result, I wanted to take a moment to assure everyone that we have been reading these comments, and that the design team has seen them, and has taken them seriously.
It's perhaps worth reminding everyone that our goals here are twofold:
1) We went to be open and share our plans with the community.
2) We want to absorb your feedback and make good use of it.
Looking at those two yardsticks as a way of measuring our progress, I would say that this has been a very successful process for us. It is great to be able to share ideas with the community, and your input has been very useful to us. We are not yet ready to say exactly how these comments have influenced the team, but I can assure you that they have influenced us, and they have had a positive impact on our planning process. Thank you so much for the comments you have submitted so far.
@Charlie,
Why do I get the feeling that you are trying to prepare us for the fact that even after all of the feedback you have gotten from this blog, you still decided to go with your original dynamic block idea?
@Simon,
"A dynamic object presumably would not have both, static and dynamic methods"
For objects instantiated by a dynamic library, you are probably right. But imagine if you want to use dynamic method invocation to invoke a method declared as private in a statically defined class using reflection? In that case, it is certainly possible to imagine cases where you might want to make both static and dynamic calls on the same object; and at that point, a dynamic call operator might make sense. Not necessarily voting in favor of it, just pointing out that it is not as ridiculous as you made it sound.
I've read all comments, and I vote for this:
dynamic object a = GetDynamicObject();
a..SomeMethod(x);
a.ToString();
a..SomeProperty = "123";
I want to assure you that the design team has been actively engaged with this process and is really grateful for your input and has found it very interesting and helpful. Our goal is to be open and to share information freely, and of course we actively gather feedback for the design team. If you reread the initial paragraphs of this post, you’ll see why I don’t want to promise specific outcomes, nor allow myself to set expectations too high. I promise that the comments that have been made here have been and will continue to be carefully monitored by myself and the design team. I can also promise that your comments are having a real and positive impact. They aren’t being ignored. They are actively and sometimes heatedly discussed. The design team has been interested, excited, and engaged by the input you and others have given. This process has been a success so far, and that means we want to do much more of it. We all appreciate the intelligent and courteous feedback we have received, and we are very happy about its success.
Love the idea, but the dynamic keyword is indeed a bit limiting - since it's most logically tied to an instance, the "this is dynamic" magic should be tied to an instance/variable instead of a scope.
What Andrew Davey said about IQuackFu from Boo is good, but IMHO the easier and more powerful approach is also from Boo - the "duck" type (), which you declare a variable as and then the compiler knows that it's a dynamic type. Then you can pass "duck" objects around without having to deal with the dynamic keyword. Then tools (like the debugger) also know the instance is "special" and interact with it as such.
Instead of duck, though, perhaps System.Dynamic or similar, since it probably makes sense to have it represented in the BCL since you may want to string some static methods off of the type (System.Dynamic) that helps runtime interaction with such objects, like easier-than-reflection inspection of methods/properties/etc, or Ruby's "reopen this instance/the entire class" support, or whatever.
Back to the IQuackFu/IDynamicDispatch idea - as long as the compiler implements it as a fallback so "regular" method calls that are implemented by the type keep working as normal, then that's fine with me - it's effectively Ruby's method_missing at that point, which would be useful to have in some situations.
The combination of the two gives you both fully-dynamic instances (with the duck typing aka System.Dynamic) and partially-static, partially-dynamic (with IQuackFu aka IDynamicDispatcher), so you can choose what works best for you.
The idea is great, but I really fear the dispatch keyword+scope approach would make it less useful (read: more cumbersome) to interact with.
Ok, so it's just in the planning stages, but you may have run across Charlie Calvert's recent blog post
VB6 and VB.Net developers know this feature: "Late Binding" and C# developers have often ridiculed
Ok, so it's just in the planning stages, but you may have run across Charlie Calvert's recent
Hey Charlie!
You, of course, remember that Delphi has also had this same functionality since version 3 (10 years ago) by using dynamic Variant dispatching. In natively compiled code, no less. I'm just saying... ;-) The cycle is coming around again...
Say 'Hi' to Anders, Chuck and the whole gang for me!
Allen.
Charlie, Mads;
I definately like the idea of adding some dynamic typing support for C#. I've seen a lot of comments on various ideas for implementation and wanted to throw in my own.
Using 'dynamic' as a block is a good idea that seems to cause usage problems when defining initial values (such as in field member declarations). While this can be resolved by placing a dynamic {} call in the ctor or cctor you might also provide a dynamic() keyword (similar to the unchecked{} vs unchecked() syntax). This would allow you to do the following:
class MyClass {
object foo = dynamic(SomeStatic.GetSomeDynamic().someDynamicMethod);
void Method01() {
dynamic {
foo.Method01();
I would also recommend allowing the 'dynamic' keyword be applied to a method or type similar to the 'unsafe' keywoard, informing the compiler to widen its usage of the DLR based on the scope of what is dynamic (type, method, get, set, add, remove, and at the expression level).
The key here I'm seeing is that C# is *not* a dynamic language and should not become one, but by adding a dynamic{}/() language feature merely lets you call into the dynamic language aspects.
Dynamic is also useful in a LINQ scenaro, e.g.:
void Foo() {
var q = from o in GetData()
where o.State = "WA"
select new { CustomerCount = o.Count, ... }
foreach(var r in q) {
print(dynamic(r.CustomerCount));
I also think adding in some type of interface based manipulation of the dynamic context without the expense of having to use a RealProxy would be useful as well. In addition, it would be useful to be able to test for the existance of a dynamic field, method or property before a call using a "has" keyword followed by a signature (matching a method, field, property, or event signature), e.g.:
dynamic void Foo(object bar) {
if (bar has void Baz()) {
bar.Baz();
if (bar has string Text { get; }) {
print(bar.Text);
I also think the idea of supporting dynamic instantiation of a type by overloading the new operator:
/*
new StaticTypeName(); /* standard new */
new { PropI = 1, PropS = "2" }; /* anonymous type new */
new (typeInstance); /* new using argument of System.Type */
new (progid="Some.ProgID"); /* new using a progid */
new (clsid="SOMEGUID-00ad-00ad-0a0a00..."); /* new using a CLSID */
*/
void Foo(Type t) {
object f = dynamic(new (t));
dynamic void Foo() {
var x = new (progid="MSXML2.DOMDocument");
x.loadXML("<foo/>");
The key here is that complicated reflection calls can be pared down to simple keywords, which could take the guesswork out of reflection.
Also if dynamic is effectively a compiler macro over reflection, it might be useful to be able to mark certain dynamic calls based on binding flags, e.g.:
class Foo {
private int bar = 1;
Foo f = new Foo();
int bar = dynamic(f.bar, private);
Charlie,
I can certainly appreciate that you cannot promise any specific outcome. I can also appreciate that sharing these plans with the community does not mean that this is our chance to design the feature; the inmates cannot be allowed to run the asylum, as it were.
I suppose I am simply wary because I have seen this too many times before. A team decides on a new feature it wants to implement, debates it internally, and comes up with the approach they want to use, and then exposes that approach to the community. At which point, there is a very strong community response toward another approach, or away from the feature entirely; but at that point it is too late, because the team has already convinced itself of "the right way" to do it.
I can only hope that will not be the case here; what prompted my comment was that, although the tone of your comment was positive, I felt it ringing with an undertone of "but don't get your hopes up." Which, as you say, you had already stated earlier.
Please don't let my pessimism or cynicism dissuade you from continuing the series. I would love to see what else the team is coming up with, even if I don't get to do it the way I want :)
This will become very handy for mine MVC RouteProviders in SQL en XML. Now I have to use dynamic compiling to create a structure to pass the parameters which are normally build as
new { Controller="HomeController", Action="View", ID="ObjectID" } and passed to the MvcRouteHandler as an 'Object'
The compiler creates a anonymous typed when compiling, but you can't yet create really dynamic structures.
Sounds very promising..
Regarding type safety, I believe it's good to limit the dynamic keyword to a variable declaration. But also, it shouldn't be limited to 'dynamic object' we should be able to declare dynamic variables of any interface type.
Even on dynamic objects programmers know pretty well what to expect, but this way the compiler catches typos.
Example:
interface IMyCOMAPI
void MyMethod();
int CalculateSomething(int someParam);
dynamic IMyCOMAPI myO = GetDynamicObjectFromSomewhere();
myO.MyMethod(); //just fine!
myO.NyMethod(); // hey!! a typo!
I think that resolves many issues elegantly.
Perhaps I should add ...
'GetDynamicObjectFromSomewhere()' would be the only place where a binding related runtime excpetion would occur.
Optimizations, like caching reflection objects, would be done in an anonymous class that implements the interface and actually takes care of the binding.
This way optimal use of a dynamic object can be planned by developers. Like initializing dynamic objects once, automatically binding upon construction, sotring it in a field, and invoke methods efficiently throughout the field's scope thanks to this.
Well, my 2 cents ...
Sebastian
Sorry, on a roll ...
Another benefit I just noticed (although I can see some criticism) of this method is that by using itnerfaces, we can pass dynamic objects to all consumers of the interface, even those that were not initially devised for dynamic object consumption (assuming we use a predefined and already popular interface). This is were the possible criticisms arise, because although everything except binding can can be statically checked, the potential remains for misuse.
I however think compilers are there to protect us from typos and similar mistakes, not from not understanding and API.
Hey, me again heh,
It's later in the day and I realized the following: There doesn't need to be a 'dynamic' keyword at all. All that's really needed is a way to wrap dynamic objects in anonymous interface implementations.
For COM:
A dynamically bound COM object could be created by a generic (as in generically typed) COM object factory.
void MyMethod();
int CalculateSomething(int someParam);
IMyCOMAPI myO = new DynamicCOMObject<IMyCOMAPI>(guid /*or pointer to object or whatever*/);
myO.NyMethod(); // hey!! a typo! compiler detected as always
For the DLR and its dynamic objects:
The DLR can return dynamic objects, like it normally does, which will be dynamically bound to an interface at the developer's will.
Something like perhaps:
object o = dlrObject.GetDynamicObject();
IMyCOMAPI myO = DLR.BindObject<IMyCOMAPI>(o); // no special operator ever needed.
Perhaps I'm missing something? some feature? It doesn't seem like an operator is needed at all.
First, for those that don't want dynamic features in the language, get over it or stop using C#, because what's being proposed already exists. The suggestion to move to Java doesn't help, because it exists there as well. In both, the feature is known as reflection. The only difference here is we're proposing language syntax to make it easier to accomplish. Now, if you're one of those that doesn't care for syntactic sugar, then make that argument.
I strongly believe our best bet is a new operator for this.
void DoSomeDynamicStuff(Type type)
// reflective construction
object instance = new type!(10);
// non-reflective usage
if (instance.GetType() != type)
throw InvalidOperationException();
// reflective method call
instance!DoSomething(20);
// reflective field/property access
int result = instance!Result;
The ".." syntax would work as well, but I believe the "!" syntax is superior ;).
This syntax makes the granularity as small as possible, which is best, IMHO. It also makes every call explicit to both the compiler and the developer(s). You always know if something is static or dynamic.
This Dynamic are direct runaway from strong typification, but the last concept is foundation of C#.
We need other higher-order approach for this problem.
I think, we must to proceed from strong typification
as basic.
Simple Example (WSH inline):
// There is begin of example--------------------
using System.Scripting.WSH;
string StringBox = string.Empty;
// in the next scope provides other (read: dynamic) rules
script (WScript ws)
...
exl = ws.CreateObject("Excel.Application");
StringBox = exl.SomeMethod();
// There is end of example----------------------
P.S. Sorry for my English. I am russian developer.
It would be nice to have more flexibel operator overloading, like arbitrary operators instead of a fixed set.
Aren't you basically just adding VB-style late binding to C#?
I wanted to thank everyone again for their great suggestions. The positive and thoughtful nature of your feedback is greatly appreciated.
We are now certain enough of our plans to confirm that your comments will lead to significant changes in the way we implement this feature. We are looking forward to the time when we can get back to you with concrete information on the exact nature of our new plans.
The success of the first Future Focus post has made it easy for us to continue sharing our plans for
Well since we're throwing random ideas about I'd like to join:
There's already extension methods but they do seem a bit limited in some ways so what about 'extended scope':
!dynamic,with(GetDynamicObject())
.SomeMethod();
.someString = "value";
[0] = 25;
The only new keyword here is "!" for marking beginning of extended scope that brings in different entension delimited by ",".
Now of course bringing a ton of weird extensions would likely always mean throwing away intellisense atleast in v1 but maybe if it proves popular some support could be added to add some intellisense features even in extended scopes.
"So much for type safety and code that can be analyzed by external tools for issues"
That's a very good point.
The "infered duck typing" suggested above seems like a good idea without going overboard like the extendable scope thing which practically would mean a language in language.
I agree with the duck typing concepts, but I suggest you simply extend the functionality of the as keyword.
interface IDuck
// returns the string quack;
string Quack();
// moves the duck the specified number of steps, and returns the new location of the duck
Point Waddle(int steps);
// note that this class does not implement IDuck specifically.
class RandomFowl
public string Quack()
// ... implementation
public Point Waddle(int steps)
then you can use it:
...
RandomFowl fowl = new RandomFowl();
// here the as operator infers that the RandomFowl object is compatible with IDuck, since it implements the required method.
// there is no need to specify that this is a "dynamic lookup" behaviour.
IDuck duck = fowl as IDuck;
if(null != duck)
{
duck.Quack();
Point location = duck.Waddle(10);
}
Lets go farther... What might also be interesting are anonymous interfaces... like:
interface duck = fowl as interface {
string Quack();
Point Waddle(int steps);
};
if (null != duck)
duck.Quack();
duck.Waddle(10);
Even better would be anonymous interfaces with the ability to specify failover implementation.
string Quack() : { return "Quack"; };
Point Waddle(int steps) : { return Point.Empty; };
So what you get with that, is something like if the class had inherited a base class with the methods Quack and Waddle implemented as virtual methods. If the class implements them, that implementation is used, userwise the interface failover definition is used... Even better if type constraints could be applied in that failover implementation.
Here's a more realistic example, showing type constraints in an anonymous interface with failover implementations:
class Person
private string _name;
public string Name
get { return _name; }
class Thing
private string _description;
public string Description
get { return _description; }
static void PrintDescription(object obj)
interface describableObject = obj as
interface {
string Description
{
get :
switch (this.GetType())
{
case typeof(Person):
{ return this.Name; };
break;
default:
{ return this.ToString(); };
}
}
if(null != describableObject)
Console.WriteLine(describableObject.Description);
List<object> someObjects = new List<object>();
Person person = new Person();
person.Name = "Bob";
Thing thing = new Thing();
thing.Description = "Piano";
SomeOtherType foo = new SomeOtherType();
someObjects.Add(person);
someObjects.Add(thing);
someObjects.Add(foo);
foreach(object obj in someObjects)
PrintDescription(obj);
Output would be:
Bob
Piano
SomeOtherType
In the case of the Person instance, it couldn't find a matching Description property, so it went into the failover implementation which contained a switch block, that checked the type of the object instance, found it to be a Person type, and used the implementation specified in that case block. The Thing instance had a Description property already, so it just inferred the anonymous interface, The SomeOtherType instance didn't have a Description property, or a failover description defined, so it used the code in the default case block. Leaveing out the default case block here would have caused the cast to the anonymouse nterface to fail, and describableObject would have been null.
Maybe these ideas aren't practical, but I think they would be useful, and fit nicely with the existing langauge features, without compromising type safety.
Regarding syntax used... Using the colon to indicate failover implementation makes sense to me, since colon is used in the terniary expression syntax (ie: " (bool) ? true : false; "). Also, using switch case for the type constraints is a little verbose, and could probably be done more like the generic type constains, though, to be honest, those need a lot of work too.
I personally think using existing keywords is a much better idea than adding new ones. for example, using the default(Type) syntax was a great idea. Please don't add any new keywords.. Just find a way for it to make sense with the existing ones.
Troy
thoward37 at gmail dot com usefull.)
Kudos to Charlie Calvert for opening up the discussion of C# future features to the public (sure would
Hopefully the dynamics includes also the following syntax:
string method = "MyMethod";
object.method();
or directly:
object."MyMethod"();
or some other new syntax to accomplish the above.
Otherwise it's not really dynamic, i.e. you have to know the method names when you write the code. Runtime resolution of the method name should be possible like with reflection.
@anon: you said, "Otherwise it's not really dynamic, i.e. you have to know the method names when you write the code. Runtime resolution of the method name should be possible like with reflection."
Either way you need to know the method name when you write the code.. But you're right, it's not "dynamic", and that's kind of a silly word for it. It's "runtime method reoslution".
They are using the word "dynamic" in this context to mean that even though you know the method name and parameters that you want to call, the object may or may not actually have it at that point. The reason it's being referred to as dynamic is because the intention is to use this feature to deal with dynamicly typed objects.
So what is dynamic?
Currently, we describe what methods we want a type to have using static type declaration. That means that once you've defined the type, you can't add more methods or properties to it, or change it at all. In order to make changes, you need to make a new type. Those two types will be "different" all the time, no matter how similiar they are.
With dynamic typing, the type itself can be modified at runtime.
What they are discussing here is a "dynamic" lookup of the methods on a type. For example, normally, when you write:
someObject.someMethod();
The c# compiler will check the type of object *when you compile* to make sure it has the method "someMethod". If it doesn't have that method, it won't compile, and will generate an error.
The "dynamic" concept we're discussing is to allow you to write (using your syntax):
someObject."someMethod"();
to indicate that, while the method may not be there when I compile, it will probably be there when the code is running, because the type "someObject" is a dynamic type, whose methods and method names may or may not be consistent.
In that context, we're telling the compiler "don't check the method name now, wait until runtime, and do a 'dynamic lookup' of the method on the type, and if it's there, invoke it with these parameters."
This is definately something that can be accomplished with Reflection, in the sense that you could write a DynamicMethodInvoke method that took an object instance, method name, and a list of parameters, and it would call GetType() on the instance, then GetMethod() on the type, passing GetMethod the methodname, and the parameter's types in an array... That would return a MethodInfo for the oject, if it was there, then you could call Invoke() on the MethodInfo object, passing the parameters..
For some reason, Microsoft wants to make this part of the built-in syntax of the language. Probably to make it easier and more convienent for people to do that, instead of forcing them to write the described Reflection code a million times. It could easily a extension method, but then, the code would be really ugly if every call you made on a dynamically typed object had to be made like this:
dynamicObject.DynamicInvoke("Foo", new object[] { some, parameters, go here } );
So, implementing this as a language features is a nice idea, and the syntax you described would work fine for that.
Anyhow, it's important to understand that this is not in anyway bringing dynamic typing into c# syntax, but rather allowing c# to deal with dynamic types that are already in the .Net universe.
The way I described this, was to use interfaces. Interfaces allow you to specify the function prototypes of method on an object.
Wether you're using interfaces, delegates, or just regular methods on a class, you're doing fundamentally the same thing. You're describing a method by name, and a list of parameters, and you're indicating an object instance that you want to invoke it on...
Consider these three different ways of running the method Bar():
class Foo
void Bar();
interface IFoo
void Bar();
((IFoo)object).Bar();
delegate void BarDelegate();
void MyMethod();
Foo foo = new Foo();
BarDelegate bar = new BarDelegate(foo.MyMethod);
bar.Invoke();
So, in short, all we really need is to indicate, in some way to the compiler that it shouldn't check the static type definiton of the method call described by your code at compile time, but rather, emit code that lookup the method at runtime.
I like interfaces, because it is a concise way to describe a set of methods and thier signature that I can use as a single atomic check.
The downside in C# now is that if a type doesn't implement an interface at compile type using the "Foo : IFoo" syntax, then, even if the type has all the necessary methods to comply to an interface, there is no way to "apply" the interface to it after compilation. This is known as "duck typing" (ie. "if it looks like a duck, walks like a duck, and sounds like a duck.... it's a duck!").
I would like to be able to apply an interface to an object at runtime. I would also like to be able to describe the interface I want at runtime, "anonymously", and give default method implementations if the type does not implement a given method.
PS: Somebody please correct me if I misspoke. I don't have a debugger in the blog comment textbox... ;)
I'd say to still preserve type safety even if it means a litle more typing to declare dinamic method signatures beforehand.
In my example, the result of GetDynamicObject() is casted to an anonimous type specifiong the methods that should be bound, and if the binding fails null is returned.
var someObj = GetDinamicObject() as new {String Text, void Foo(int x)};
if (someObj != null) {
someObj.Text = "Bar"
someObj.Foo(6);
and you can do even more:
interface IBar {
int SomeMethod(int param)
var someOtherObj = GetDinamicObject() as new {String Text, void Foo(int x)}:IBar
the cast will only succed if the object returned by GetDinamicObject() implements IBar and has a public 'String Text' property and a public 'void Foo(int x)' method.
someObj.SomeMethod(3);
Maybe if the cast fails, it's not null that should be returned but, an UnboundDinamicObject instance that has null equality and should throw UnboundCallException when someone tries to do a dinamic call whithout checking for null, but this could have some issues regarding an Object.ReferenceEquals(someObj, null) call.
My opinion is, late binding is ok as long as it doesn't compromise type safety and adds the posibility to introduce type and spelling errors in staticaly type cheched language like C#.
I certainly hope I will be able to turn this "feature" off for our in-house developers.
Sorry for my English!
I think that one of ways for creating dynamic classes is like this:
using System;
class A
static void Main()
string s="class B { "
+" public void DisplayMessage() { "
+" Console.WriteLine(\"Hello from dynamic C#.\");"
+" }"
+"}";
dynamic B obj = new B(s);
obj.DisplayMessage();
Reason is:
1)Possibilities to create varible s dynamicaly and then create class dynamicaly.
2)Posibilities to read existing cs files and after modification create new classes dynamicaly.
Its not big deal. Well its good to hear that "dynamic" would be a built-in feature for C# developers (too).
I have already done this sort of work by writing my own classes using reflection. And really it worked some how the same way.
Please don't turn C# into a dynamically typed language...
Let me add my name to long list above opposing this.
I use C# primarily because I can depend on it being type safe by default. Dynamic lookup will destroy this. Can I disable the feature? In a team environment, I would hate to think about manually checking for this abusive code.
Further, as already mentioned, this type of functionality belongs in a library, not at the language level...
Please reconsider this. Whether you realize it or not, you're destroying C#.
I would think that something like this would be better accomplished through the DLR than through new syntax and type semantics in the C# language. As others have mentioned, a lot of us like C# because it is explicitly type-safe and we can assume that it will always be so. Anytime I need to interact with COM classes in a late-bound fashion I always use VB.NET and isolate that code from the rest of the solution.
My personal preference would be a method off of the DLR, or within the CLR, to allow an arbitrary object to be duck-typed to a specific interface. That method would perform the necessary inspection to ensure that the object members can be bound to the interface members and a proxy type that implements the interface it returned.
public interface IRecordset {
void Close();
object rs = GetRecordsetFromSomewhere();
IRecordset irs = DLR.DynamicCast<IRecordset>();
irs.Close(); // wouldn't we all like to do this?
I think that while being more verbose that this enables the scenario without trading type-safety.
I really don't want C# to end up with something akin to Option Explicit or Option Strict.
I really, really like Halo_Four's solution. It keeps C# entirely in the static typing world, doesn't require any new language features, but still gives us everything we are looking for in terms of making dynamic calls, both reflecting to the internals of an object and calls on dynamic objects. The only downside is that it requires an additional interface to be defined; but that can be a good thing, because that interface now exists in the metadata, and can be used like other type definitions.
Charlie, what do you think?
That's a very interesting article, and I can easily see places where dynamic typing might be useful. Have you guys looked into how ActionScript 3.0 deals with dynamic typing? I think they came up with a really elegant solution for dynamic typing.
I second to David, Halo_Fours solution is an safe and elegant way to do it. I have used the dynamic lookup in Delphi (with variants) but never really liked it because it is prone to typing errors. Following syntax would defentely be better:
dynamic interface IDog
void Run();
void Eat();
....
object o = LetThereBeDog();
IDog dog = (IDog)o;
dog.Run();
dog.Eat();
That's a very interesting article, and I can easily see places where dynamic typing might be useful. Have you guys looked into how ActionScript 3.0 deals with dynamic typing?
Hi,
thank you for sharing you current plans.
I've read through the comments, and saw some pretty good ones, yet also very bad ones.
I don't think it is bad to get feature from other languages into the existing one, unless it influences anybody who does not want to use it.
So:
- Do not mix it with var keyword. It is strongly typed, safe type. Any attempt to use it for dynamics would make all the people against var having actually truth.
- Do not mix it with interafaces. Interfaces are what they are for and taking them into dynamics makes the interface concept more complex, and turns dynamics into generics. Dynamics should just turn your calls into reflection ones. That's it, no interfaces. If anybody wants to wrap the dynamic object into class, why not.
- Do not restrict the base dynamic object to the type of object. Dynamics should not force you to cast to object if you know the base type.
- Make sure you can get anything you would need to do using reflection. Access static members, generic ones, etc. I agree with the suggestion of calling constructor dynamically as well, instead of kind of GetDynamicObject() method.
- As far as the scope is mentioned... it seems you could fulfill wishes of peoply only if you allowed both object and block scope. I don't think any keyword is needed at all, if you make the member accessor different. From what I've seen I like most the .. one, though I still do not feel 100% comfortable with this due to the .ctor and ..ctor methods. If you use special accessor, then no scope is needed, the behavior would be absolutely predictable (no attemps to early bind if the accessor is used) and the code would be much more clear.
- Do not allow dynamics to access non-public members. This is not the purpose of dynamics and developers should still have to use reflection for this.
If you make indexed properties also accessible, I would welcome them in static C# as well. ;)
I believe you will get this as right as you want and wish you to ship it as good as you wanted.
Jan
Here are some thoughts I have regarding the ideas of dynamic method calls in C#:
I can agree with all written above, just because all of the statements have reasonablу meaning...
I think we shoudn't use the sugar.
So, in my POV, i will use intensively code like this, which is IMHO actually do not loose meaning of word 'simplicity'.
It is my vision - i'd better appreciate to not thouch the language, but add compiler-generated stuff, and make a good support on a CLR, Frameworks and IDE;
//Compiler throws an exception when
//DynamicObject type is used in places not
//marked as DynamicMethod or DynamicProperty
[DynamicObjectAttribute("Company")]
object a;
[DynamicMethodAttribute]
int Foo(int typedA)
//DynamicObject is appears to users
//as concrete, non-instantiable, sealed
//(and so, non-derivable by users)
//ancestor class of System.Object class.
//Compiler treats all dynamic variables
//as derived(and, so, hidden from users)
//classes from DynamicObject class.
if (a.GetType() == typeof(DynamicObject))
try
// Compiler-genarated call would be like
//a.get_method<void, string>("SayHireMe")
//using some sort of late binding
if (((Action<string>)a.SayHireMe) != null)
//Already fail-safe call
a.SayHireMe("Hello, World!");
//Not so safe, i need more money:$1000000
a.SayGoodBye(-1000000);
a.SayGoodBye("Hello, World!");
//Intellisense analyses the usage of
//object of type codename "Company"
//and show both methods already used
catch(DynamicException)
try
MethodInfo[] mi = typeof(a).GetMethods();
if (mi["SayGoodBye"] == null)
{
Console.WriteLine("You can't say goodbye to your comany in such the way due to the fact, that object [Company] has no such a method, just because otherwise it will give you the possibiliby that you can not refuse. P.S. 'And give us $1000000 back!'");
}
else
//checking in/out parameters...
That's pretty cool, however, have you though about making it so that the "dynamic" isn't a scope keyword but instead applies to a variable? Like this:
-tony V.
exellent,plz include me in the program.
iwill be glade if you sent me more regarding C#.
nice time
Allow me to refine my suggestion a tad. I wanted to clarify what I had intended as well as correct a minor problem with my sample. As mentioned I don't think the semantics of C# should be changed to support dynamic dispatch. I would prefer a more intentional method of interacting with dynamic types.
My suggestion is to not modify the language at all. Instead, provide the facility through the DLR or through remoting to construct a proxy for an object given a defined interface. That proxy would handle the details of how the actual members are called and would handle .NET objects as well as COM objects to the best of it's ability.
public interface ICalculator {
int Add(int x, int y);
static void Main() {
object o = GetCalculatorFromSomewhere();
ICalculator calc = o.TryDynamicCast<ICalculator>();
if(calc != null) {
int value = calc.Add(2, 3);
Extension methods would be provided through the DLR that would construct the proxy. Suggestion methods as as follows:
// Try to create proxy for interface T, throw exception if object cannot conform to interface
public static T DynamicCast<T>(this object o);
// Try to create proxy for interface T, return default(T) if object cannot conform to interface
public static T TryDynamicCast<T>(this object o);
// Return whether or not object can conform to interface
public static bool CanDynamicCast<T>(this object o);
Or the methods could just be normal static methods.
What I like about this suggestion is that:
1. It does not change any semantics of C# at all. Only normal run-of-the-mill interfaces are used and C# remains completely type-safe.
2. No language enhancements are required, so this functionality could be built right now on the existing C# 2.0/3.0 languages, depending on whether or not extension methods are used.
3. You gain the requested functionality of allowing "duck-typing" in C# automatically.
4. You only need to do this work in one place and any CLI-compatible language can immediately benefit since you are only using the existing facilities within the framework. This will increase the pervasiveness of support for dynamic dispatch.
The disadvantage is that this method is more verbose since you have to declare the interface, but it is my opinion that requiring the intent to be declared keeps the language appropriately type-safe.
Also, it would prevent a dynamic object from being partially conformant to the requested interface. I can envision problems with dynamic dispatch using a "dynamic" keyword where the consumer needs to make several calls and some of those calls exist and others do. The code necessary to compensate could be complicated.
Anyway, I hope you consider my recommendation. In fact, I hope you can see it at all buried in the slew of comments on this article.
Justin
A number of people have suggested that for the dynamic case, the member access syntax should be made deliberately different to the usual dot syntax. There is a lot to be said for this. but it properly flags up the dynamic nature of what the code is doing.
But then I realised we can already do that today. Just make a class that has an indexer, which returns a delegate that takes a variable number of parameters:
Would this support Dynamic Dispatch mechanism? something like:
public void Something(int i){...}//(1)
public void Something(string s){...}//(2)
public void ADynamicMethod(object param)
dynamic{Something(param);}
ADynamicMethod("hello world") would then result in call to method (2)
ADynamicMethod(0) would result in call to (1)
ADynamicMethod(DateTime.Now) whould result in exception.
Is this a scenario that this mechanism will enable?
As for syntax, I see two issues here, that have been touched upon in previous commens.
1. please do not make it too easy to use. With that too many bad programs will be written by unexperienced developers.
2. Make it explicit, which calls are dynamic, and which are not.
The solution that seems the most appealing to me at the moment is going with BOTH options presented above.
public interface Ia
public int Something();
public void ADynamicMethod(Ia parameter)
parameter.Something();//called statically just like in CLRv2.0
parameter.SomethingElse();//compile time exception, list like in CLRv2.0
parameter.dynamic.SomethingElse();//late bound call
var dynamicParameter = parameter as dynamic;
dynamicParameter.SomethingElse();//late bound call
this has two advantages:
all dynamic calls are explicit, and we still have fine grained control over it.
using obj.dynamic.Method(), is similar to obj.base.BaseClassMethod() we already have, so it looks more familiar than ~@!.. and other syntax suggestions mentioned earlier.
Second option:
var dynObj = obj as dynamic;
I see it purely as syntactic sugar, shortcut for obj.dynamic.method
It would NOT create another local variable but all calls
dynObj.AMethod() would be translated at compile time to obj.dynamic.AMethod()
that's just my $0.02
As a follow up to my previous comment.
Adding duck typing would be also trivial and natural
having a class like
class MyString {int Length{get;}}
and method
int GetLength(string s){return s.Length;}
We might duck-type MyString to string and pass it to GetLength method like this:
int length = GetLength(new MyString().dynamic);
Microsoft: "C# is strongly typed ... Just kidding!"
I choose to program in C# because I prefer statically typed languages to dynamic ones, so I'm really unsure about this new feature.
If it was to be included in C# 4.0, I'd add my vote for the object."method"() syntax. I think that the double-dot operator could easily be confused with a single dot and dynamic blocks are a bit overkill. The object."method"() syntax makes it obvious that, like someone said, the method name is only a string (and will as such be resolved dynamically, unless it can be resolved statically). Operators might be accessed using a syntax such as object."+"(param1, param2) and generics like object."method"<Type>(param1).
Although this is, as I see it, the best syntax for this feature, I'm still unsure about if it should be added as I fear it will be abused.
Please do not implement this in C#. You have already alienated me enough with LINQ and anonymous types. (I like LINQ to SQL, I just don't like the C# query syntax because I don't believe it belongs in a language like C#.)
There are reasons I switched from VB/VBA/VBScript/JavaScript to C# many years ago and this is one of them. I don't want a language that promotes loose typing and laziness. If you really wanted to fix the problem with Office Interop, you'd make real managed classes instead of relying on tlbimp-generated code as a base. It can't be that hard cause I have already done it for Outlook and I'm just one guy.
Contrary to what many of the above commentors feel, late binding is trivial today in C# -via reflection -, and its use is inevitable in some real-world cases (people using PropertyGrid and TypeConverters frequently, can acknowledge the necessity of PropertyDescriptors etc.). I feel that an operator is in order here, rather than the block solution. As a matter of fact, although initially the thought of -> and .. operators came to my mind as I read the article, I feel that they are inadequate in the way they are proposed.
Dynamic Lookup should NOT turn our favourite language into a hell of loosely typed constructs or a transgender language, the kinds of "I used to be the most syntactically coherent language ever devised, but now I'll do anything for a few lines of code less". It should respect everyone's wish for maintaining strong typing and allowing for a robust, intuitive syntax.
IMHO, implementing an operator-based transliteration of the existing reflection tools would sufficiently cover the subject of late binding. For example, instead of
TargetType myPropValue = (TargetType)obj.GetType().GetProperty("MyProp").GetValue(obj, null);
TargetType myPropValue2 = (TargetType)obj.GetType().GetProperty("MyProp2").GetValue(obj, new object[] { 1 });
(which is the way we're used to do late binding in C# 2.0), thanks to Extension methods we can have something more coherent, like
TargetType myPropValue = obj.GetPropertyValue<TargetType>("MyProp");
TargetType myPropValue2 = obj.GetPropertyValue<TargetType>("MyProp2", 1);
Obviously, obj can implement any type, and there is no specific declaration needed for retrieving dynamic properties. I personally use this a lot:
public static class DynamicPropertyExtensions
public static T GetPropertyValue<T>(this object instance, string propertyName, params object[] index)
return (T)instance.GetType().GetProperty(propertyName).GetValue(instance, index);
public static void SetPropertyValue<T>(this object instance, string propertyName, T newValue,
params object[] index)
instance.GetType().GetProperty(propertyName).SetValue(instance, newValue, indexer);
I like this solution. It's plain old good C#. It'll throw exceptions if something goes wrong (we could always have a GetPropertyValueOrDefault method as well). What I would see as an improvement to the above, would be some syntactic beautification:
TargetType myPropValue = obj.<TargetType>("MyProp");
or
TargetType myPropValue = obj..MyProp<TargetType>;
and
obj.<TargetType>("MyProp") = myPropValue;
obj..MyProp<TargetType> = myPropValue;
The first solution allows the use of a variable instead of a property name, something that many people will certainly request sooner or later:
string myPropName = "MyProp";
TargetType myPropValue = obj.<TargetType>(myPropName);
Obviously, the generic parameter can be inferred from use in some cases.
Lexapro 20mg. Lexapro. Lexapro and side effects.
That's great,I am glad to heard that.
I am sure the next version of Visual Studio will be perfect.
Just to add another idea: couldn't this perhaps be done partly at the library level instead of adding another keyword to the language, something along the lines of Nullable<T>?
I mean something like:
Dynamic d = new Dynamic(GetDynamicObject());
d.SomeMethod();
where the compiler translates d.SomeMethod() to something like d.Call("SomeMethod").
I’ve not watched many Channel 9 videos over the last few months, but every now and then some really good
The syntax outlined can become very clunky and dangerous because usually such block of code will contain mix of late binding as well as early binding (assuming not all programmers are perfect). I would suggest you invent a different calling notation other than "." to make dynamic call. For example, may be we can define ".." as replacement for "." for dynamic calls. So whenever ".." follows identifier it would specify that next operator/method should be invoked dynamically.
myDynamicObject..SomeMethod();
myDynamicObject..someString = "value";
myDynamicObject..[0] = 25;
I don't normally make these kinds of posts but I'm taken aback by this.
We had this feature for years in VB. We called it Option Strict Off. We could set it at the Project level, the File level, and through use of partial classes even at the method level. And for years we caught nothing but grief from the development community over it.
And now that you want to "shoehorn" it into C# it's a "cool new feature" that all the jocks and cheerleaders use while drinking Pepsi. I don't get it. This reversal of prejudices lobbed at VB for generations all because it's applied to the trendy languages confuses and insults me. This was a horrible, not-best-practice, bad-coding-practice feature 10 years ago and the C# community should have to live with and accept this as a vile black mark on its perfect language for all time like I've had to (no matter how useful it is). You can't make this "good" now that you want it.
First Edit & Continue and now this. Can't the C# universe stick to its elitism and stop ripping off VB.NET? Nevermind that it encroaches on the VB market niche. The end result of this language bloat will be the same fate that befell VB and C++ before it:
A monstrous all inclusive language anchored to legacy code with a subcontinent of diverse development groups that make it impossible to identify a target audience.
One of the common feature requests for IronPython is to support static compilation. While the feature
i agree with the people promoting the
dynamic object foo
approach infavor of a block..
a block seems clunky to me..
however i dont agree that there should be some special operator to call dynamic methods. the ide knows the type of the untyped object so to speak so it can highlight the member calls as dynamic..
i also agree withthe people saying that this should be implemented with extreme care..c# is at its core a static language and there are many many many great things with that.. please dont loose those advantages just to please the dynamic crowd..
that said, expanding the language is great! just dont loose the great things that are already in there.. :)
I want to cast my vote for the ! calling syntax instead of blocks:
myObject!Method();
myObject!"Method"();
myObject!Property = 0;
myObject!"Property" = 0;
It fits nicely with anyone who used vb6 back in the day!
At the risk of sounding like a dork this is kind similar to Powerbuilder( at least from what I remeber of it). Guess the language was ahead of it's time.
I agree with the comments made by Thomas Krause, Daniel Earwicker, and Simon Watfa: dynamic object MyOfficeObject (for syntax, instead of the dynamic code block), I dislike the idea of a separate member-access operator (C++ is a mess of operators), and that C# should only be a consumer of dynamic objects (and remain static).
Charlie, you said declaring a whole object as dynamic is too broad. What you mean by that? What specific scenarios have you come up with that demonstrate this problem? If you always first try to do static lookups, and only perform dynamic lookups when that fails (and only on variables marked as dynamic), what problem remains?
C# should remain static, but by using extension methods, it can take on the appearance of being somewhat dynamic, in the sense that we're "adding" members to types, at least for code that references the appropriate library and imports the right namespace. It's not flexible to the point of being able to add and remove members at runtime, but I can't think of a situation that more would ever provide significantly more value (which isn't to say there is none). My only request here is that C# incorporate general type extensions instead of limiting them to extension methods.
Some kind of duck typing or structural typing would be very useful, and wouldn't require dynamic typing in the language, but as others have stated, this doesn't address the needs of accessing types whose members change during runtime.
While I don't want to be able to modify classes during runtime by adding or removing members, it would be VERY useful (for aspect oriented programming) to allow dynamic dispatch for pervasive method interception. Keep the interface of a class the same, but allow calls to be rerouted to different bits of logic. .NET has a TypeForwardedTo attribute, but this would be a more powerful, fine-grained (member-level) approach. Perhaps extending the language, or providing new reflection-like classes for intercepting individual members (properties and methods), all members of a type, etc.
It should definitly try to resolve statically first, because we want to have code completion available inside dynamic blocks when it is available and just have nothing when its not... :)
I would like to see generics inheritence compabitility... eg....
class Fruit
class Apple : Fruit
class Orange : Fruit
// THis wont compile because we cant
// define a base class for the
// generic type, but i want it to work
class FruitPackage<Fruit fruitType>
Now we should be able to create:
FruitPackage<Apple> oApple = new FruitPacakge<Apple>();
and
FruitPackage<Orange> oOrange = new FruitPacakge<Orange>();
Then i want to be able to go
FruitPacakge<Fruit> oFruit = oApple;
FruitPacakge<Fruit> oFruit = oOrange;
We should be able to define a base type for generics, this could make generics much more useful... it would be good if this worked in VB.NET as well as C#.
Previous comment:
class FruitPackage<Fruit fruitType>
Should probably be more like:
class FruitPackage<typeof(Fruit) fruitType>
Back to the issue at hand, i like the dynamic block idea, it makes it clear where the dynamic calling can occurr, which means its easy to spot, and easy to perform QA on to ensure its not being overused. The only problem i see is allowing a mix of dynamic and static calls, as far as im concerned if any calls can be statically linked and are in a dynamic block the compiler should fail.
Sure this might mean a little more work because you may have to have more dynamic blocks than you would previous need, but this will stop overuse and keep C# to a static language as we all like it....
how about adding dynamic interfaces to the language? Interfaces are perfect for static typesafe dynamic coding and fit into the tool feature set quite well too. What do i mean?
Given an object _obj_ that may or may not be dynamic, anonymous, concrete whatever. I can declare a variable _x_ such that x exposes a public method/property/field through a dynamic interface. for instance var x:{void Walk();}. With this type of feature, one can cast anything to anything as long as theor interfaces <dynamic or otherwise> match.
At assignment time (ie- _x_ = _obj_ ;) the runtime or vs.net can check to ensure that _obj_ exposes the interface as well. Its seems like an easy way to give us a TON of functionality; including finally able to interact with anonymous types outside of a method without having to have a known type to copy it into.
A post by Jeremy Miller caught my eye this morning in regards to extension methods in Javascript . While
How about using # for dynamic member access?
Foo#Bar()
It stands out a lot more than .. or ! in my opinion.
Would be interesting if I could do something like that:
dynamic
object dynamicObject = GetDynamicObject();
string method = "Foo"; /* or a call to somewhere in order to initialize this string */
dynamicObject.method(); /* in this case, it means 'dynamicObject.Foo();' */
The goal of DLR is to ease the way we use reflection in C#. Since this construct can't compile in normal C# (object.stringIdentifier() ?), a dynamic block allowing this would improve reflection usability.
I know that according to the definition I saw on this post this should call a method named 'method'. But when there is an identifier on the block with this name, could be more interesting to the developer to use this information. This identifier could refer basically to a string, but pottentially to other objects with more method info.
And about the syntax, I think '..' is the best option, allowing of course the dynamic block also.
PDC 2008 arrives today, and that means that I am finally able to talk publicly about some of the things
Muitas novidades aconteceram e vem acontecendo no mundo de tecnologia e desenvolvimento. Principalmente
C# 4.0 Dynamic Lookup I really like the way the C# team tackled bring dynamic programming to the language
I don't care what the syntax is AS LONG AS I CAN MAKE IT AN ERROR TO USE IT in the project settings.
Ideally it would like unsafe where you have to go turn it on.
The top 2 horrible things about VB.NET are:
1) The background compiler
2) Late-binding
For the love god, please do not trash C#.
Many .NET users have no doubt run into issues using math functions with generics. Let's say you want
IronPython in action, embedding dell'IronPython engine
Lors des techdays 2009, je suis allé voir la session “ Programmation dynamique ” de Mitsu Furuta et Simon
An attentive reader pointed me at this long thread on a third-party forum where some people are musing
ヒマだょ…誰かかまってぉ…会って遊んだりできる人募集!とりあえずメール下さい☆ uau-love@docomo.ne.jp… | http://blogs.msdn.com/charlie/archive/2008/01/25/future-focus.aspx | crawl-002 | refinedweb | 19,049 | 62.48 |
Data Visualization is an accessible way to represent the patterns, outliers, anomalies, etc. that are available in data by plotting graphs and charts. Data Visualization is a powerful tool because as soon as the human eyes see a chart or plot they try to find out a pattern in it because we get attracted to colours and patterns. Python provides different visualization libraries but Seaborn is the most commonly used library for statistical data visualization.
It can be used to build almost each and every statistical chart. It is built on matplotlib which is also a visualization library. Seaborn provides highly attractive and informative charts/plots. It is easy to use and is blazingly fast. Seaborn is a dataset oriented plotting function that can be used on both data frames and arrays. It enhances the visualization power of matplotlib which is only used for basic plotting like a bar graph, line chart, pie chart, etc.
REGISTER FOR OUR UPCOMING ML WORKSHOP
Through this article, we will discuss the following points in detail:
- How to use Seaborn
- Visualizing different statistical charts
- Various plotting functions in Seaborn
- Different parameters for seaborn visualization.
Before using seaborn we need to install it using pip install seaborn.
Visualization Implementations in Seaborn
Here, we will download a dataset named “tips’ from the online repository, or by using Seaborn’s load_dataset() function. This dataset contains different attributes like total_bill, tips, smoker, etc.
Let us start by importing the important libraries and the dataset.
import pandas as pd import seaborn as sns df = sns.load_dataset("tips") df
Plotting different statistical graphs:
1. lmplot
‘lmplot’ is the most basic plot which shows a line along a 2-dimensional plane and is used to see the correlation between two attributes plotted against the x-axis and y-axis. Here we will plot Sales against TV.
Seaborn also allows you to set the height, colour palette, etc. properties for the plot generated.
sns.lmplot(
2. kdeplot
A Kernel Density Estimate plot is used to visualize the Probability density distribution of univariate data. In simple terms, we can use it to know the spread/distribution of the data.
sns.kdeplot(df['tip'])
3. Scatterplot
Scatterplots are similar to lineplot/lmplot, the difference is that it only shows the scattering of the two attributes without trendline. It is also used for finding the relation between two attributes.
sns.scatterplot(
4. Distplot
Distplot is the most convenient way of visualizing the distribution of the dataset and the skewness of the data. It is a combination of kdeplot and histograms.
sns.distplot(df['total_bill'])
5. Barplots
Barplots are the most common type of visualization and mostly used for showing the relationship between numeric and categorical data. Barplots can be plotted both horizontally and vertically as required.
sns.barplot(
6. FacetGrids
FacetGrids are used to draw multiple instances of the same plot on different subsets of the dataset. In this visualization, we take a data frame as an input and the names of variables for rows and columns.
To draw facet grids we need to import matplotlib as well. Let us visualize the dataset using Histogram FacetGrids.
import matplotlib.pyplot as plt a = sns.FacetGrid(df,
7. Box-Plot
We use box-plots to graphically display the data according to its quartiles. With box-plot, we can easily identify the median, any outlier if data has and the range of the data points.
Here we will visualize the tip that is paid on different days of a week.
sns.boxplot(
8. Violin Plots
Violin plots are the combination of the KDE plot and box-plot. It is used to visualize the numerical distribution of the data.
sns.violinplot(
9. Heatmaps
Heatmaps are used to display the correlations of different numerical attributes in a dataset. In heatmaps, colour scheme plays an important role in visualizing whether the relationship is positive or negative.
For creating a heatmap we will create a Correlation matrix and pass it to the heatmap parameter. We will also set the annotation to true so the value of the relationship is also visible.
sns.heatmap(df.corr(), annot=True)
10. Jointplots
Jpintplots are useful when we want to visualize the relationship between two variable as well as their univariate relationship. Jointplots are of many types and we can define the kind we want by passing the value in the “kind” parameter.
sns.jointplot(
These are some of the basic plots which we can visualize using Seaborn, and are helpful in data analysis. Seaborn has the advantage of manipulating the graphs and plots by applying different parameters. Some of the important parameters are:
- set_style: It is used to set the aesthetics style of the plots, mainly affects the properties of the grid and axes.
- hue: It is used for deciding which column of the dataset will be used for colour encoding.
- palette: It is used to select the colour palette which we want to use for our visualization. Seaborn has six pre-defined colour palettes namely: “pastel”, “muted”, “bright”, “deep”, “colorblind” and “dark”.
- height: It sets the height of the visualization figure.
Other than these properties all the graphs have some of their internal properties which can be altered accordingly.
Conclusion
In this article, we saw how we can create highly informative and visually appealing charts and graphs using seaborn and what are the uses of this visualization. We explored that seaborn is really easy to use as all of our graphs are created in just a single line of code and is blazingly fast as graphs are plotted within seconds.. | https://analyticsindiamag.com/a-beginners-guide-to-seaborn-pythons-visualization-library/ | CC-MAIN-2021-31 | refinedweb | 926 | 55.34 |
Red Hat Bugzilla – Bug 693608
Review Request: icinga - Open Source host, service and network monitoring program
Last modified: 2014-01-20 01:33:12 EST
Spec URL:
SRPM URL:
SOURCE URL:
Description: Icinga - System Monitoring Application
First packaged created/released. Thank you for any assistance.
rpmlint is throwing 72 errors and 2646 warnings on your files - please clean that up before review. Most of these are due to file being owned by nagios (most should be owned by root:root). Use the -i option to get verbose information about any errors which seem unclear. Also, I noticed that your package is trying to own /etc/httpd/conf.d which is owned by httpd.
Sorry about that, here are some updated versions of the files.
Spec URL:
SRPM URL:
SOURCE URL:
Please note that while rpmlint throws a "subsys-not-used" error, it is actually being used and rpmlint is simply not detecting it.
Hi Mike, thanks for putting this together. Here are some initial comments to get you into shape for a formal review:
1. Latest upstream seems to be 1.3.1. Please update your package from 1.3.0 to the latest upstream version.
2. The proper license is GPLv2. Please update the License field.
3. Please remove gcc, glibc, glibc-common from BuildRequires. These packages are installed in every buildroot in mock.
4. net-snmp-devel will pull in net-snmp, so no need to BuildRequires both. Please remove BuildRequires: net-snmp.
5. When you copy in README.Fedora, please try to preserve the timestamp.
6. This portion makes me think that you should probably not use the "nagios" username at all:
# For when the user already exists
/usr/sbin/usermod -c "nagios" -s /sbin/nologin -r -d /var/icinga -G icinga-cmd -g nagios nagios 2> /dev/null || :
In this case, you're reaching in and modifying another package's username. It would be better to just use an "icinga" username. Your spec contains a few comments that indicate you're trying to preserve compatibility with nagios-plugins, but nagios-plugins ought to work ok without requiring a "nagios" username on the system. Please elaborate in this ticket if you think that you need to use the "nagios" username.
7. Please use %{_sbindir}/usermod instead of /usr/sbin/usermod .
8. /var/icinga should probably not be used. Nagios uses /var/spool/nagios, so can you use /var/spool/icinga ?
9. --with-lockfile="%{_localstatedir}/icinga/icinga.pid" should be %{_localstatedir}/run/%{name}.pid like nagios. If it really needs its own sub-folder, %{_localstatedir}/run/%{name}/%{name}.pid.
10. Can you please clean up some of the "non standard perm" rpmlint errors, eg. /usr/bin/icingastats 0774L
11. Please do not start the services by default:
icinga.i686: W: service-default-enabled /etc/rc.d/init.d/icinga
icinga-idoutils.i686: W: service-default-enabled /etc/rc.d/init.d/ido2db
Use "-" as the default runlevel in the icinga init script's "chkconfig:" line, and remove the "Default-Start:" LSB keyword in the ido2db init script.
> you're reaching in and modifying another package's username.
Already using the same special user/group as another package isn't entirely nice and also isn't best practice security-wise (even if apparently it just tries to access nagios-plugins).
> %attr(2755,nagios,icinga-cmd) %{_localstatedir}/icinga/rw/
Along the same lines, the following is also going too far:
> Provides: nagios
"nagios" is not a package capability, but the name of an existing package in the collection. Even if "icinga" has started as a fork of nagios, it must not disturb the package namespace of nagios and must not claim that it provides "nagios".
> %package gui
> ...
> Requires: %{name}-doc
Caution! A strict dependency on a documentation package asks for a rationale in the spec file just like other explicit dependencies:
Note that %doc files may be absent with --excludedocs installs, so either the documentation really is required by the -gui pkg at run-time, or it may be optional. What is it?
Looking at the %files tree, currently the -gui package provides a directory that is needed by the -doc package. Same for the -api package.
> %package doc
> Summary: documentation %{name}
> Group: Applications/System
Cut'n'paste error. Not the appropriate group.
> %prep
> %setup -qn %{name}-%{version}
"-n %{name}-%{version}" is the default.
> %config(noreplace) %{_sysconfdir}/icinga/objects/commands.cfg
> %{_libdir}/icinga/cgi
There could be more unowned directories.
Found this bug while discussing the future use of icinga instead of nagios for monitoring and just wanted to add a comment on idoutils..
Also I hope it could provided for epel!
Mike, if you incorporate the changes in the last three comments and post your updated files, I'll do a formal review.
>:
allow me to correct that as I am the developer who added the --enable-pgsql flag in order to use libpq instead of libdbi's abstraction layer for postgresql.
current implementation of idoutils focuses on 2 dependencies, which are used productively and are fully implemented:
* --enable-idoutils
needs libdbi, whereas you can load either libdbd-mysql or libdbd-pgsql as a rdbms driver being detected as approriate.
so this flag as is will provide *either* mysql *or* pgsql - no further configure option needed during build
* --enable-idoutils --enable-oracle
requires ocilib as oracle rdbms abstraction layer. as there are no builds available, i have created a spec file myself in order to ship that in our environment.
but due to the dependency on commercial, not fully licensed rpms (oracle instantclient) this can't be built into by default. so this was made an exclusive configure option for those demanding a seperated build (gcc will create another binary, ido2db.cfg will need an adapted config whilst depending on tnsnames.ora and such.
>
>.
that sounds good to me, but keep in mind that rpmforge spec file (which is the default we provide within the official Icinga tar.gz) already built
- icinga-idoutils (for libdbi usage with mysql and pgsql)
- icinga-idoutils-oracle is never found anywhere, but can be contributed somewhere for those needing it (e.g. Icinga Wiki)
Even though, to conclude with the original discussion - my packaging skills are work-in-progress, especially on rpmlint/selinux. So if you have any suggestions especially for RHEL/Fedora on the spec file which could fit to upstream (side-by-side for SuSE), then feel free to get in touch.
Either open a new issue on the dev tracker, get aboard the mailinglists or join the IRC community -
Kind regards,
Michael
Created attachment 505534 [details]
Spec-file icinga permissions unchanged
Created attachment 505535 [details]
Spec-file icinga permissions changed
I have created two Spec-files. The first one I have left the permissions unchanged so icinga can read and write its configs, but I don't see why this should be needed so I have created the second one..
(In reply to comment #10)
> I have created two Spec-files. The first one I have left the permissions
> unchanged so icinga can read and write its configs, but I don't see why this
> should be needed so I have created the second one.
Thanks, I'll have a look what I can merge into the upstream available icinga.spec file.
2 more topic to discuss ...
1) the so called "icinga api" is mainly a php based abstraction layer on the idoutils rdbms. shouldn't this be renamed into "icinga-phpapi" in their respective package name (if you consider adding this from scratch)? i can't change that in the official spec file but e.g. debian maintainers did due to the nature of its behaviour.
2) the newly introduced "module definition" in 1.4.0 - can now be used to load neb modules without enabling them in icinga.cfg explicitely.
1.4.x still contains the modules/idoutils.cfg which contains commented sample configs. this is known bug (make install overrides existing source installs) - - and it will be replaced by modules/idoutils.cfg-sample allowing the same procedure as you know about idomod/ido2db.cfg;a=commit;h=6e9e78f686c0aa0de436e66b840984a6a122ab66;a=commit;h=65a76c55df7052884354de4884684e8fc0803981
(all recent changes can be found in this git branch until they hit the release branches;a=shortlog;h=refs/heads/test/core
whilst cgis and ido do have their own)
>.
p1.pl is only used if embedded perl is enabled (by configure/compile) and if enabled explicitely in icinga.cfg. this is intentionally disabled in future releases as the embedded perl interpreter could cause memory leaks which haven't been fixed / cannot be fixed for some years now. don't ask me about the details, i'm no expert at this stage of coding.
even more, nearly each know distribution moans about the location of p1.pl in $bindir so the recent git commit introduces default $libdir and a new configure option to be named '--with-p1-file-dir' and is targetted to be used by packagers who don't like to do the normal mv and sed stuff.;a=commit;h=08b0437c5648bfe014e096c14be73b784e2d4f02
so expect older packages to be having an old p1.pl floating around, but that's something to be mentioned seperately in the changelogs.
due to these changes, the icinga-spec provided with the official releases will change too.
and some more changes, because the target of p1.pl in (new_)mini_epn.c in contrib/ (which can be used to manually execute and test perl plugins) have a lot of hardcoded stuff which is now to be replaced to be more packager friendly.
the intended location for an official distribution package is $libdir/icinga/p1.pl which is enabled in configure and the filelist itsself.;a=commit;h=15d9ce78b907811b2048a8fb99983d08be2de6e8
though i'm not sure if introducing such changes would make sense in 1.4.2 as it will remain a bugfix release.
> >.
probably a change which can only be done with a fresh package start. existing rpmbuilds will suffer from revoking icinga-idoutils, but that's fine if it will be kept as an alternative over here.
>.
i'm doing internal packaging stuff (still learning!), but my daily job is partly icinga core development, so i'd be very happy to see an official maintainer. also possible as part of team icinga as we are trying to keep communication channels easy and changes - if they fit - mostly upstream.
If the p1.pl relocation patch:;a=commitdiff;h=08b0437c5648bfe014e096c14be73b784e2d4f02;hp=d362c03fd78789dfb7e1a24164cf656ab5dd6ce1
applies cleanly to 1.4.2, then I'd advocate carrying the patch for moving p1.pl in the Fedora spec to avoid trying to move it in the next release (and putting it in a silly place to start with).
Thanks for all of your work, guys.
currently it won't apply cleanly against 1.4.x release target, as this was intentionally built against latest dev branches for 1.5 to be released in August.
the reason i'm asking in advance is that this will introduce a change several packagers have been asking for, but i am not very keen on doing this within a bug fix release as it is still a rather major change (although it would just affect those actually using embedded perl, and that's mostly within packages, not within the quickstart guides).
so the question remains, where to put that logically. the idoutils.cfg-sample fix is now included for 1.4.2 upstream release which is planned next week or similar.;a=shortlog;h=refs/heads/r1.4
i've taken the liberty to move some proposed patches on icinga.spec for upcoming 1.4.2 release.
there's a small bug in the spec file over here on the logging directory for the cgis.
initially, %{logdir}/gui is created, but the cgi.cfg reflects that as %{logdir}/cgis
this only is in effect, if you enable gui logging, but should be changed if this spec is taken upstream.
%{__perl} -pi -e '
- s|cgi_log_file.*|cgi_log_file=%{logdir}/cgi/icinga-cgi.log|;
+ s|cgi_log_file.*|cgi_log_file=%{logdir}/gui/icinga-cgi.log|;
s|cgi_log_archive_path=.*|cgi_log_archive_path=%{logdir}/archives|;
' %{buildroot}%{_sysconfdir}/icinga/cgi.cfg
for 1.5 i am planning to add a configure option for that.
Is there a revised package to test?
you could get the 1.5.0-beta where most of the things for wednesday's 1.5.0 are already included. the icinga.spec does not contain everything mentioned in this topic but some suggestions have been taken over. so creating a fully compliant spec file will need an updated version from the one Dirk Götz provided.
just a thought on the libdbi dependencies and creation of different idoutils packages - it does not matter if you install icinga-idoutils-mysql or icinga-idoutils-pgsql then, because it matters which driver is being used via config directive and not explizit package dependency. so by just naming the package "icinga-idoutils" you can reserve the name logic for some different implementations (e.g. icinga-idoutils-pgsql for a compile based on libpq, if it might come).
icinga-api is not a dependency for icinga-web anymore, so there's actually no deep need to create rpms out of that too.
all recent changes have been documented into changelog as well as developer wiki
still, if someone's willing to update the existing spec file provided with icinga tarball (and used for rpmforge), i'd be happy help wherever i can.
My thought was not only having the correct libdbi-driver installed, I also wanted to reduce the installed files. Can the idoutils be compiled with support for both libdbi and pgsql-specific support? Perhaps the naming should then be icinga-idoutils-libdbi-pgsql for installing libdbi with pgsql-driver and icinga-idoutils-pgsql for pgsql-specific? Or will this get too complicated?
I did not find any time to update the spec-files, but I have convinced my supervisor to pay the guys from netways to build the packages for us, just need to get the budget from finance to start the project. So I am looking forward to get spec-files for all parts of icinga and eventdb which can pass the review process. Next thing to do after having packages build will be convincing my supervisor to sign a support contract so netways guys are payed for updating or allow me to do so.
actually the point in naming it genericly "icinga-idoutils" is to use the libdbi version, and allow the user to decide
* which driver is being used
* which driver is loaded
one could install all possible libdbd-* drivers, and just select that by changing ido2db.cfg entry. i would not recommend to make the driver for libdbi an actual dependency of icinga idoutils. it should be made a user decision only.
regarding the libdbi and libpq compiles - it wouldn't make sense to add that doubled dependency to a package. either use libdbi (which is stable implemented) or use libpq (which is not yet implemented, experimental).
so i do think it's fine to support binary builds for each rdbms layer. if the would be oracle available, one could also build idoutils with ocilib dependency.
I do not see the problem with the user decision.
If the user has to decide between icinga-idoutils-mysql and icinga-idoutils-pgsql (or installing both if he for some unknown reasons likes) and this package installs the idoutils with libdbi-support and the corresponding libdbi-driver, the user has the possiblity to decide and does not need to know which further packages to install. Also the user benefit is less (unnecessary) files on the system.
If the user has one generic icinga-idoutils with all files, he installs the package and also needs to know that he has to install the needed libdbi-driver and to decide which one he actually needs. I think the first one is more user-friendly.
I just asked the question if compiling with support for both is possible, because I do not know how to handle multiple make && make install with different parameters for one source in one rpmbuild. If it is possible, I am just not experienced enough to know how! If not, we perhaps need to make one decision for the packages on a technical limitation or need multiple specfiles.
Is anyone still actually trying to push this through as the packager? If not, I'll try to take a look at what's needed to get them into shape and reviewed.
not as a packager - i'd love to see someone (you? :) )actually catching up with this (as i said already on twitter - @dnsmichi).
for what it's worth, i've got a ping by someone revamping the spec file a bit - from here and from upstream, so maybe we can merge that discussion.
should i put you on cc and summarize offlist? current discussion is being done in german only.
thing is, for the discussion above my final proposal to name the idoutils package like this:
* icinga-idoutils-libdbi-mysql or -pgsql for the libdbi db layer
=> needs ./configure --enable-idoutils
* icinga-idoutils-oracle (will never happen as it requires oracle rpms)
=> needs ./configure --enable-idoutils --enable-oracle
* icinga-idoutils-pgsql (will happen in 2012 based on libpq)
=> needs ./configure --enable-idoutils --enable-pgsql
libdbi does not scale well. it's not threadsafe, does not support parameter bindings, and can get deprecated if it gets worse.
ok, some updates. in current git branch "dev/core" are some mostly breaking changes, which should make packing even more easier.
this will hit the 1.7 release then, so if we could work out a mostly package upstream <=> source upstream spec file until then, it would be great.
* add --with-plugin-dir to configure for setting the plugins path accordingly
* add configure option --with-temp-file=<filepath> to set temp_file for icinga.cfg
furthermore, the most significant break will be moving the icinga idoutils idomod.o neb module from $bindir to $libdir by default. this has been suggested by $every packager but i feared to introduce such a breaking change.
* change default target location of idomod.o from $bindir to $libdir
and last but not least, the package install of icinga-idoutils should install the "idoutils.cfg" containing a module definition by default (/etc/icinga/modules)
this will allow installs without modifying the icinga.cfg for automatically loading the event broker module. just like apache handles config integration, but hereby based on a new object definition.
and just for once - the "provides: nagios" is required in regard of other packagers requiring nagios implicitely - if there aren't any, feel free to drop it.
anyhow. if there are other suggestions or needs for making the package building cleaner, either contact me directly at michael.friedrich(at)univie.ac.at or open a new issue on in the core section.
i've now cleaned the spec file by comments over here, by the nagios.spec on epel, and other input i found necessary to compete with the issues.
it's now called
icinga-idoutils-libdbi-mysql
icinga-idoutils-libdbi-pgsql
and got the proper requires and conflicts.
furthermore, htpasswd is automated like the nagios.spec as well as a logrotate example is added to upstream.
plus it's not /var/icinga anymore, but /var/spool/icinga so a rather huge change for now.;a=shortlog;h=refs/heads/r1.7
this is currently on git r1.7, so in order to get a testable build, do the following.
$ git clone git://git.icinga.org/icinga-core.git
$ cd icinga-core
$ ./configure ; make create-tarball
$ cp ../icinga-1.7.0.tar.gz* <yoursourcesdir>
$ cp icinga.spec <yourspecdir>
a pre 1.7.0 changelog can be found here
rpmlint only moans about the "provides: nagios" which would possibly be a discussion point.
please keep in mind that this is still in development, so if you happen to have proposals or fixes, we can do it.
Created attachment 579454 [details]
current pre 1.7 icinga spec file
Created attachment 584757 [details]
final icinga 1.7 spec file epel prepared
this is the final version. it contains all valuable patches, plus a clean upgrade path for those having built previous versions on their systems. the full changelog can be seen inside the spec - upstream 1.7.0 tarball was released a few hours ago.
so i'd appreciate it if someone could review the spec file and tell what else is needed to bring icinga into EPEL.
thanks,
michael
Just one question about the changes for 1.7 - does this make Icinga work with SELinux, or are some rules still required?
I don't like the need to disable (or set to permissive) SELinux to run this, but the changes appear to better fit what SELinux expects with file locations and such.
mh tbh i have forgotten that issue. all my systems don't use selinux, and i am not really an expert regarding this.
so if anyone applicable to help out adding rules (maybe copy them from nagios rpm?) i would really appreciate that.
The practical extent of my SELinux knowledge is attending a nice talk Dan Walsh gave about 5 years ago ... that said, has anybody here tried running the 2012-05-15 version and has the selinux errors handy?
I ask because what I see in the nagios SPEC is a 1-liner to run restorecon on the nagios .pid file. I'm wondering if icinga's needs are more complex.
If nobody has this, I'll install a VM and give it a whirl. I've been maintaining my own nagios SPEC with a local patch anyway (one that icinga picked up a couple years ago) so I'd just as well be done with that. :)
Hej Michael,
I fooled around with your spec file and think that, for using the nagios-plugins (especially nagios-plugins-icmp), it would make sense to add the user icinga to the group "nagios".
Cheers,
Roland
@Bill
Chris prepared some selinux parts within selinux/ (which are rather old, as only el5 covered). if you have any other special findings, please keep us updated here, and if possible, at that issue as well:
@Roland
true that. that should mainly be the reason why Debian packages still use the nagios user. but imho, icinga should use it's own. either way, as this is important, marked as upstream issue here
i will provide an updated spec file later on. the -devel packages was introduced as well on git ()
Out of all of the nagios-plugins-\* packages, only 4 utilities have a mode other than 0755:
-rwsr-x--- 1 root nagios 50640 Jul 1 15:26 check_dhcp
-rwsr-x--- 1 root nagios 49008 Jul 1 15:26 check_fping
-rwsr-x--- 1 root nagios 56584 Jul 1 15:26 check_icmp
-rwsr-x--- 1 root nagios 40400 Jul 1 15:26 check_ide_smart
I think it would be reasonable for the icinga RPM to add the icinga user to the nagios group. However, since it's just a few sgid files I also think it would be completely reasonable for the user to have to manually add icinga to the nagios group. That action would only need to be done on the server running icinga as nrpe clients will already being in the nagios group.
(In reply to comment #33)
>
Feel free to open a bug against the nagios-plugins package.
/jpo
I see that there is now a package owner for Icinga 2.x (which is not yet released). However, that release is still a ways off.
What is blocking the icinga 1.x srpms from being included into EPEL? Are there any technical objects or does a packager just need to step up? If the later is the case, I will volunteer to become a packager if I can find a mentor.
(In reply to Joshua Hoblitt from comment #35)
> What is blocking the icinga 1.x srpms from being included into EPEL?
check out the above problems listed, but if you just want a running icinga 1.x, the RPM's from rpmforge seem to work great on el:
The issues I ran into with those are the same as listed above: adding the icinga user to the nagios group so pings work (essential for most icinga installs, I'd imagine) and figuring out that I needed idoutils (coming over from nagios) and which idoutils packages I'd need (postgresql on my machines). For users running selinux, a more comprehensive policy seems to be needed to meet EPEL muster.
My input is that adding the icinga user to the nagios group should not be a user task, because icinga is re-using nagios-plugins* and the group membership is needed for compatibility with the nagios-plugins packages. Re-bundling nagios-plugins makes less sense, and icinga should work out-of-the-box.
The idoutils dependency should be handled with the documentation. I use a puppet script, but Fedora* still handles these manually.
As I understand it, the selinux cycle is a matter of running icinga through its capabilities, finding denials, and running the selinux tools to map those to policies. Is there a test suite that will exercise the majority of icinga to force these issues out?
Testing the policy provided in and adding feedback there would be helpfull. If it does not work for you, please describe your usecase and the avc from /var/log/audit/audit.log.
You can additional comment in the permissive lines in the te-file. This will run icinga and/or ido permissive while keeping the system in enforcing mode. This will create more avcs, but perhaps not all privileges are necessary.
For idoutils: The backend is not needed for running the core, but for the most addons. And the database to use is user’s choice. So dependency from ido packages to core package is good if the user knows he has to choose one of those and gets installed all needed. ;-)
For user: Adding icinga to the nagios group would be nice but I do not think packaging guidelines allow it.
Summary from my point of view, having so many different people asking and offering help:
- Rene Koch asked on icinga-devel mailinglists [0], and we had a short chat on osdc. We had the conclusion that we need a sponsor and selinux policies for the package [no further updates]
- On 27.4.2013 Christopher Meng wrote me a mail asking about Icinga2. While I think this is a really good idea, I've asked about bringing 1.x also into Fedora. He told me to ask the original bug creator here. [no further updates]
- Dirk Goetz already added some SELinux Policies to the bug on the Icinga Dev Tracker [1]. I've added these files into upstream's git already, so they ship with the Icinga tarball itsself - and eveverything else can and will be, if a sponsor/packager is found.
- A User named "Corey" (with the cloak "staff/freenode") joined last week on #icinga at freenode irc, where a missing SELinux policy prevented him from installing the package "icinga-cgi" (because it adds the apache user to the icinga-cmd group, which selinux prohibits). Maybe he will/can provide an updated policy then.
- Some others offered help too ("palli" on irc, etc).
- Packages on repoforge are not automated, but manually. The spec files on git are 1:1 the same as shipped with the Icinga tarball and mostly updated within the release week. But the package build itsself takes a rather long time. Users are not really satisfied by that. Of course, there's an icinga repo on the (long) todo list, but having Icinga on the official Fedora/EPEL repositories would be much appreciated - as many distributions already have it [2] (and icinga-web even).
Conclusion to that:
- A package sponsor is needed. I don't know who to ping/grab/convince/sendbeer/etc but I would appreciate it if we find someone willing to help us out here.
- A packager & coordinator is needed. While I think that my package skills evolved over time, I would really appreciate it if someone else (Dirk? Joshua?) could take the hat. My development ressources are flattering between 1.x and 2.x right now.
- If there are changes required for the Icinga source (e.g. adding something to make packaging easy), just create a patch and/or issue on the icinga dev tracker and i will make sure that it gets into the next upstream tarball release.
- regarding the icinga user to nagios group for plugin execution: please provide a README.RHEL patch for that with manual instructions for the user.
thanks,
Michael
[0]
[1]
[2]
Hi,
Status Update
- David Ressman is now working on the selinux and systemd patches.
- systemd support is already in git 'next' -;a=tree;h=refs/heads/next;hb=refs/heads/next (requires tests)
- selinux is pending - icinga assigned issue:
- possible package reviewer/sponsor, chatted now with Shawn Starr
- the nagios plugins issue with the icinga user being in the nagios group - to be discussed
kind regards,
Michael
Forgot that Wiki entry:
- should be updated for 1.x too
Hello,
I can help you with getting Icinga into Fedora. If the SELinux issues are sorted then it's a matter of now just making sure the package .spec file passes rpmlint, builds in mock and rpmlint shows no serious issues.
There is no reason this should be blocked from being brought into Fedora.
The nagios-plugins issue
For user: Adding icinga to the nagios group would be nice but I do not think packaging guidelines allow it.
I don't know of any policy regarding this from what I can see. It would not make sense to have to repackage nagios-plugins JUST to change the groups in .spec file.
Thanks,
Shawn
I have asked the maintainer for permission to use the nagios group in nagios-plugins. If they say yes, this will unblock that issue.
Peter Lemenkov has said it's fine with him to let icinga use the nagios group as long as we check for it.
As long as we are depending on nagios-plugins the group should be created prior to us being installed, in the unlikely event the nagios group isn't created, we can still create it as nagios does this:
getent group nagios >/dev/null || groupadd -r nagios
getent passwd nagios >/dev/null || useradd -r -g nagios -d %{_localstatedir}/spool/%{name} -s /sbin/nologin nagios
It is not using any UID/GID hard coded or specific numbers just the name, we just use the same name and no conflicts will occur.
rpmdb doesn't store the UID/GID as I just checked only the name. So with everyone using the fixed name there can be no situation where the UID/GID for nagios (previously installed) would be overwritten by a new UID/GID breaking things.
the current selinux files are on git next - yet someone needs to tell if they're ok and/or integrate them (haven't figured out how the nagios package does it).;a=tree;f=selinux;hb=refs/heads/next
imho it would be best to work on pre 1.10 packages having systemd and selinux inside (october will be rushing in anyways when release is scheduled) and commit possible changes back into git next. we may even create pre-release tarballs for that specific reason.
david will update us soon-ish with the latest and greatest changes here.
I'm no SELinux expert to verify if those are right or not. I'll wait til thats sorted then we can begin the package review process.
Then I need the .spec file and will do Fedora specific cleanups accordingly, finally someone else will use the fedora-review tool to do vetting of the spec and package requirements.
You are welcome to run fedora-review also, which can make grabbing your .spec file easy if there's less changes I need to make (if any).
Package has sponsor, me :)
Waiting for an update from Icinga folks please.
Upstream has provided me builds, we will begin the re-review this week. I need to go over their stuff first.
reset owner, reviewer will change this.
Aside from any SELinux issues which we will deal with in this ticket, upstream provides some SELinux policy files.
Here is the latest spec and SRPM, first pass mock pass, rpmlint pretty good (with exceptions)
SPEC:
SRPM:
Of note inside SRPM:
icinga-0001-Apache-2.4-configuration-fix-for-Fedora.patch
icinga-0002-Added-several-images-to-the-sample-config-revb.patch
icinga-0003-fix-tests.patch
There are three patches I've included, two from Nagios (the first one modified, second one left as-is) and the third one to fix building the Icinga test suite. If upstream can take any of the patches this would be great!
As with Nagios there are funny permissions in this package, I'd like to make sure we've got this all covered so we don't have any issues.
Let's begin this kickoff review.
Created attachment 852626 [details]
fix build test suite
Shawn, please submit a new review and mark this one as obsolete because the initial submitter was not you.
will do
*** This bug has been marked as a duplicate of bug 1055378 *** | https://bugzilla.redhat.com/show_bug.cgi?id=693608 | CC-MAIN-2017-30 | refinedweb | 5,566 | 64.1 |
VAT
All prices are VAT free.
Please be aware your country might charge you custom fees,
import taxes or VAT
when importing parts from the UK, please look into this before purchasing any items.
If you want to stay under
the limit, for example EU has a arrangement for duties/fees to be taken by UK sellers for under €150/£125 but this depends on your country's customs applying this arrangement, keep your order per box under it
and split your order up across multiple orders to keep the fees/taxes down.
Check your country's VAT charges and threshold.
We can't take any responsibility for fees/taxes, charged by your country's customs. It's your responsibility to clarify these fees/taxes.How to select shipping location when shopping
- For UK shipping use: UK-Free shipping
- For Europe use: EUR-1st item
- For International shipping use: International-1st Item
- For extra parts use: EUR or International-additional items
UK Post Office sign for delivery:
Arrives within a day or three of posting (UK).
Requires a signature.
UK Post Office, next day special delivery:
On request.
UK Post Office Airsure, signed for:
Can be tracked till it leaves the UK.
Normally 3-5 days for Europe and 14 days for rest of the world.
Courier service (UPS, DPD, Fedex, etc.):
On request. | https://www.carbonfbr.com/faq | CC-MAIN-2021-49 | refinedweb | 224 | 62.38 |
Closed Bug 1341006 Opened 3 years ago Closed 3 years ago
High atoms-mark-bitmaps memory footprint
Categories
(Core :: JavaScript: GC, defect)
Tracking
()
mozilla54
People
(Reporter: bugzilla.mozilla.org, Assigned: bhackett1024)
References
Details
(Keywords: memory-leak, regression, Whiteboard: [MemShrink:P1])
Attachments
(1 file)
Name Firefox Version 54.0a1 Build ID 20170216030210 From the parent process: 5,354.25 MB (100.0%) -- explicit ├──3,943.54 MB (73.65%) -- js-non-window │ ├──2,208.52 MB (41.25%) -- runtime │ │ ├──2,163.13 MB (40.40%) ── atoms-mark-bitmaps │ │ └─────45.39 MB (00.85%) ++ (13 tiny) │ ├──1,710.11 MB (31.94%) ++ zones │ └─────24.92 MB (00.47%) ++ gc-heap ├────481.20 MB (08.99%) ── heap-unclassified ├────477.63 MB (08.92%) ++ window-objects ├────176.39 MB (03.29%) ++ heap-overhead ├─────90.65 MB (01.69%) ++ xpconnect ├─────65.98 MB (01.23%) ++ add-ons ├─────62.26 MB (01.16%) ++ dom └─────56.60 MB (01.06%) ++ (20 tiny)
Can you reproduce this? Does it happen in safe mode? This looks very bad.? > Can you reproduce this? Reproduce would not be a word I'd use yet. The report above was the first time I have spotted it, that session had several days of uptime. With today's session I have a second sample: 4,658.56 MB (100.0%) -- explicit ├──2,468.58 MB (52.99%) -- js-non-window │ ├──1,359.42 MB (29.18%) ++ zones │ ├──1,083.26 MB (23.25%) -- runtime │ │ ├──1,041.63 MB (22.36%) ── atoms-mark-bitmaps │ │ └─────41.63 MB (00.89%) ++ (13 tiny) │ └─────25.91 MB (00.56%) ++ gc-heap ├────794.38 MB (17.05%) ++ window-objects ├────616.28 MB (13.23%) ── heap-unclassified ├────439.66 MB (09.44%) ++ heap-overhead ├─────92.43 MB (01.98%) ++ dom ├─────90.07 MB (01.93%) ++ (20 tiny) ├─────78.73 MB (01.69%) ++ xpconnect └─────78.43 MB (01.68%) ++ add-ons > Does it happen in safe mode? This looks very bad. Haven't tried.
Flags: needinfo?(bugzilla.mozilla.org)
(In reply to The 8472 from comment #2) >? Yes, this was added in bug 1324002. It changed how the memory management of certain kinds of strings (atoms) are handled. The bitmaps are just used to check whether the atoms are alive or not, so I would not expect the memory to go out of control like this. It seems likely there is a leak in them somewhere, given that you don't also have the memory for atoms ballooning up..
(In reply to The 8472 from comment #4) >. How many zones do you have in about:memory? There are several inefficiencies with the current implementation. The scaling isn't so much numZones * numAtoms, but numZones * maxAtomsWhichEverSimultaneouslyExisted, which is even worse. The best way forward here is I think to use a sparse bitmap, so that the amount of memory used by a zone bitmap is linear with the number of atoms it actually references. That should fix the scaling problems, though there will still be other constant-factor inefficiencies. I'll try to write a patch in the next day or two.
> How many zones do you have in about:memory? about 1600. Maybe it would make sense to move about:blanks into a common JS zone, if that's possible?
Summary: Leak of atoms-mark-bitmaps → High atoms-mark-bitmaps memory footprint
This patch uses a sparse representation for the bitmaps stored on zones. The bitmap is divided into page-size blocks, and a hash table is used to keep track of the blocks which a zone has set any bits within. This shouldn't increase memory usage much at all for bitmaps that are filled in densely, and the main time overhead is a hashtable lookup when setting the bit for a particular atom, which shouldn't have much of an impact. I wasn't able to reproduce the circumstances described here of having a bazillion zones; when I open a bunch of about:blank tabs or restore a session with a bunch of tabs there aren't many zones that are active. I did test this with a testcase that produces a lot of atoms, and verified it does keep zone bitmaps much smaller than they would be before this patch.
Assignee: nobody → bhackett1024
Attachment #8840138 - Flags: review?(jcoppeard)
Whiteboard: [MemShrink] → [MemShrink:P1]
Comment on attachment 8840138 [details] [diff] [review] patch Review of attachment 8840138 [details] [diff] [review]: ----------------------------------------------------------------- This looks good, and it's nice to see the bitmap manipulation factored out. The bitwiseOrWith issue below seems concerning, otherwise r=me. ::: js/src/ds/Bitmap.cpp @@ +11,5 @@ > +SparseBitmap::SparseBitmap() > +{ > + AutoEnterOOMUnsafeRegion oomUnsafe; > + if (!data.init()) > + oomUnsafe.crash("Bitmap OOM"); SparseBitmap is initialized as part of the Zone, so we could handle failure here rather than crashing. @@ +124,5 @@ > +{ > + size_t blockWord = blockStartWord(wordStart); > + > + // We only support using a single bit block in this API. > + MOZ_ASSERT(numWords && (blockWord == blockStartWord(wordStart + numWords - 1))); Can you change the method name to indicate this restriction? :::? @@ +72,5 @@ > + // Return the number of words in a BitBlock starting at |blockWord| which > + // are in |other|. > + static size_t wordIntersectCount(size_t blockWord, const DenseBitmap& other) { > + ssize_t count = other.numWords() - blockWord; > + return (count < 0) ? 0 : ((count > (ssize_t)WordsInBlock) ? WordsInBlock : count); This nested ternary operator is a little confusing to read. Can you refactor using at least an if statement for the outer condition?
Attachment #8840138 - Flags: review?(jcoppeard) → review+
(In reply to Jon Coppeard (:jonco) from comment #8) > :::? Oops, yes, you're right. The behavior here is correct, I'll change the name to copyBitsFrom(). This is used by computeBitmapFromChunkMarkBits, which starts with an empty dense bitmap and just fills in parts of it from the chunk bits in different arenas.
Pushed by bhackett@mozilla.com: Use a sparse representation for atom mark bitmaps in zones, r=jonco.
Status: NEW → RESOLVED
Closed: 3 years ago
Resolution: --- → FIXED
Target Milestone: --- → mozilla54
Are things looking better for you since this patch landed?
status-firefox52: --- → unaffected
Flags: needinfo?(bugzilla.mozilla.org)
yes, significantly ├──1,723.45 MB (45.07%) -- js-non-window │ ├──1,563.88 MB (40.90%) ++ zones │ ├────136.14 MB (03.56%) -- runtime │ │ ├───79.85 MB (02.09%) ── atoms-mark-bitmaps │ │ └───56.30 MB (01.47%) ++ (13 tiny)
Flags: needinfo?(bugzilla.mozilla.org)
Thanks for confirming!
Status: RESOLVED → VERIFIED | https://bugzilla.mozilla.org/show_bug.cgi?id=1341006 | CC-MAIN-2020-24 | refinedweb | 1,038 | 72.53 |
Advertise Jobs
Perl
module
-
Part of CPAN
distribution
Inline-CPP 0.23.
Inline:;
}
END_OF_CPP_CODE
The Inline::CPP module allows you to put C++ source code directly
"inline" in a Perl script or module. You code classes or functions in
C++, and you can use them as if they were written in Perl.
Inline::CPP
Inline::CPP just parses your C++ code and creates bindings to it. Like
Inline::C, you will need a suitable compiler the first time you run the
script. Choosing a C++ compiler can prove difficult, because Perl is
written in C, not.
gcc
g++
cc
CC
Some compilers actually compile both C and C++ with the same compiler.
Microsoft's cl.exe is one such compiler -- you pass it the <-TP> flag
to convince it that you want C++ mode.
cl.exe
Inline::CPP is very similar to Inline::C. in C++.
For more information about the grammar used to parse C++ code, see the
section called "Grammar".
The following example shows how C++ snippets map into the Perl
namespace:
Example 1:
use Inline CPP => <<'END';).
$obj
For information on how to specify Inline configuration options, see
Inline. This section describes each of the configuration options
available for C. Most of the options correspond either Config => AUTO_INCLUDE => '#include "something.h"';
Specifies code to be run when your code is loaded. May not contain any
blank lines. See perlxs for more information.
use Inline Config => BOOT => 'foo();';
Specifies which compiler to use.
Specifies extra compiler flags. Corresponds to the MakeMaker option. so they don't conflict with C functions
of the same name. iostream.h at the top of your code. This
option makes it include iostream instead, which is the ANSI-compliant
version of the makefile. On non-GNU implementations, these files are not
compatible with one another.
iostream.h
iostream.
Inline::Struct
C++.
Here are some examples.
This example illustrates how to use a simple class (Farmer) from
Perl. One of the new features in Inline::CPP is binding to classes
with inline method definitions:
Farmer
my $farmer = new Farmer("Ingy", 42);
my $slavedriver = 1;
while($farmer->how_tired < 420) {
$farmer->do_chores($slavedriver);
$slavedriver <<= 1;
}
print "Wow! The farmer worked ", $farmer->how_long, " hours!.
Object
The Airplane is a fully-bound class which can be created and
manipulated from Perl.
Airplane
my $plane = new Airplane;
$plane->print;
if ($plane->isa("Object")) { print "Plane is an Object!\n"; }
unless ($plane->can("fly")) { print "This plane sucks!\n"; }
/*;
}
double avg(...) {
Inline_Stack_Vars;
double avg = 0.0;
for (int i=0; i<items; i++) {
avg *= i;
avg += SvNV(ST(i));
avg /= i + 1;
}
return avg;
}
The perl sub runs in 14.18 seconds, an average of 0.0709s per call.
The C function runs in 1.52 seconds, an average of 0.0076s per call.;
};.
Inline
For information on using C with Perl, see Inline::C and
Inline::C-Cookbook. For WMTYEWTK, see perlxs,
perlxstut, perlapi, and perlguts.
WMTYEWTK:
The grammar used for parsing C++ is still quite simple, and does not allow
several features of C++:
Other grammar problems will probably be noticed quickly.
In order of relative importance, improvements planned in the near
future are:
Neil Watkiss <NEILW@cpan.org>
Brian Ingerson <INGY@cpan.org> is the author of Inline,
Inline::C and Inline::CPR. He is known in the innermost Inline
circles as "Batman". ;)
Inline::C
Inline::CPR
All Rights Reserved. This module is free software. It may be used,
redistributed and/or modified under the same terms as Perl itself.
See | http://aspn.activestate.com/ASPN/CodeDoc/Inline-CPP/CPP.html | crawl-002 | refinedweb | 584 | 68.97 |
-
DESCRIPTION
The examples in this FAQ assume a standard POSIX shell, like
bash or
dash,
and a user, A U Thor, who has the account
author on the hosting provider
git.example.org.
Configuration
- What should I put in
user.name?
You should put your personal name, generally a form using a given name and family name. For example, the current maintainer of Git uses "Junio C Hamano". This will be the name portion that is stored in every commit you make.
This configuration doesn’t have any effect on authenticating to remote services; for that, see
credential.usernamein git-config[1].
- What does
http.postBufferreally do?
This option changes the size of the buffer that Git uses when pushing data to a remote over HTTP or HTTPS. If the data is larger than this size, libcurl, which handles the HTTP support for Git, will use chunked transfer encoding since it isn’t known ahead of time what the size of the pushed data will haven’t specified an editor specifically for Git, it will by default use the editor you’ve configured using the
VISUALor
EDITORenvironment variables, or if neither is specified, the system default (which is usually
vi). Since some people find
vidifficult to use or prefer a different editor, it may be desirable to change the editor used.
If you want to configure a general editor for most programs which need one, you can edit your shell configuration (e.g.,
~/.bashrcor
~/.zshenv) to contain a line setting the
EDITORor
VISUALenvironment variable to an appropriate value. For example, if you prefer the editor
nano, then you could write the following:
export VISUAL=nano
If you want to configure an editor specifically for Git, you can either set the
core.editorconfiguration value or the
GIT_EDITORenvironmentoption to avoid backgrounding the process.
Credentials
- How do I specify my credentials when pushing over HTTP?
The easiest way to do this is to use a credential helper via the
credential.helperconfiguration. Most systems provide a standard choice to integrate with the system credential manager. For example, Git for Windows provides the
wincredcredential manager, macOS has the
osxkeychaincredential manager, and Unix systems with a standard desktop environment can use the
libsecretcredential manager. All of these store credentials in an encrypted store to keep your passwords or tokens secure.
In addition, you can use the
storecredential manager which stores in a file in your home directory, or the
cachecredential?
The
credential.helperconfiguration option can also take an arbitrary shell command that produces the credential protocol on standard output. This is useful when passing credentials into a container, for example.?
Usually, if the password or token is invalid, Git will erase it and prompt for a new one. However, there are times when this doesn’t always happen. To change the password or token, you can erase the existing credentials and then Git will prompt for new ones. To erase credentials, use a syntax like the following (substituting your username and the hostname):
$ echo url= | git credential reject
- How do I use multiple accounts with the same hosting provider using HTTP?
Usually the easiest way to distinguish between these accounts is to use the username in the URL. For example, if you have the accounts
authorand
committeron
git.example.org, you can use the URLs and. This way, when you use a credential helper, it will automatically try to look up the correct credentials for your account. If you already have a remote set up, you can change the URL with something like
git remote set-url origin(see git-remote[1] for details).
- How do I use multiple accounts with the same hosting provider using SSH?
With most hosting providers that support SSH, a single key pair uniquely identifies a user. Therefore, to use multiple accounts, it’s necessary to create a key pair for each account. If you’re using a reasonably modern OpenSSH version, you can create a new key pair with something like
ssh-keygen -t ed25519 -f ~/.ssh/id_committer. You can then register the public key (in this case,
~/.ssh/id_committer.pub; note the
.pub) with the hosting provider.
Most hosting providers use a single SSH account for pushing; that is, all users push to the
gitaccount or
git@example_committerinstead of
git@example.org(e.g.,
git remote set-url git@example_author:org1/project1.git).
Common Issues
- I’ve made a mistake in the last commit. How do I change it?
You can make the appropriate change to your working tree, run
git add <file>or
git rm <file>, as appropriate, to stage it, and then
git commit --amend. Your change will be included in the commit, and you’ll be prompted to edit the commit message again; if you wish to use the original message verbatim, you can use the
--no-editoption to
git commitin addition, or just save and quit when your editor opens.
- I’ve made a change with a bug and it’s been included in the main branch. How should I undo it?
The usual way to deal with this is to use
git revert. This preserves the history that the original change was made and was a valuable contribution, but also introduces a new commit that undoes those changes because the original had a problem. The commit message of the revert indicates the commit which was reverted and is usually edited to include an explanation as to why the revert was made.
- How do I ignore changes to a tracked file?
Git doesn’t provide a way to do this. The reason is that if Git needs to overwrite this file, such as during a checkout, it doesn’t know whether the changes to the file are precious and should be kept, or whether they are irrelevant and can safely be destroyed. Therefore, it has to take the safe route and always preserve them.
A
gitignorefile ensures that certain file(s) which are not tracked by Git remain untracked. However, sometimes particular file(s) may have been tracked before adding them into the
.gitignore, hence they still remain tracked. To untrack and ignore files/patterns, use
git rm --cached <file/pattern>and add a pattern to
.gitignorethat matches the <file>. See gitignore[5] for details.
- How do I know if I want to do a fetch or a pull?
A fetch stores a copy of the latest changes from the remote repository, without modifying the working tree or current branch. You can then at your leisure inspect, merge, rebase on top of, or ignore the upstream changes. A pull consists of a fetch followed immediately by either a merge or rebase. See git-pull[1].
Merging and Rebasing
- What kinds of problems can occur when merging long-lived branches with squash merges?
In general, there are a variety of problems that can occur when using squash merges to merge two branches multiple times. These can include seeing extra commits in
git logoutput, with a GUI, or when using the
...notation to express a range, as well as the possibility of needing to re-resolve conflicts again and again.
When Git does a normal merge between two branches, it considers exactly three points: the two branches and a third commit, called the merge base, which is usually the common ancestor of the commits. The result of the merge is the sum of the changes between the merge base and each head. When you merge two branches with a regular merge commit, this results in a new commit which will end up as a merge base when they’re merged again, because there is now a new common ancestor. Git doesn’t have to consider changes that occurred before the merge base, so you don’t have to re-resolve any conflicts you resolved before.
When you perform a squash merge, a merge commit isn’t created; instead, the changes from one side are applied as a regular commit to the other side. This means that the merge base for these branches won’t have changed, and so when Git goes to perform its next merge, it considers all of the changes that it considered the last time plus the new changes. That means any conflicts may need to be re-resolved. Similarly, anything using the
...notation in
git diff,
git log, or a GUI will result in showing all of the changes since the original merge base.
As a consequence, if you want to merge two long-lived branches repeatedly, it’s best to always use a regular merge commit.
- If I make a change on two branches but revert it on one, why does the merge of those branches include the change?
By default, when Git does a merge, it uses a strategy called the
ortstrategy,. Note that rebases rewrite history, so you should avoid rebasing published branches unless you’re sure you’re comfortable with that. See the NOTES section in git-rebase[1] for more details.
Hooks
- How do I use hooks to prevent users from making certain changes?
The only safe place to make these changes is on the remote repository (i.e., the Git server), usually in the
pre-receivehook or in a continuous integration (CI) system. These are the locations in which policy can be enforced effectively.
It’s common to try to use
pre-commithooks (or, for commit messages,
commit-msghooks) to check these things, which is great if you’re working as a solo developer and want the tooling to help you. However, using hooks on a developer machine is not effective as a policy control because a user can bypass these hooks with
--no-verifywithout being noticed (among various other ways). Git assumes that the user is in control of their local repositories and doesn’t try to prevent this or tattle on the user.
In addition, some advanced users find
pre-commithooks to be an impediment to workflows that use temporary commits to stage work in progress or that create fixup commits, so it’s better to push these kinds of checks to the server anyway.
Cross-Platform Issues
- I’m on Windows and my text files are detected as binary.
Git works best when you store text files as UTF-8. Many programs on Windows support UTF-8, but some do not and only use the little-endian UTF-16 format, which Git detects as binary. If you can’t use UTF-8 with your programs, you can specify a working tree encoding that indicates which encoding your files should be checked out with, while still storing these files as UTF-8 in the repository. This allows tools like git-diff[1] to work as expected, while still allowing your tools to work.
To do so, you can specify a gitattributes[5] pattern with the
working-tree-encodingattribute. For example, the following pattern sets all C files to use UTF-16LE-BOM, which is a common encoding on Windows:
*.c working-tree-encoding=UTF-16LE-BOM
You will need to run
git add --renormalizetofile in the repository will apply to all users of the repository.
See the following entry for information about normalizing line endings as well, and see gitattributes[5] for more information about attribute files.
- I’m on Windows and git diff shows my files as having a
^Mat the end.
By default, Git expects files to be stored with Unix line endings. As such, the carriage return (
^M) that is part of a Windows line ending is shown because it is considered to be trailing whitespace. Git defaults to showing trailing whitespace only on new lines, not existing ones.
You can store the files in the repository with Unix line endings and convert them automatically to your platform’s line endings. To do that, set the configuration option
core.eolto
nativeand see the following entry for information about how to configure files as text or binary.
You can also control this behavior with the
core.whitespacesetting if you don’t wish to remove the carriage returns from your line endings.
- whose names differ onlyhook .
- What’s the recommended way to store files in Git?
While Git can store and handle any file of any type, there are some settings that work better than others. In general, we recommend that text files be stored in UTF-8 without a byte-order mark (BOM) with LF (Unix-style) endings. We also recommend the use of UTF-8 (again, without BOM) in commit messages. These are the settings that work best across platforms and with tools such as
git diffand
git merge.. | https://git-scm.com/docs/gitfaq/2.34.0 | CC-MAIN-2022-27 | refinedweb | 2,097 | 62.07 |
Numpy tile allows you to repeat the whole NumPy array in one dimension or two dimensions. There is also another function that allows you to repeat elements of the array. It is numpy.repeat(). But in case you want to repeat the whole array then the NumPy tile() method is used. In this entire tutorial, you will know how to implement numpy tile() method with examples.
Steps to implement NumPy tile function
Step 1: Import all the required libraries
Here in our example, we are using only the NumPy array so let’s import them using the import statement.
import numpy as np
Step 2: Create a dummy array
The second step is to create a sample array where you will implement the various examples. You can create a NumPy array using the numpy.array() method . I will use the tile() method both on the 1D array and 2D array. So let’s create them.
1D Numpy array
array_1d = np.array([10,20,30])
2D Numpy array
array_2d= np.array([[10,20,30],[40,50,60]])
Step 3: Apply the numpy tile method
After the creation of the NumPy array let’s apply the tile method. There are many ways to apply it. Let’s explore all the examples.
Example 1: Repeating over columns
To repeat the array over the columns then you have to pass the value as the second argument inside the tile() method. Execute the below lines of code.
1D array
np.tile(array,2)
Output
2 D array
np.tile(array_2d,2)
Output
Example 2: Repeating array over Rows
To repeat the array over rows then you have to pass the tuple (no_of_rows, no_of_columns) as an argument to the tile() method. For example, I want to repeat the array for 2 rows then I will execute the following code.
1 D array
np.tile(array_1d,(2,1))
Output
2D Array
np.tile(array_2d,(2,1))
Output
Example 2: Repeating array over Rows and columns
In the above two examples, you have repeated arrays over columns or rows. Now let’s repeat the array in both rows and columns. To do so you have to pass both the columns and rows as an argument of the tile() method.
1D array
np.tile(array_1d,(2,3))
Output
2D array
np.tile(array_2d,(2,3))
Output
Conclusion
These are the examples on the NumPy tile that I have aggregated for you. Numpy tile() allows you to easily repeat your NumPy arrays along with columns or rows. I hope this tutorial has cleared your all queries on tile() method. Even if you have doubt then you can contact us for more help.
Source:
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox. | https://www.datasciencelearner.com/numpy-tile-method-implementation-python/ | CC-MAIN-2021-39 | refinedweb | 461 | 75.4 |
Dane Hillard
Writing Publishing Python Packages 🐍📦 ⬆️ Author of Practices of the Python Pro 🐍📘 Principal Engineer at ITHAKA
Education
University of Michigan
Work
Lead web application developer at ITHAKA
I'm writing Publishing Python Packages
Practices of the Python Pro out now!
Practices of the Python Pro is on Product Hunt
Learn the Django User Authentication System
Our Open Source Software in the Wild
Form habits by making the right thing easiest
A flexible approach to Python API client development
Truly taking time off: A checklist
Integrating ButterCMS in your Vue application
I'm writing Practices of the Python Pro
Be more productive with shell aliases
Open sourcing apiron: A Python package for declarative RESTful API interaction
Recent comments
Practices of the Python Pro - Book Review
Thank you for this review, Albert! Your point about the title...
Practices of the Python Pro is on Product Hunt
Thanks so much! Please let me know how you like it! The boo...
Practices of the Python Pro is on Product Hunt
Great question! Whereas Fluent Python is specifically geare...
What do you use for password management?
Like @dbh mentions in another thread, storing the Vault fi...
Daily Challenge #38 - Middle Name
def initialize(full_name): names = full_name.split() ...
Daily Challenge #36 - Let's go for a run!
def running_pace(distance, time): minutes, seconds = [i...
Daily Challenge #35 - Find the Outlier
I believe this would fail if the outlier is even and the re...
Daily Challenge #35 - Find the Outlier
This goes through the list of numbers only a single time, s... | https://practicaldev-herokuapp-com.global.ssl.fastly.net/easyaspython | CC-MAIN-2022-33 | refinedweb | 256 | 61.77 |
Retail software development kit (SDK)
Important
This topic applies to Dynamics 365 for Retail and Dynamics 365 for Finance and Operations.
This topic provides general information about the Retail SDK. The Retail SDK includes code, code samples, templates, and tools that you can use to customize retail functionality.
Overview
The Retail software development kit (SDK) includes code, code samples, templates, and tools that you can use to add new or customize existing retail functionality. The SDK supports rapid development, full MSBuild integration, package generation, and code separation.
Note
The Retail SDK supports TLS (Transport Layer Security) 1.2 standard, any customization build using the Retail SDK should follow TLS 1.2 standard.
Download the Retail SDK
The Retail SDK is available in development environments, and in hotfix packages in a Retail SDK folder. For more information see:
- If you get the SDK from a development instance, it is immediately ready for configuration and use. For more information, see Access instances.
- If you get the SDK from a hotfix, it is included in the hotfix package as a zipped folder. Retail hotfixes are cumulative and includes all other fixes.
We recommend that you put the SDK in a source control system such as Visual Studio Online.
Rapid development
The main focus of the Retail SDK is to help you write customizations efficiently and correctly. The SDK lets you run applications directly in a single-computer demo environment by using the F5 functionality (run and debug) in Microsoft Visual Studio. All the required "deployment chores" are done for you. Therefore, you don't have to copy any files.
Full MSBuild integration
The Retail SDK is a build system. A simple MSBuild command from the root of the SDK builds everything. This behavior eliminates guesswork about how and where to build from, and guarantees consistency and reproducibility. Therefore, the Retail SDK can easily be used together with any application lifecycle management (ALM) system, even Microsoft Visual Studio Online. This integration includes automation of the build.
Creation of final update packages, and better and explicit control over the customization
The Retail SDK includes tools that generate new packages that include everything that is required in order to deploy a service. For example, if the commerce runtime is extended with a new custom service dynamic-link library (DLL), the SDK automatically includes the new DLL in all appropriate packages (RetailServer and MPOSOffline). Or, if the database is extended, the upgrade script is automatically included in both RetailServer and MPOSOffline packages, because these are the packages that must (potentially) run the channel database update. Files that are shared exist only one time in the SDK. The packaging projects are set up in such a way that they pull in the right files for the package. Therefore, you edit a commerceruntime.config file in only one place. The same applies for deployment-related script files, even though these files rarely require customization.
Better code separation
If the Retail SDK needs to be updated, a potential code merge is required. This requirement applies to existing code samples or templates that have been changed. Some features in the implementation and in the folder structure of the SDK help to provide an easy way to separate customized code from sample code. You can expect to see additional improvements to code separation in future releases.
Real-world implementation samples
In addition to the source code of some of the Retail implementations, the Retail SDK includes sample code that illustrates how certain scenarios should be implemented.
Retail SDK deep dive
Prerequisites
To code or build your customization, you must have the following tools:
- Microsoft Visual Studio 2015 with Typescript 1.5 (an LCS developer topology is acceptable)
- ASP.NET MVC 4.0 (an LCS developer topology acceptable) (required only by StoreFront)
- A minimum of 150 MB of available disk space (an LCS developer topology is acceptable)
This list of requirements is very short and lets developers be productive on simple laptops. There is no longer a prerequisite for a validation utility.
To run your customization, the normal prerequisites to run Retail apply. We recommend that you run the customizations on a single-box developer topology (either LCS cloud-hosted or downloaded) during development.
Retail SDK contents
The following folders and files are part of the Retail SDK at the top level.
Note
The folder structure and description above are applicable only for the Retail July 2017 update (7.2). In the Retail 7.3 release, we sealed the Retail proxy and Hardware station projects. Therefore, in the Retail 7.3 release, you will see only samples for Hardware station and retail proxy. The proxy can be generated by following the new extensibility pattern.
The C# source code in the SDK uses the Contoso namespace. Therefore, it's easier to distinguish Microsoft types and your own types, because Microsoft uses Microsoft.Dynamics. If you're referencing a type from the Microsoft binary, reference it by using Microsoft.Dynamics. That way, you'll know that it's not from the Retail SDK but from a referenced binary.
Dependencies, build order, and full build
The following illustration shows a high-level logical dependency tree within the Retail SDK. It doesn't show the references to all Microsoft files or assets. To see these, look at the Visual Studio project and solution files in more detail.
Consider the following important points:
- The RetailServer API is consumed by a few projects by means of automatically generated client proxy code. This behavior allows for more rapid development, and reduces opportunities for errors and bugs. By default, the Retail SDK uses the official Microsoft DLL to generate the client code. Customizers can switch to their own DLL (in Customization.settings) and therefore automatically generate the proxy code for their customized RetailServer API. After switching the DLL, a developer might have to change some implementations inside the RetailProxy project. The reason is that Modern POS in offline mode must communicate directly with the commerce runtime, and that code must be implemented. However, no guesswork is required. The C# compiler will force it.
- The packaging projects generate the deployment packages in the way that LCS expects them. By default, these projects will ship only the Microsoft assets (non-customized) and the proxy DLLs. Anything else that should be included must be explicitly named in Customization.settings. This behavior is by design. It reduces the deployed custom code and allows for binary patches. For example, a customization adds a new CommerceRuntime service and a new RetailServer controller. In this case, two new DLLs are registered for inclusion in the packages and are automatically included in all relevant places. The packages will not have all recompiled binaries from the SDK.
- There is no single Visual Studio solution that includes all projects. Because there are few couplings between the various Visual Studio projects, you can open multiple projects or solutions side by side, and can compile the appropriate project after a change.
- Even if you didn't customize every component, the easiest way to get the final deployment packages is by building the whole Retail SDK. To do this, open an MSBuild Command Prompt for VS2015 window, and enter msbuild (or msbuild /p:Configuration=Release for a non-debug version).
This command will build all projects. This approach also provides a great way to verify that there are no implementation or code bugs. If there are any bugs, the build will fail, and the Command Prompt window will show what failed (this output resembles what Visual Studio would show).
For detailed help for MSBuild, see.
The binaries that the build creates are automatically copied to the SDK's References folder. The References folder also includes all the other binaries. Notice that no DLLs are overwritten, because they are all prefixed with a name (in this case, "Contoso") that you can define in Customization.settings.
Minimal required configuration
Do you just want to quickly build the Retail SDK, or to run POS in the debugger on a demo machine? For Modern POS only, you must create an app package signing certificate in order to build correctly. Alternatively, you can use Cloud POS. Follow the instructions at to create a PFX file. Then copy the PFX file to the BuildTools folder, and update the BuildTools\Customization.settings file with the correct name (ModernPOSPackageCertificateKeyFile). At this point you have everything that you require in order to build individual solutions, projects, or the whole Retail SDK (by using MSBuild).
Normal configuration/code signing
BuildTools\Customization.settings holds most of the configuration values for the SDK. The highlighted items in the following illustration are the global values. These values control how built binaries, components, and packages are named, versioned, and code-signed.
It's good practice to sign your assemblies with a strong name, even though this isn't required. To learn how to create your own key file if you don't already have one, see. To build correctly, you must create an app package signing certificate. Follow these instructions at to create a PFX file. Both the strong name key file and the app package signing certificate can be stored inside the BuildTools folder. The RetailServerLibraryPathForProxyGeneration property can be used to set a different RetailServer DLL for proxy generation. Customization.settings is also the place to define your new customization assets, such as binaries, configuration files, and SQL update scripts. After you specify your extensions, binaries, and assets here, the files will be added in the deployable package that is created.
Customizing the build
Adding new projects
It's easy to add new projects to the Retail SDK's build system. You can either clone one of the many existing projects or start a new project. You just have to make some adjustments in a text editor, as shown in the following illustration. The relative path of the Import elements should be adjusted, and the AssemblyName element should use the predefined AssemblyNamePrefix property. These adjustments are required in order to get versioning, code signing, uniform assembly naming, automatic dropping to the References folder, and other tasks for free.
Changing the build order or adding to the build
The whole directory tree of the Retail SDK is built with the help of MSBuild traversal files (dirs.proj files). The following illustration shows the main traversal file of the Retail SDK. Similar files might also exist in subdirectories. Notice that Visual Studio solution files (.sln files) are very similar to traversal files. Both "direct" the MSBuild engine to process other build scripts.
After new code is added, most of it should be located in a new folder (for details, see "Best practices of code implementation"), and you must add it to the traversal structure by adding to one or multiple dirs.proj files. The Extensions folder appears highlighted on line 10 in the previous illustration. The quickest way to get started with a new dirs.proj file is to copy an existing file, correct the paths in the Import elements, and update the ProjectFiles elements in the ItemGroup element.
Build script customization
When you must implement new build steps, keep in mind that the existing scripts might be updated by a Retail SDK update later. Best practice is to minimize the editing of any file, or add new files instead. If you require new global MSBuild properties, BuildTools\Microsoft.Dynamics.RetailSDK.Build.props is a good place to add them. Likewise, BuildTools\Microsoft.Dynamics.RetailSDK.Build.targets can be used to add new build processing targets. If only one project requires special handling, it is better to explicitly make the change there. If you require new local MSBuild properties, add a new file that is named local.props in the same directory. Alternatively, add a local.targets file if you require local build processing targets.
Developer productivity
As shown in the architecture diagram earlier in this article, several things depend on the RetailServer interface. It is likely that someone will change this interface. On a developer topology machine, someone might want to immediately try out a change. In this case, any CommerceRuntime and RetailServer extension DLLs must be copied into the bin folder of the locally installed RetailServer web application. A user can configure the Customization.setting file so that the DLLs are automatically copied into the bin folder of the local RetailServer web application whenever new versions of these files are built.
Application lifecycle management
A good ALM solution provides version control, builds, automated builds, planning tools, tracking tools, dashboards, customization, and more. The Retail SDK is organized in such a way that it supports these tasks.
[Azure DevOps](/Azure DevOps/) is a great tool and is recommended.
Branching and versioning
To work efficiently in a team, or even just to be able to go back and look at some changes that were done in the past, you must have good branching strategy and versioning discipline. The following illustration shows a simple branching strategy that might work well for most teams. The version numbers are fictitious.
Retail SDK mirror branch
A very important point to emphasize is that the non-customized Retail SDK should be stored in your source control. You don't have to store every version, but the versions that your team wants to snap to should be added (these versions might be cumulative updates or hotfixes). Only a simple merge of all changes (additions, changes, and deletions) should be done. No other development work should occur in this branch. The Retail SDK has its own version. All Retail binaries and packages that are included have the same version. The version can also be found in the root of the Retail SDK in a file that is named Microsoft-version.txt.
Customization branch
After development can start, a new branch should be started (customization branch). At the beginning of the initial branch-out, this branch will be an exact copy of the Retail SDK mirror branch. This is the branch for a team's development. The version of the customization branch must be incremented at least every time that a build is created for testing, or it can even be incremented daily. The file version to increment is defined in Customization.setting file by using the CustomVersion property. If you update it and rebuild, all binaries, packages, manifest files are updated accordingly. Note that the CustomAssemblyVersion property should be updated only when the update isn't backward compatible and/or for major new releases. In other words, this update should very rarely. For example, Microsoft's assembly version stayed the same for the multiple CTP releases for the current version. Because there are both Microsoft assets and your own changes in the same branch, the branch essentially has two file versions. The first version is the Microsoft version of the Retail SDK that the current branch is based on, and the second version is the version that is set by the CustomVersion property. In the previous illustration, the current file version of the customization branch is 1.0.2.* (based on Microsoft version 7.0.2200.3). The file version of the first rolled-out release was 1.0.0.40 (based on 7.0.2000.0). When a testing phase is completed, and the final packages are being deployed with that version, it's important that you increment the version (or create a source control label).... | https://docs.microsoft.com/kk-kz/dynamics365/unified-operations/retail/dev-itpro/retail-sdk/retail-sdk-overview | CC-MAIN-2019-26 | refinedweb | 2,561 | 56.15 |
I'm doing some tutorials online...and I'm stuck at an exercise:Define a function
L#L#L#
L
#
S
False
S
L#L#L#
L
def postalValidate(S):
while " " in S:
S.remove(" ")
for i in range(1,6,2):
S.isdigit(S[i])
for j in range(0,5,2):
S.upper(S[j]
S.isalpha(S[j])
return True
This is clearly a job for regular expressions, although I don't know if you're supposed to use them in the exercise...
I'm posting this as an answer just in case you can. Otherwise, let us know...
#/usr/bin/evn python import re zipCode = re.compile(r"\s*(\w\d\s*){3}\s*") if __name__ == "__main__": samples = [ " 44F 4 F", #Invalid " L0L0L0 ", #Valid " L0 L0 L0 ", #Valid ] for sample in samples: if zipCode.match(sample): print "The string %s is a valid zipCode (nice and clean: %s)" % (sample, sample.replace(" ", "").upper()) else: print "The string %s is NOT a valid zipCode" % sample
Edit:
Since you can not use regular expressions, I'd recommend you change the way of thinking... Instead of checking if the characters belong to a valid postal code, I'd recommend you do the opposite: check if they DON'T belong in a valid postal code, returning False as soon as you detect a misplaced (or wrong) character:
def postalValidate(S): S = S.upper().replace(" ", "") if len(S) == 6: for i in range(len(S)): if i % 2 == 0: #Even index (0, 2, 4, 6...) , has to be 'letter' if not(S[i].isalpha()): return False else: #Odd index (1, 3, 5, 7...), must be 'number' if not(S[i].isdigit()): return False else: #You can save some cpu ticks here... at this point, the string has to be of length 6 or you know it's not a zip return False return S
The return statement stops the execution of the current function so as soon as you realize that there's something "wrong" with the string to check, you can return False (there's no point on keeping checking once you know it's not valid, right?) | https://codedump.io/share/TRGRrW8ADPu1/1/validate-postal-code | CC-MAIN-2019-09 | refinedweb | 357 | 71.65 |
Web Scraping Framework
Project description
- And much, much more
- Grab has written by the guy who is doing site scraping since 2005
Example of Grab usage:
from grab import Grab g = Grab() g.go('') g.set_input('login', 'lorien') g.set_input('password', '***') g.submit() for elem in g.doc.select('//ul[@id="repo_listing"]/li/a'): print '%s: %s' % (elem.text(), elem.attr('href'))
Example of Grab::Spider usage: grab
See details here
Documentation
Russian docs:
English docs in progress:
Mailing List (Ru/En languages):
Contribution
If you have found a bug or wish a new feature please open new issue on github:
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/grab/0.5.3/ | CC-MAIN-2018-51 | refinedweb | 128 | 53 |
Due to the policy change imposed by Google to protect users from harmful code, there were a number of change required to the extension.
I also took advantage of the changes to upgrade to a new jQuery file and refactor some other code.
This:
{
/"
]
}
(Manifest Version 1) The 'update_url' element defined the XML file used by the Auto Update tool to check for newer revisions of the extension. As of Version 2, this is no longer required as the extension is hosted through the Chrome store. Chrome Browser takes care of the version update process. This property was susequently removed.. The browser will however keep reminding you and asking if you want to disable this mode.
Once you have installed by either method,)
public class SanderRossel : Lazy<Person>
{
public void DoWork()
{
throw new NotSupportedException();
}
}
DaveAuld wrote:Have you had a look on the chrome://extensions/ page to see if you can explicitly enable it?
var category = $(this).text();
var category = $(this).find("a").text();
var category = $(this).text();
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/98631/Google-Chrome-Extension-CodeProject-Reputation-Wat?msg=3822436 | CC-MAIN-2015-48 | refinedweb | 198 | 64.41 |
My data is a csv that looks like:
1 abc
1 def
2 ghi
3 jkl
3 mno
3 pqr
abc; def
jkl; mno
mno; pqr
First, your input csv file is not really a csv. It's more a file that can be parsed using
str.split. Well.
Now, I'll get the tokens and use
itertools.groupby using first column as key to group items with same first column.
Once you have that, filter out the lists with one 1 item, and apply a combination on the rest.
Write as a proper csv file:
import csv, itertools with open("test.csv") as f: with open("output.csv","w",newline="") as f2: # with open("output.csv","wb") as f2: # uncomment for python 2 (comment above!) cw = csv.writer(f2,delimiter=";") for l in itertools.groupby((l.split() for l in f),lambda x : x[0]): grouped = [x[1] for x in l[1]] if len(grouped)>1: for c in itertools.combinations(grouped,2): cw.writerow(c)
result (corrected, yours is not correct):
abc;def jkl;mno jkl;pqr mno;pqr | https://codedump.io/share/IV26FUMg2ahF/1/transforming-a-csv-to-a-list-of-co-occurrence-pairs-in-python | CC-MAIN-2017-30 | refinedweb | 182 | 84.37 |
Written By Leo Yorke,
Edited By Lewis Fogden
Thu 07 December 2017, in category Data science
In the first part of this series of blog posts we created a simple webscraper in Python that would go to Yahoo Finance and fetch a table of currency exchange rates. There are a couple of drawbacks using our previous approach. Firstly, we don't have any access to any historical exchange rates - only current ones - and secondly we have a limited list of currency pairs to choose from. In this post we are going to try and address these limitations and explore how we can take our webscraper a little bit further. All the code in this example and the previous blog can be found here.
Looking at Yahoo's website, they have a currency converter page that gives us the option to convert between a much more extensive list of currencies than were available to us previously. It also displays a plot of historical exchange rates for all of the currency pairs. If we can access the data behind that graph, we'll have exactly what we need. The problem is that this is no longer in a neat and tidy table for us to access so we will need a different approach.
If we inspect the page (
right click -> inspect) we'll discover that the HTML tag that contains the currency converter is actually an iframe - essentially a web page embedded within a web page.
<iframe name="currencyCalculator-iframe" allowtransparency="true" scrolling="no" frameborder="0" referrerpolicy="no-referrer" class="W(100%) Mb(5px) Bd(0) H(305px)--cclg H(560px)--ccmd H(305px)--ccsm H(560px)--ccxs" src="" id="Col1-0-IFrame" data- </iframe>
We can actually go to the embedded web page and take a look for ourselves to verify it is the currency converter widget used in the original page. Isolating this widget might make writing our webscraper a bit simpler, but how are we actually going to get data out of it?
One option would be to have a program that can open the page in a web browser such as Chrome, click through all the options in the dropdown, and scrape information as it goes. This is certainly feasible but is likely to be fairly slow due the overhead of driving the browser. Selenium is a popular browser automation framework, with APIs available in many languages including Python. However, for this post we're going to take a different approach.
Instead what we can do is get the data the same way that the widget does. Behind the scenes, every time we click on one of the dropdowns the website is going off and fetching the corresponding exchange rate from somewhere, so if we can duplicate that process we can fetch all the exchange rates we want.
We can use Chrome's DevTools to monitor what requests the website makes and where it sends them when we click on something. If we
right click -> inspect, go to the
Network tab, and then click on the dropdown we will see something similar to the following:
Each
1 in the
Name panel is the website making a request and by clicking on each of them we can see what the website is requesting. We can see that there is a
POST request being made, and by examining the
Headers and
Response tabs we can see what exactly is being sent and what is being returned.
At the bottom of the
Headers tab there is a section called
Request payload, which actually shows us what is being sent out by the website to request data. The website is sending off the following piece of JSON to the URL.
{ "method": "spotRateHistory", "data": { "base": "ARS", "term": "EUR", "period": "day" } }
If we switch to the
Response tab we can see what is being sent back. In return the website is receiving JSON data that looks like this:
{ "data": { "CurrentInterbankRate": 0.050245055371495, "HistoricalPoints":[ { "PointInTime": 1511352900000, "InterbankRate": 0.050556151155792685 }, ... ] } }
This looks suspiciously like the current exchange rate and historical data points for the exchange rate that we want. So now we have figured out where we can get our information from, how do we write a program that can go a make these
POST requests for us?
First let's import the libraries that we will need.
import bs4 # The goto library for parsing HTML documents import requests # Standard library module for handling URLs and HTTP requests import pandas as pd # The defacto tabular data manipulation library from datetime import datetime # Standard library module for working with dates
Looking at the format of the outgoing
POST request, it seems we will need a list of currency codes. We could just write the desired codes out manually, but ideally we should fetch a complete list of available ones from the website. Luckily it seems that the website itself makes a request for a list of currencies in the form of a JSON file,
USA.json on the
Network, so we can also use that. If this doesn't appear, just refresh the page.
URL = '' def get_webpage(url): return requests.get(url).json()
Now we have a list of currency codes, but examining
USA.json reveals that they're not quite in the format we want. We want a 3 letter code to match the request we want to copy, however the data we have at the moment looks like this:
{ "Registration Button A": "Transfer Now with OFX", "Registration URL": "", "Disclaimer": "Currency converter displays [Market Rates] and is not indicative of [OFX Customer Rates]", "Disclaimer Market Rates URL": "", "Disclaimer Customer Rates URL": "", "Currency Converter": "Currency Converter", "Conversion Unavailable": "temporarily unavailable", "Chart Page Link": "[More Charts]", "Chart Page URL": "https: //", "Chart Title Post Currencies": "Exchange Rates", "Brought to you by": "Sponsored and brought to you by", "Monday": "Monday", "Tuesday": "Tuesday", "Wednesday": "Wednesday", "Thursday": "Thursday", "Friday": "Friday", "Saturday": "Saturday", "Sunday": "Sunday", "Mon": "Mon", "Tues": "Tues", "Wed": "Wed", "Thurs": "Thurs", "Fri": "Fri", "Sat": "Sat", "Sun": "Sun", "1 Minute": "Minute", "1 Hour": "Hour", "1 Day": "Day", "1 Week": "Week", "1 Month": "Month", "1 Year": "Year", "All time": "All time", "Month": "Month", "Jan": "Jan", "Feb": "Feb", "Mar": "Mar", "April": "April", "May": "May", "June": "June", "July": "July", "Aug": "Aug", "Sept": "Sept", "Oct": "Oct", "Nov": "Nov", "Dec": "Dec", "AED - Description":"United Arab Emirates Dirham", ... }
We need to write a function that only keeps the desired text, leaving us with just the 3 letter currency codes:
def get_list_of_cys(response): l = [] for x in response.keys(): if x.endswith("- Description"): l.append(x.split("-")[0].strip()) return l
So now we have a list of currency codes we have enough to construct our request. All we need to do is copy the format of the JSON file we saw earlier and submit it to the same place as the website does, and we will get the same response. We can see that this only allows for one currency at a time, so we will need to loop over our different currencies. Finally we should convert the results from a JSON format into a tabular format so we could then write it out to a
.csv file or relational database if we wanted to.
POST_URL = '' COLUMNS = ['cy-pair', 'rate', 'date'] def post_loop(currencies): results = [] for base in currencies: for term in currencies: data = { "method": "spotRateHistory", "data": {"base": base, "term": term, "period": "day"} } f = requests.post(POST_URL, json=data).json() try: results.append( [base + term, f['data']['CurrentInterbankRate'], datetime.now()]) except Exception as e: print(e) return pd.DataFrame(results, columns=COLUMNS)
One thing to note is that all we are doing is returning the current exchange rate for different currency pairs, and ignoring the historical data points. The next step to expand our program would be to try and work out how to extract all the historical information as well, but we wont worry about that for now.
At this point let's also add a function to allow us to control which currency pairs we actually want to retrieve rather than just blindly fetching them all. If we ever do want to fetch them all we can just not call this function.
def filter_cys(currencies): allowed = set(['GBP', 'USD', 'EUR']) return list(allowed & set(currencies))
Now the final piece of the puzzle is to string all of our functions together and check everything is working.
if __name__ == "__main__": webpage = get_webpage(URL) currencies = get_list_of_cys(webpage) filtered = filter_cys(currencies) data = post_loop(filtered) print(data)
If we run it, we should get the following output:
$ python3 yf-post.py cy-pair rate date 0 USDUSD 1.000000 2017-11-24 10:40:41.857866 1 USDEUR 1.000000 2017-11-24 10:40:42.207901 2 USDGBP 0.751300 2017-11-24 10:40:42.557936 3 EURUSD 1.184300 2017-11-24 10:40:42.903970 4 EUREUR 1.000000 2017-11-24 10:40:43.254005 5 EURGBP 0.889744 2017-11-24 10:40:43.601040 6 GBPUSD 1.331100 2017-11-24 10:40:43.948075 7 GBPEUR 1.123919 2017-11-24 10:40:44.296109 8 GBPGBP 1.000000 2017-11-24 10:40:44.645144
Success! We have managed to write a program to make a HTTP request to an API endpoint and fetch a table of all the currency exchange rates that we want. We could also extend this to cover historical data points of up to a year if we wanted too. Get the full code here and try it out for yourself. | http://blog.keyrus.co.uk/a_simple_approach_to_webscraping_part_2.html | CC-MAIN-2022-05 | refinedweb | 1,583 | 60.75 |
On 09/26/2011 11:35 PM, Laine Stump wrote:
On 09/26/2011 04:31 PM, Eric Blake wrote:Commit ecd8725c dropped attempts to probe the cgconfig service on new enough Fedora where systemd took over that aspect of the system, but mistakenly used F14 instead of F15 as the cutoff point. * libvirt.spec.in (with_cgconfig): Check cgconfig service in F15. --- libvirt.spec.in | 4 ++-- 1 files changed, 2 insertions(+), 2 deletions(-) diff --git a/libvirt.spec.in b/libvirt.spec.in index c0ea898..03d6f1f 100644 --- a/libvirt.spec.in +++ b/libvirt.spec.in @@ -894,9 +894,9 @@ done %endif %if %{with_cgconfig} -# Starting with Fedora 15, systemd automounts all cgroups, and cgconfig is +# Starting with Fedora 16, systemd automounts all cgroups, and cgconfig is # no longer a necessary service. -%if 0%{?fedora}<= 14 || 0%{?rhel}<= 6 +%if 0%{?fedora}<= 15 || 0%{?rhel}<= 6 if [ "$1" -eq "1" ]; then /sbin/chkconfig cgconfig on fiACK
Thanks; pushed (actually, I merged 1/1 and 2/1 into a single patch, since they were both short).Thanks; pushed (actually, I merged 1/1 and 2/1 into a single patch, since they were both short).
-- Eric Blake eblake redhat com +1-801-349-2682 Libvirt virtualization library | https://www.redhat.com/archives/libvir-list/2011-September/msg01073.html | CC-MAIN-2015-22 | refinedweb | 204 | 57.47 |
Shifting data for creating lag features in time series modeling
I have a pandas dataframe in the below format. I am trying to convert the time series problem into a regression problem, hence in the process of creating lag features. But the "Price" is dependent not only on month and year, but also on columns make, AA, VO & value.
For creating lag features, I sorted the dataframe based on columns make, AA, VO, month, year and value. After that, I am not sure on how to create lag features as the price is dependent on several variables. I am pretty new to time series modeling and I understand this is an open ended question. Any suggestions would be greatly appreciated.
make AA VO month year value Price ACURA No Yes 1 2016 8 4271.41 ACURA No No 1 2018 8 1769.92 ACURA No No 1 2019 14 4363.9 ACURA No Yes 2 2018 2 671.84 ACURA No No 2 2016 29 3551.07 ACURA No Yes 5 2018 14 5044.95 ACURA No Yes 6 2016 11 4049.2 ACURA No Yes 7 2018 0 1466.29 ACURA No Yes 7 2019 0 4118.45 ACURA No Yes 12 2016 1 1062.03 ACURA No No 12 2018 23 7361.5
1 answer
- answered 2020-09-28 03:25 David Erickson
I think this is an example of what you are trying to do. I would include more columns in the
.groupby, but it would lead to all
NaNvalues, since the number of rows within each group of all the required columns is only one, so there is nothing to shift on; thus, it will return all
NaNvalues. However, if you groupby for example,
['make', 'month', 'value']then this would return a few values, just so you can visualize what is going on:
import pandas as pd df['Price Lag'] = df.groupby(['make', 'month', 'value'])['Price'].transform(lambda x: x.shift()) df Out[1]: make AA VO month year value Price Price Lag 0 ACURA No Yes 1 2016 8 4271.41 NaN 1 ACURA No No 1 2018 8 1769.92 4271.41 2 ACURA No No 1 2019 14 4363.90 NaN 3 ACURA No Yes 2 2018 2 671.84 NaN 4 ACURA No No 2 2016 29 3551.07 NaN 5 ACURA No Yes 5 2018 14 5044.95 NaN 6 ACURA No Yes 6 2016 11 4049.20 NaN 7 ACURA No Yes 7 2018 0 1466.29 NaN 8 ACURA No Yes 7 2019 0 4118.45 1466.29 9 ACURA No Yes 12 2016 1 1062.03 NaN 10 ACURA No No 12 2018 23 7361.50 NaN | https://quabr.com/64095457/shifting-data-for-creating-lag-features-in-time-series-modeling | CC-MAIN-2020-45 | refinedweb | 449 | 84.88 |
January 2018 (version 1.10.0-beta)
1.10.0 Update
Happy new year! 🎊 🎉
This year we are going to do our best. Keep a watchful eye on us.
We've released a 1.10.0 DeepScan service.
Keep reading for the highlights for this release.
Release Summary
This version includes a number of updates that we hope you will enjoy. The key highlights are:
- Vue.js support - We added support to analyze
.vuefile.
- Analysis improvements - Enhanced support for outer-scope variable.
- Improvements for React rules - Support React rules more precisely.
- New rules - New rules for common pitfalls.
- About the pull request check - Changes in the pull request check.
Vue.js support
While we have been supporting React rules actively, we have noticed we can't ignore Vue.js by its growth.
As a first step toward Vue.js support, we enhanced our analysis targets to include
.vue files. (For full listings of analysis targets, see here)
So, you can see the analysis results for the
<script> code in Vue.js single file component.
As of Demo, "Vue component" configuration was added. When you paste code, select "Vue component" in Configuration combo and just analyze.
Analysis Improvements
Enhanced support for outer-scope variable
We've further enhanced the analysis to handle complex use of outer-scope variables. Let's see an example:
let readyMap, queueMap; function consumeQueue(element) { const callbacks = queueMap.get(element, []) || []; // Number of arguments passed to 'WeakMap.prototype.get()' should be 1. But 2 arguments are passed. queueMap.delete(element); callbacks.forEach(callback => callback()); } export default function contentReady(element, fn = () => {}) { if (readyMap === undefined) { readyMap = new WeakMap(); queueMap = new WeakMap(); // queueMap is initialized here as a WeakMap type } addCallback(element, fn); if (isContentReady(element)) { consumeQueue(element); return; } ... }
Now, DeepScan is aware of the type (
WeakMap) of an outer variable (
queueMap).
The developer might have confused the second argument of
WeakMap.prototype.get() as a default value for non-existing key. But, it does not apply and the default value is actually specified by
|| [].
Provide the location of alarm cause by using React PropTypes declaration
To aid developers in fixing issues, we are taking a lot of effort to provide the location of alarm cause. We now support React PropTypes declaration as a cause. Let's see an example:
import React from 'react'; import PropTypes from 'prop-types'; class ProductCreate extends React.Component { static propTypes = { site: PropTypes.shape( { ID: PropTypes.number, slug: PropTypes.string, } ), }; render() { const site = this.props.site; const isValid = 'undefined' !== site && this.isProductValid(); // Condition ''undefined' !== site' is always true at this point. The value of variable 'site' is originated from the prop type declaration at line 6. const isBusy = Boolean( actionList ); const saveEnabled = isValid && ! isBusy; return ( <Main className={ className } wideLayout> <ProductHeader site={ site } onSave={ saveEnabled ? this.onSave : false } /> </Main> ); } }
The alarm is caused by
this.props.site having an object value because of the PropTypes declaration at line 6. The developer wrongly compared it with
'undefined' string value.
Improvements for React Rules
Precise application for JSX
Previously, React rules were applied for all JSX expressions. However, JSX is also used for other frameworks such as Preact and Vue.js. Now, we apply React rules only when the file actually uses React.
And in this context, REACT_JSX_BAD_COMMENT has been changed to JSX_BAD_COMMENT.
REACT_INEFFICIENT_PURE_COMPONENT_PROP
This rule applies when newly created object is always used as a `React.PureComponent` prop. We enhanced it to detect newly created objects by the JS and React API.
New Rules
- MISSING_ELSE_KEYWORD - Check for missing
elsekeyword in
else ifsequence
About the Pull Request Check
In the 1.8.0 release, we changed the pull request check as to be successful even when unresolved issues exist.
By some stabilization, now we restore it. So the pull request check in GitHub page will show a proper 'Failure' mark when there are unresolved issues.
Also, when there are two or more DeepScan projects for the repository, we will harmonize the pull request checks for all the projects and show a comprehensive result in GitHub page.
Miscellaneous
- Update Open Source Report which shows the inspection results of 200 JavaScript projects in GitHub:
- Inactive or non-impactive projects removed: naver/egjs, naver/jindojs-jindo, google/traceur-compiler, NUKnightLab/TimelineJS, Modernizr/Modernizr
- New projects: sproutcore/sproutcore, SAP/openui5, swagger-api/swagger-ui, RocketChat/Rocket.Chat, naver/billboard.js
- Support the analysis of the commit which is rewinded
- Depending on the span, display a date instead of just time in Trends chart
- Display an alarm message as multi-line instead of one-liner in the file viewer
Bug Fixes
- Add project-wide access control for some APIs | https://deepscan.io/docs/updates/2018-01 | CC-MAIN-2020-50 | refinedweb | 765 | 51.44 |
How do I make this so once the user inputs a number and presses enter(or something) it runs the
if
else statements?
public static void main(String[] args) {
System.out.println("please guess the number between 1 and 100.");
boolean run = true;
int y = 0;
Random ran = new Random();
int x = ran.nextInt(99);
while (run == true) {
Scanner scan = new Scanner(System.in).useDelimiter(" ");
// System.out.println(scan.nextInt());
y = scan.nextInt();
/*
* if(y > 0){ run = false; } else{ run = true; }
*/
if (y > x) {
System.out.println("Lower...");
} else if (y < x) {
System.out.println("Higher...");
} else if (y == x) {
System.out.println("Correct!");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}
}
}
}
Your code works as is. It is just that your input needs to be delimited by spaces.
If you input a single number and hit enter, there will be no space, and as you have set your
Scanner up to be delimited by spaces, it wont find anything. On the other hand, if you input:
3 9
(
3 [space]
9), your Scanner will pick up the 3. What you probably want is this:
Scanner scan = new Scanner(System.in).useDelimiter("\n");
so that your
Scanner will read a number after you hit enter. No matter which way you do this, you will want to put some error handling around the
Scanner to handle
InputMismatchExceptions.
I think your question is not very clear, the following changes seem logical, given the structure of your code:
else if (y == x) { System.out.println("Correct!"); run = false; }
and of course just
if(run) (a matter of good style)
Your code didn't actually generate numbers between 1 and 100 inclusive (rather, between 0 and 98 inclusive). Fixing this bug and adding some error checking, your code becomes:
import java.util.*; public class HiLo { public static void main(String[] args) { int guess = 0, number = new Random().nextInt(100) + 1; Scanner scan = new Scanner(System.in); System.out.println("Please guess the number between 1 and 100."); while (guess != number) { try { if ((guess = Integer.parseInt(scan.nextLine())) != number) { System.out.println(guess < number ? "Higher..." : "Lower..."); } else { System.out.println("Correct!"); } } catch (NumberFormatException e) { System.out.println("Please enter a valid number!"); } catch (NoSuchElementException e) { break; // EOF } } try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } | http://www.dlxedu.com/askdetail/3/79f8466f995f9f78221860e0d3353039.html | CC-MAIN-2019-13 | refinedweb | 392 | 51.24 |
Dec 10, 2007 10:37 PM|NigelLinnett|LINK
First of all congrats on getting this released. Must have been a lot of work, and panicked work over the weekend I guess.
Now for the problem. I have the VS2008 Pro RTM trial installed on Vista Ultimate. The only add-on installed is Resharper.
I created a new MVC Web Application (also tried it with an MVC Web Application and Test) and added a reference to the MVCToolkit dll. I opened the Index.aspx file, and typed <%= Html. and the dropdown only had ActionLink, Encode, and ViewContext options.
I tried adding a reference to the MVCToolkit project, and rebuilding the solution, but it didn't make a difference.
I have also tried using HtmlHelper instead of Html, and still didn't make a difference.
I'm assuming it's something I've done wrong, but can't figure out what it is. Anyone have any ideas?
Dec 11, 2007 11:31 AM|NigelLinnett|LINK
In the code behind I do see the HtmlHelper class. I tried creating a new method, and manually creating an instance of HtmlHelper
HtmlHelper hh = new HtmlHelper(ViewContext);
But the hh object, still isn't picking up any of the extensions (and a restart didn't help, will try a full system restart tonight).
Dec 11, 2007 10:46 PM|NigelLinnett|LINK
That's correct Rob. It looks as if VS isn't seeing the extension methods for some reason. When I look in the Object Browser, I see them all there (for instance, in the TextBoxExtensions class, I'm seeing all 21 methods there).
I just remembered today that I do have something else installed, the Entity Framework Beta 3, and the Entity Framework Tools (downloaded and installed Dec 6th), might that be connected?
Dec 12, 2007 12:30 AM|NigelLinnett|LINK
Problem solved, I restarted the system with no result.
Uninstalled all VS addins (turns out I also had Resharper 3.0.3 installed, and think that is likely the culprit since I was using it's intellisense, and it doesn't support the new features yet)
Re-installed the ASP.Net futures, and now I'm good to go.
So thanks guys for your help, but this one was my fault (haven't had a chance to do development in 2K8 since I installed the RTM)
Nigel
Jan 16, 2008 04:59 PM|dnoxs|LINK
Hi
I have a similar problem. I have just installed VS2008 Team System Development Edition. I then installed ASPNETExt.exe.
After starting VS2008 I attempt to do the following:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Costar.Focus.Web.Portal.Views.Security.Login" Title="Untitled Page" %>
<asp:Content
<h2>Login</h2>
<% if (ViewData["ErrorMessage"] != null)
{ %>
<%= ViewData["ErrorMessage"] %>
<% } %>
<% using (Html.Form("Authenticate", "Security"))
{ %>
Username: <%= Html.TextBox("username") %><br />
Password: <%= Html.Password("password") %><br />
<%= Html.SubmitButton() %>
<%= Html.Hidden("returnUrl", "/") %>
<% } %>
</asp:Content>
When I run it however I get this result: CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'Form' and no extension method 'Form' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive
or an assembly reference?)
In the object browser I can see the HtmlHelper object but it does not contain any functions for Form, TextBox, or Password. Here is the url I used to download ASPNETExt.exe from:
Any help would be appreciated.
Dec 01, 2008 11:03 AM|rodrijp|LINK
I have the same problem. When i revise de web.config file, you must have added the System.Web.Mvc.Html namespace.
<namespaces>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Linq"/>
<add namespace="System.Collections.Generic"/>
</namespaces>
12 replies
Last post Dec 01, 2008 11:03 AM by rodrijp | http://forums.asp.net/p/1192523/2051697.aspx?Problem+with+MVCToolkit | CC-MAIN-2014-42 | refinedweb | 650 | 60.21 |
The latest update for Windows 11 is a big one — and we’re not just talking about the size of the download. The update in question is KB5010414, and it’s something we have already touched on a couple of times.
Much of the focus has been, entirely understandably, on the new features the update brings; KB5010414 is about much more than this. Yes, the arrival of support for Android apps is nice, but it’s certainly not something everyone is interested in. What is more impressive and interesting about the KB5010414 is the laundry list of changes, tweaks and fixes Microsoft has introduced. This is what makes this the most significant update to Windows 11 yet.
The reason we have already written about the KB5010414 update is that it was first released to Insiders, and is now available as a preview update ahead of March’s Patch Tuesday when it will be unleashed on the masses.
Some of the most immediately noticeable changes are to be found in the taskbar. But, in addition to all of the headline-grabbing new features such as Android app support and new widget options, there are dozens of other noteworthy updates that will benefit users.
Microsoft draws attention to the following key changes, additions and fixes:
- New! Provides the ability to shares cookies between Microsoft Edge Internet Explorer mode and Microsoft Edge.
- New! Opens.
- New! Adds the clock and date to the taskbars of other monitors when you connect other monitors to your device.
- New! Adds weather content to the left side of the taskbar if the taskbar is aligned in the center. When you hover over the weather, the Widgets panel will appear on the left side of the screen and will disappear when you stop hovering over the area.
- New! Adds the ability to quickly share open application windows directly from your taskbar to a Microsoft Teams call.
- New! Adds support for hot adding and the removal of non-volatile memory (NVMe) namespaces.
- New! Adds the ability to instantly mute and unmute a Microsoft Teams call from your taskbar. During a call, an active microphone icon will appear on the taskbar so that you can easily mute the audio without having to return to the Microsoft Teams call window.
- Addresses an issue that occurs when Windows Server 2016 runs as a terminal server using certain cloud computing virtual desktop infrastructure (VDI). As result, the servers randomly stop responding after running for a period of time. This also addresses a regression that proactively checks to ensure that the CSharedLock in rpcss.exe is set correctly to avoid a deadlock.
- Addresses an issue that might cause the time zone list in Settings to appear blank for users who are not administrators.
- Addresses an issue that affects the Windows search service and occurs when you query using the proximity operator.
- Addresses an issue that fails to show the Startup impact values in Task Manager.
- prevents printing from operating properly for some low integrity process apps.
- Introduces support for Windows Hello for Business Cloud Trust. This is a new deployment model for hybrid deployments of Windows Hello for Business. It uses the same technology and deployment steps that support on-premises single sign-on (SSO) for Fast IDentity Online (FIDO) security keys. Cloud Trust removes the public-key infrastructure (PKI) requirements for deploying Windows and simplifies the Windows Hello for Business deployment experience.
- Addresses an issue that prevents you from unloading and reloading drivers when the drivers are protected Hypervisor-protected Code Integrity (HVCI).
- Addresses an issue that affects the Silent BitLocker enablement policy and might unintentionally add a Trusted Platform Module (TPM) protector.
- Addresses a reliability issue that affects the use of the Remote Desktop app to mount a client’s local drive to a terminal server session.
- Addresses an issue that displays right-to-left (RTL) language text as left justified on File Explorer command menus and context menus.
- Addresses an issue that prevents you from reaching the LanguagePackManagement configuration service provider (CSP) using the Windows Management Instrumentation (WMI) Bridge.
- Addresses an issue that causes a mismatch between a Remote Desktop session’s keyboard and the Remote Desktop Protocol (RDP) client when signing in.
- Addresses an issue that causes incorrect tooltips to appear in an empty area on the taskbar after you hover over other icons like battery, volume, or Wi-Fi.
- Addresses.
- Addresses an issue that disconnects Offline Files on the network drive after you restart the OS and sign in. This issue occurs if the Distributed File System (DFS) path is mapped to the network drive.
- Addresses an issue that displays the authentication dialog twice when you mount a network drive.
We have already covered some of the issues that users have experienced after installing KB5010414, but it’s worth drawing attention to the single known issue that Microsoft currently acknowledges:
Recent emails might not appear in the search results of the Microsoft Outlook desktop app. This issue is related to emails that have been stored locally in a PST or OST files. It might affect POP and IMAP accounts, as well as accounts hosted on Microsoft Exchange and Microsoft 365. If the default search in the Microsoft Outlook app is set to server search, the issue will only affect the advanced search.
The company offers up the following advice:
To mitigate the issue, you can disable Windows Desktop Search, which will cause Microsoft Outlook to use its built-in search. For instructions, see Outlook Search not showing recent emails after Windows update KB5008212.
We are working on a resolution and will provide an update in an upcoming release.
To see what you think of KB5010414, you can manually check for updates for Windows 11 and grab this cumulative update right away.
Image credit: IB Photography / Shutterstock | https://websetnet.net/kb5010414-update-for-windows-11-fixes-loads-of-problems-as-well-as-adding-new-features/ | CC-MAIN-2022-33 | refinedweb | 966 | 51.89 |
Upgrading to prompt_toolkit 2.0¶
Prompt_toolkit 2.0 is not compatible with 1.0, however you probably want to upgrade your applications. This page explains why we have these differences and how to upgrade.
If you experience some difficulties or you feel that some information is missing from this page, don’t hesitate to open a GitHub issue for help.
Why all these breaking changes?¶
After more and more custom prompt_toolkit applications were developed, it became clear that prompt_toolkit 1.0 was not flexible enough for certain use cases. Mostly, the development of full screen applications was not really natural. All the important components, like the rendering, key bindings, input and output handling were present, but the API was in the first place designed for simple command line prompts. This was mostly notably in the following two places:
First, there was the focus which was always pointing to a
Buffer(or text input widget), but in full screen applications there are other widgets, like menus and buttons which can be focused.
And secondly, it was impossible to make reusable UI components. All the key bindings for the entire applications were stored together in one
KeyBindingsobject, and similar, all
Bufferobjects were stored together in one dictionary. This didn’t work well. You want reusable components to define their own key bindings and everything. It’s the idea of encapsulation.
For simple prompts, the changes wouldn’t be that invasive, but given that there would be some, I took the opportunity to fix a couple of other things. For instance:
In prompt_toolkit 1.0, we translated \r into \n during the input processing. This was not a good idea, because some people wanted to handle these keys individually. This makes sense if you keep in mind that they correspond to Control-M and Control-J. However, we couldn’t fix this without breaking everyone’s enter key, which happens to be the most important key in prompts.
Given that we were going to break compatibility anyway, we changed a couple of other important things that effect both simple prompt applications and full screen applications. These are the most important:
We no longer depend on Pygments for styling. While we like Pygments, it was not flexible enough to provide all the styling options that we need, and the Pygments tokens were not ideal for styling anything besides tokenized text.
Instead we created something similar to CSS. All UI components can attach classnames to themselves, as well as define an inline style. The final style is then computed by combining the inline styles, the classnames and the style sheet.
There are still adaptors available for using Pygments lexers as well as for Pygments styles.
The way that key bindings were defined was too complex.
KeyBindingsManagerwas too complex and no longer exists. Every set of key bindings is now a
KeyBindingsobject and multiple of these can be merged together at any time. The runtime performance remains the same, but it’s now easier for users.
The separation between the
CommandLineInterfaceand
Applicationclass was confusing and in the end, didn’t really had an advantage. These two are now merged together in one
Applicationclass.
We no longer pass around the active
CommandLineInterface. This was one of the most annoying things. Key bindings need it in order to change anything and filters need it in order to evaluate their state. It was pretty annoying, especially because there was usually only one application active at a time. So,
Applicationbecame a
TaskLocal. That is like a global variable, but scoped in the current coroutine or context. The way this works is still not 100% correct, but good enough for the projects that need it (like Pymux), and hopefully Python will get support for this in the future thanks to PEP521, PEP550 or PEP555.
All of these changes have been tested for many months, and I can say with confidence that prompt_toolkit 2.0 is a better prompt_toolkit.
Some new features¶
Apart from the breaking changes above, there are also some exciting new features.
We now support vt100 escape codes for Windows consoles on Windows 10. This means much faster rendering, and full color support.
We have a concept of formatted text. This is an object that evaluates to styled text. Every input that expects some text, like the message in a prompt, or the text in a toolbar, can take any kind of formatted text as input. This means you can pass in a plain string, but also a list of (style, text) tuples (similar to a Pygments tokenized string), or an
HTMLobject. This simplifies many APIs.
New utilities were added. We now have function for printing formatted text and an experimental module for displaying progress bars.
Autocompletion, input validation, and auto suggestion can now either be asynchronous or synchronous. By default they are synchronous, but by wrapping them in
ThreadedCompleter,
ThreadedValidatoror
ThreadedAutoSuggest, they will become asynchronous by running in a background thread.
Further, if the autocompletion code runs in a background thread, we will show the completions as soon as they arrive. This means that the autocompletion algorithm could for instance first yield the most trivial completions and then take time to produce the completions that take more time.
Upgrading¶
More guidelines on how to upgrade will follow.
AbortAction has been removed¶
Prompt_toolkit 1.0 had an argument
abort_action for both the
Application class as well as for the
prompt function. This has been
removed. The recommended way to handle this now is by capturing
KeyboardInterrupt and
EOFError manually.
Calling create_eventloop usually not required anymore¶
Prompt_toolkit 2.0 will automatically create the appropriate event loop when
it’s needed for the first time. There is no need to create one and pass it
around. If you want to run an application on top of asyncio (without using an
executor), it still needs to be activated by calling
use_asyncio_event_loop() at the beginning.
Pygments styles and tokens¶
prompt_toolkit 2.0 no longer depends on Pygments, but that definitely doesn’t mean that you can’t use any Pygments functionality anymore. The only difference is that Pygments stuff needs to be wrapped in an adaptor to make it compatible with the native prompt_toolkit objects.
For instance, if you have a list of
(pygments.Token, text)tuples for formatting, then this needs to be wrapped in a
PygmentsTokensobject. This is an adaptor that turns it into prompt_toolkit “formatted text”. Feel free to keep using this.
Pygments lexers need to be wrapped in a
PygmentsLexer. This will convert the list of Pygments tokens into prompt_toolkit formatted text.
If you have a Pygments style, then this needs to be converted as well. A Pygments style class can be converted in a prompt_toolkit
Stylewith the
style_from_pygments_cls()function (which used to be called
style_from_pygments). A Pygments style dictionary can be converted using
style_from_pygments_dict().
Multiple styles can be merged together using
merge_styles().
Wordcompleter¶
WordCompleter was moved from
prompt_toolkit.contrib.completers.base.WordCompleter to
prompt_toolkit.completion.word_completer.WordCompleter.
Asynchronous autocompletion¶
By default, prompt_toolkit 2.0 completion is now synchronous. If you still want
asynchronous auto completion (which is often good thing), then you have to wrap
the completer in a
ThreadedCompleter.
Filters¶
We don’t distiguish anymore between CLIFilter and SimpleFilter, because the application object is no longer passed around. This means that all filters are a Filter from now on.
All filters have been turned into functions. For instance, IsDone became is_done and HasCompletions became has_completions.
This was done because almost all classes were called without any arguments in the __init__ causing additional braces everywhere. This means that HasCompletions() has to be replaced by has_completions (without parenthesis).
The few filters that took arguments as input, became functions, but still have to be called with the given arguments.
For new filters, it is recommended to use the @Condition decorator, rather then inheriting from Filter. For instance:
from prompt_toolkit.filters import Condition @Condition def my_filter(); return True # Or False | https://python-prompt-toolkit.readthedocs.io/en/stable/pages/upgrading/2.0.html | CC-MAIN-2022-33 | refinedweb | 1,319 | 57.87 |
Hello Sorry if this is confusing I'm really new to python and have been stuck trying to figure this out for hours now.
I'm trying to write a function for a text based battlship game. I need the function to do this is_occupied:
(int, int, int, int, list of list of strs) -> bool
The first to int's are suppose to refer to indices in the list of list of strings, same with the second 2 int's. The idea is to check the indices from range 1st set to 2nd set including themselves for a specific string element.
This is what I have so far the quoted out part was a different approach I took however so far both approaches have been unsuccessful.
def is_occupied(row1, col1, row2, col2, board): #row_1_col1 = board[row1],[col1] #row_2_col2 = board[row2],[col2] board = board r1 =[row1],[col1] r2 =[row2],[col2] if r1 >= r2: return True else: #if row_1_col1 >= row_2_col2: #return True #else: #for item in range(row_1_col1,row_2_col2): #if item != (VACANT): #return True #else: #return False for col in range(board(r1,r2)): for item in col: if not item == (VACANT): return True else: return False
Any help would be greatly appreciated I have also made some attemps to use multiple nested loops however I haven't got anything to work yet. | https://www.daniweb.com/programming/software-development/threads/415993/i-m-new-to-python-trying-to-write-battle-ship-function-i-m-stuck | CC-MAIN-2022-21 | refinedweb | 221 | 58.86 |
Choosing between numerous options for styling your app could be a project in and of itself. 🤯
I've tried several styling solutions and approaches on frontend like:
- Vanilla CSS
- CSS extensions like Sass or Less
- CSS modules (and Sass)
Projects which used them were written either with Vanilla JS or with some modern JavaScript frameworks like AngularJS, Angular 4, React ⚛️ or even React Native.
After all I have a huge favourite regarding styling options world which is not mentioned above. I would vote for it on new project anytime (sorry, there are local elections 🗳️ soon here in Croatia).
To finally get closer to the point, I like to write my styles just as rest of the app. In JavaScript. Which means I use the same programming language and the same syntax both for logic and for styles. This is really cool, but it's not the main motive behind it. It's because I find JavaScript much more powerful 💪 and capable than CSS.
JavaScript brings more of the engineering flavour into the app styling process. And it's possible with CSS-in-JS solutions, or shorter JSS.
I used JSS for the first time while I was working on projects built with Material UI. In their docs, you can find out why they use such approach after abandoning Less and custom solution inline-styles. Actually they did some pretty interesting comparison 📊 when choosing styling solution.
I've mentioned engineering flavour so let's show some examples of what I thought.
Variables
You can simply keep any style in a variable.
const COLOR_PRIMARY = "black"; const COLOR_SECONDARY = "#f0f0f0";
Also group them into a JS object.
baseTitle: { fontSize: 24, fontWeight: 600, color: COLOR_PRIMARY }
You could think now: nothing special, I can do that with extended CSS too. Be patient... 😃
Spreading, default properties and overriding
Let's say we want to extend this basic title for some other use.
sectionTitle: { ...baseTitle, //override font weight from base title fontWeight: 800, //extend base title fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif', fontStyle: 'italic', }
Notice that you don't need to learn any new syntax, you actually write CSS but you just use
camelCaseinstead of the
kebab-case:
font-size➡️
fontSize. And have JS power on top of it.
Themes
Then, you could also keep all your reusable styles in one place and build your whole theme - which is simply JS object.
const theme = { backgroundColor: COLOR_PRIMARY, color: COLOR_SECONDARY, ... };
That theme could be considered a config file but for styles 💅. Use Material UI theme for inspiration. From breakpoints, typography to colour palette and spacings.
Integrate JSS with React
There is a JSS Core library which can be used in any Javascript app, but React developers will be more interested in React-JSS.
Dynamic Values
Give attention to Dynamic values .
JSS uses Hooks API where you can use hooks like
createUseStyles.
There is a cool example I will borrow from JSS docs about how to start with it. I will just separate a style from components, because it is always a good practice not to make a big clutter in one file. Also, it reminds of the CSS modules approach which have a separate isolated style for each component.
useButtonStyles.js
import { createUseStyles } from 'react-jss' export const useButtonStyles = createUseStyles({ myButton: { padding: props => props.spacing }, myLabel: props => ({ display: 'block', color: props.labelColor, fontWeight: props.fontWeight, fontStyle: props.fontStyle }) })
Notice how elegantly you can change the style depending on props values passed from the component.
index.js
import React from 'react' import { useButtonStyles } from "./useButtonStyles"; const Button = ({children, ...props}) => { const classes = useButtonStyles(props) return ( <button className={classes.myButton}> <span className={classes.myLabel}>{children}</span> </button> ) } Button.defaultProps = { spacing: 10, fontWeight: 'bold', labelColor: 'red' } const App = () => <Button fontStyle="italic">Submit</Button>
Feel free to play with example on CodeSandbox.
Theming
Besides hook for creating style there is the
useTheme combined with a
ThemeProvider wrapper. It also provides a theming solution which makes it a lot easier to start writing themed apps with reusable styles, and to quick start your new project.
Would you give it a try?
❓ What are you thoughts?
❓ Which styling solution do you prefer?
❓ How do you deal with theming and reusable styles?
Discussion (7)
I would prefer my CSS to work when Javascript is disabled
@khoa0319 JSS compiles to CSS so no worries about that :)
There are examples like this demonstrating it: cssinjs.org/react-jss?v=v10.6.0#basic
😂
you won't fix css. you won't fix it by attempting to fix it on its own and you won't fix it by attempting to fix it as a part of a larger whole. it isn't broken. your approach makes sense to you and people like you, meaning the backend kind of people, the programmer, the engineer. i think it's horrible. all js frameworks make a mess of html, css and a11y and they fix very little if anything. all the old problems are still there.
one huge issue is the fact that you have welded your css into this project. therefor it isn't really reusable outside other react projects. keep it simple. css has to be a completely separate thing, in its own folder and framework agnostic. you just pop it into the project, import and use.
Hi @ronca85 , thank you for your comment!
Each tool has its usage and cases where it is great and helpful and on the opposite side where it is overkill or some kind of burden instead. JSS is not an exception. :)
For some smaller sites and projects there wouldn't be a lot of benefits of using JSS and maybe even React, so of course it can be built with good old CSS.
But if you are building some bigger enterprise application, or if you need to build some kind of design system or component library which can be reused across projects and apps, I like it how React with JSS solves this requirement for me. Because I can organise styles systematically, keep them consistent and manageable at one place (in theme).
I never had a need for reusing just a style (implemented in css, jss or any other technology), but always some piece of UI, or to be more precise some component. So I find it natural that style is tied to some html element or more complex React component.
Keep in mind this is my experience cause I'm oriented on products and applications where a lot of attention should be given also how app is built and how maintainable it is. If I would be building sites or some presentational web elements, I would have some different mindset.
Do you have some examples of reusing css across projects? How do you keep styles framework agnostic and just import and use them. It's always cool to see other approaches! :) Cheers!
I like it hook but its the same that styled-components or emotion.
Your Article was great.
Follow my YouTube Channel for amazing Web Development Tutorials.
youtube.com/channel/UCDT8sIFy3pW8L... | https://practicaldev-herokuapp-com.global.ssl.fastly.net/bornfightcompany/style-your-frontend-with-a-engineering-flavour-by-using-jss-4h06 | CC-MAIN-2021-25 | refinedweb | 1,168 | 65.22 |
Definitions of macros used in FEM code. More...
#include <fstream>
#include "itkFEMObjectFactory.h"
Go to the source code of this file.
Definitions of macros used in FEM code.
itkFEMMacro.h defines macros that allow simple and consistent FEM code creation. Use these macros whenever posible (always)!
Definition in file itkFEMMacro.h.
If defined, FEM classes will use smart pointers.
Define this macro if you want to compile the FEM classes so that they use itk's SmartPointer object instead of standard c++ pointers. If defined, FEM classes will include routines for drawing on the device context.
Define this macro if you want to compile the FEM Element and Node classes so that they include Draw() virtual member function. Calling this function draws the element or node on the specified windows device context.
Defines typedefs for pointers to class. 97 of file itkFEMMacro.h.
Defines typedefs for pointers to class. 145 248 of file itkFEMMacro.h.
Register the specified class with FEMObjectFactory. 207 of file itkFEMMacro.h. | http://www.orfeo-toolbox.org/Doxygen/itkFEMMacro_8h.html | CC-MAIN-2013-48 | refinedweb | 166 | 62.54 |
Unofficial WAD3 File Spec
Table of content
Introduction
The following file specification concerns the WAD3 file format used Valve's famous GoldSrc Engine. The file extension is ".wad". Contrary to the BSP v30 file format that has been derived from the Quake 1 BSP (v29) format, the WAD3 format is tecnically fully compatible with Quake's WAD2 files. WAD files are used to store game related files in some kind of archive. Somehow they seem to contain only textures, although they are capable of holding different kinds of data.
This file spec uses constructs from the C programming language to describe the different data structures used in the WAD file format. Architecture dependent datatypes like integers are replaced by exact-width integer types of the C99 standard in the stdint.h header file, to provide more flexibillity when using x64 platforms. Basic knowledge about textures in the BSP file is recommended.
#include <stdint.h>
Header
Like almost every file also a WAD file (WAD3) starts with a specific file header which is constucted as follows:
typedef struct _WADHEADER
{
char szMagic[4]; // should be WAD2/WAD3
int32_t nDir; // number of directory entries
int32_t nDirOffset; // offset into directory
} WADHEADER;
The first 4 bytes of a WAD archive identify the file (the so-called magic number) with the 3 character string "WAD" followed by a version numer as ASCII char. Compatible formats include "WAD3" as well as "WAD2". As with the BSP file also a WAD file starts with some kind of directory containing entries similar to the lumps of the BSP file. The major difference is that a WAD file may have an arbitrary number of entries. This value is stored in the nDir member of the header followed by the offset to the array of directory entries within the file, which is usually located somewhere at the ned of the WAD file.
Directory entries
The directory of a WAD file is basically an array of structures. Every archived file has an associated entry in this directory:
#define MAXTEXTURENAME 16
typedef struct _WADDIRENTRY
{
int32_t nFilePos; // offset in WAD
int32_t nDiskSize; // size in file
int32_t nSize; // uncompressed size
int8_t nType; // type of entry
bool bCompression; // 0 if none
int16_t nDummy; // not used
char szName[MAXTEXTURENAME]; // must be null terminated
} WADDIRENTRY;
The first value is the offset of the raw data of the archived file within the WAD file followed by the size of data used by the it in its current form. Additionally nSize stores the size of original file, if it has been compressed. This is indicated by the bCompression boolean value. If it is false, no compression is used which is mostly the case. The nType member would give as information about the type of file, that is associated with this entry. As WAD files usually contain only textures, this information may be ignored. The nDummy short integer is not used when loading textures and i have not found any information about this member. Finally the entry contains a name for the file which can be a string of maximum 16 chars including the zero termination. In case of textures, this is the name referred by the BSPMIPTEX structs of the BSP file.
Files in a WAD File - Textures
The actual files in the WAD archive, the textures, also start with a file header which may look familiar:
;
This struct equals the one of the BSP file exactly. The name of the texture as not needed actually, as it equals the file name in the directory entry. The next members are of particular interest. They give the size of the texture in pixel as well as the offsets into the raw texture data. The first value of the offset array points to the beginning of the original texture relativly to the local header (the BSPMIPTEX struct). From this point follows a nWidth * nHeight bytes long array of indexes (0-255) pointing to colors in a color table. The other three offsets are used the same way, but with the diference that the width and height of the image are cut in half with every further offset. These represent the so-called mipmap levels of the original image. After the last byte of the fourth mipmap there are two dummy bytes followed by the actual color table consisting of an array of triples of bytes (RGB values) with 256 elements. The indexes of the image are plugged into the color table array to receive the corresponding RGB color value for the pixel. | http://hlbsp.sourceforge.net/index.php?content=waddef | CC-MAIN-2018-22 | refinedweb | 750 | 57.91 |
Introduction: A-Z Guide to Interfacing TFT LCD Displays W/ Arduino
In this article, you will learn how to use TFT LCDs by Arduino boards. From basic commands to professional designs and technics are all explained here. At the end of this article, you can :
- Write texts and numbers with your desired font.
- Draw shapes like circle, triangle, square, etc.
- Display.bmp images on the screen.Change screen parameters such as rotating and inverting color.
- Display an animation by Arduino.
Teacher Notes
Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.
Step 1: Things Used in This Project
Hardware components
ElectroPeak 3.5 inch TFT Color Display Screen Module X1
ElectroPeak 2.4 inch TFT LCD Display Shield X1
Arduino UNO & Genuino UNO X1
Arduino DUE X1
Software apps and online services
Step 2: Presenting Ideas on Displays
In electronic’s projects, creating an interface between user and system is very important. This interface could be created by displaying useful data, a menu, and ease of access. A beautiful design is also very important.
There are several components to achieve this. LEDs, 7-segments, Character and Graphic displays, and full-color TFT LCDs. The right component for your projects depends on the amount of data to be displayed, type of user interaction, and processor capacity. TFT LCD is a variant of a liquid-crystal display (LCD) that uses thin-film-transistor (TFT) technology to improve image qualities such as addressability and contrast. A TFT LCD is an active matrix LCD, in contrast to passive matrix LCDs or simple, direct-driven LCDs with a few segments. In Arduino-based projects, the processor frequency is low. So it is not possible to display complex, high definition images and high-speed motions. Therefore, full-color TFT LCDs can only be used to display simple data and commands. In this article, we have used libraries and advanced technics to display data, charts, menu, etc. with a professional design. This can move your project presentation to a higher level.
Step 3: Which Size? Which Controller?
Size of displays affects your project parameters. Bigger Display is not always better. if you want to display high-resolution images and signs, you should choose a big size display with higher resolution. But it decreases the speed of your processing, needs more space and also needs more current to run.
So, First, you should check the resolution, speed of motion, details of color and size of your project’s images, texts, and numbers. We suggest popular size of Arduino displays such as 3.5 inch 480×320, 2.8 inch 400×240, 2.4 inch 320×240 and 1.8 inch 220×176. After choosing the right display, It’s time to choose the right controller. If you want to display characters, tests, numbers and static images and the speed of display is not important, the Atmega328 Arduino boards (such as Arduino UNO) are a proper choice. If the size of your code is big, The UNO board may not be enough. You can use Arduino Mega2560 instead. And if you want to show high resolution images and motions with high speed, you should use the ARM core Arduino boards such as Arduino DUE.
Step 4: Drivers & Libraries
In electronics/computer hardware a display driver is usually a semiconductor integrated circuit (but may alternatively comprise a state machine made of discrete logic and other components) which provides an interface function between a microprocessor, microcontroller, ASIC or general-purpose peripheral interface and a particular type of display device, e.g. LCD, LED, OLED, ePaper, CRT, Vacuum fluorescent or Nixie.
The display driver will typically accept commands and data using an industry-standard general-purpose serial or parallel interface, such as TTL, CMOS, RS232, SPI, I2C, etc. and generate signals with suitable voltage, current, timing and demultiplexing to make the display show the desired text or image. The LCDs manufacturers use different drivers in their products. Some of them are more popular and some of them are very unknown. To run your display easily, you should use Arduino LCDs libraries and add them to your code. Otherwise running the display may be very difficult. There are many free libraries you can find on the internet but the important point about the libraries is their compatibility with the LCD’s driver. The driver of your LCD must be known by your library. In this article, we use the Adafruit GFX library and MCUFRIEND KBV library and example codes. You can download them from the following links. Unzip the MCUFRIEND KBV and open the MCUFRIEND_kbv.CPP. You can see the list of drivers that are supported by MCUFRIEND library.
Open Example folder. There are several example codes that you can run by Arduino. Hook up the LCD and test some of the examples.
Step 5: Code. Now click add ZIP library and add the libraries
- Choose the board in tools and boards, select your Arduino Board.
- Connect the Arduino to your PC and set the COM port in tools and port.
- Press the Upload (Arrow sign) button.
- You are all set!
After uploading an example code, it’s time to learn how to create your images on the LCD.
Open a new Sketch, and the necessary codes as described in the following sections.
Step 6: Library
#include "Adafruit_GFX.h"
#include "MCUFRIEND_kbv.h"
The first line adds core graphics library for displays (written by Adafruit).
The second adds a library that supports drivers of MCUFRIEND Arduino display shields.
.
#include "TouchScreen.h" // only when you want to use touch screen
#include "bitmap_mono.h" // when you want to display a bitmap image from library
#include "bitmap_RGB.h" // when you want to display a bitmap image from library
#include "Fonts/FreeSans9pt7b.h" // when you want other fonts
#include "Fonts/FreeSans12pt7b.h" // when you want other fonts
#include "Fonts/FreeSerif12pt7b.h" // when you want other fonts
#include "FreeDefaultFonts.h" // when you want other fonts
#include "SPI.h" // using sdcard for display bitmap image
#include "SD.h"
These libraries are not necessary for now, but you can add them.
Step 7: Basic Commands
Class & Object
//(int CS=A3, int RS=A2, int WR=A1, int RD=A0, int RST=A4)
MCUFRIEND_kbv tft(A3, A2, A1, A0, A4);
This line makes an object named TFT from MCUFRIEND_kbv class and provides an SPI communication between LCD and Arduino.
.
Running the LCD
uint16_t ID = tft.readID();
tft.begin(ID);
The tft.readID function reads ID from the display and put it in ID variable. Then tft.begin function gets ID and the LCD gets ready to work.
.
Resolution of the Display
tft.width(); //int16_t width(void);
tft.height(); //int16_t height(void);
By these two functions, You can find out the resolution of the display. Just add them to the code and put the outputs in a uint16_t variable. Then read it from the Serial port by Serial.println();. First add Serial.begin(9600); in setup().
.
Color of the Screen
tft.fillScreen(t); //fillScreen(uint16_t t);
fillScreen function change the color of screen to t color. The t should be a 16bit variable containing UTFT color code.
#define BLACK 0x0000
#define NAVY 0x000F
#define DARKGREEN 0x03E0
#define DARKCYAN 0x03EF
#define MAROON 0x7800
#define PURPLE 0x780F
#define OLIVE 0x7BE0
#define LIGHTGREY 0xC618
#define DARKGREY 0x7BEF
#define BLUE 0x001F
#define GREEN 0x07E0
#define CYAN 0x07FF
#define RED 0xF800
#define MAGENTA 0xF81F
#define YELLOW 0xFFE0
#define WHITE 0xFFFF
#define ORANGE 0xFD20
#define GREENYELLOW 0xAFE5
#define PINK 0xF81F
You can add these lines to the top of your code and just use the name of the color in the functions.
.
Filling Pixels
tft.drawPixel(x,y,t); //drawPixel(int16_t x, int16_t y, uint16_t t)
tft.readPixel(x,y); //uint16_t readPixel(int16_t x, int16_t y)
drawPixel function fills a pixel in x and y location by t color.
readPixel function read the color of a pixel in x and y location.
.
Rotating the Screen
tft.setRotation(r); //setRotation(uint8_t r)
This code rotates the screen. 0=0, 1=90, 2=180, 3=270.
.
Inverting Screen Colors
tft.invertDisplay(i); //invertDisplay(boolean i)
This code inverts the colors of the screen.
tft.color565(r,g,b); //uint16_t color565(uint8_t r, uint8_t g, uint8_t b)
This code give RGB code and get UTFT color code.
.
Scrolling the Screen
for (uint16_t i = 0; i < maxscroll; i++) {
tft.vertScroll(0, maxscroll, i);
delay(10);}
This code Scroll your screen. The Maxroll is the maximum height of your scrolling.
.
Reset
tft.reset();
This code resets the screen.
Step 8: Drawing Lines
tft.drawFastVLine(x,y,h,t);
//drawFastVLine(int16_t x, int16_t y, int16_t h, uint16_t t)
tft.drawFastHLine(x,y,w,t);
//drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t t)
tft.drawLine(xi,yi,xj,yj,t);
//drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t t)
drawFastVLine function draws a vertical line that starts in x, y location, and its length is h pixel and its color is t.
drawFastHLine function draws a horizontal line that starts in x and y location and the length is w pixel and the color is t.
drawLine function draws a line that starts in xi and yi locationends is in xj and yj and the color is t.
.
for (uint16_t a=0; a<5; a++)
{ tft.drawFastVLine(x+a, y, h, t);}
for (uint16_t a=0; a<5; a++)
{ tft.drawFastHLine(x, y+a, w, t);}
for (uint16_t a=0; a<5; a++)
{ tft.drawLine(xi+a, yi, xj+a, yj, t);}
for (uint16_t a=0; a<5; a++)
{ tft.drawLine(xi, yi+a, xj, yj+a, t);}
These three blocks of code draw lines like the previous code with 5-pixel thickness.
.
tft.fillRect(x,y,w,h,t);
//fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t t)
tft.drawRect(x,y,w,h,t);
//drawRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t t)
tft.fillRoundRect(x,y,w,h,r,t);
//fillRoundRect (int16_t x, int16_t y, int16_t w, int16_t h, uint8_t R , uint16_t t)
tft.drawRoundRect(x,y,w,h,r,t);
//drawRoundRect(int16_t x, int16_t y, int16_t w, int16_t h, uint8_t R , uint16_t t)
fillRect function draws a filled rectangle in x and y location. w is width, h is height and t is color of the rextangle
drawRect function draws a rectangle in x and y location with w width and h height and t color.
fillRoundRect function draws a filled Rectangle with r radius round corners in x and y location and w width and h height and t color.
drawRoundRect function draws a Rectangle with r radius round corners in x and y location and w width and h height and t color.
Step 9: Drawing Circles
tft.drawCircle(x,y,r,t); //drawCircle(int16_t x, int16_t y, int16_t r, uint16_t t)
tft.fillCircle(x,y,r,t); //fillCircle(int16_t x, int16_t y, int16_t r, uint16_t t)
drawCircle function draws a circle in x and y location and r radius and t color.
fillCircle function draws a filled circle in x and y location and r radius and t color.
.
for (int p = 0; p < 4000; p++)
{
j = 120 * (sin(PI * p / 2000));
i = 120 * (cos(PI * p / 2000));
j2 = 60 * (sin(PI * p / 2000));
i2 = 60 * (cos(PI * p / 2000));
tft.drawLine(i2 + 160, j2 + 160, i + 160, j + 160, col[n]);
}
By this code, you can draw an Arc. change the “for” between 0 and 4000.
Step 10: Drawing Triangles
tft.drawTriangle(x1,y1,x2,y2,x3,y3,t);
//drawTriangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3,// uint16_t t)
tft.fillTriangle(x1,y1,x2,y2,x3,y3,t);
//fillTriangle(int16_t x1, int16_t y1, int16_t x2, int16_t y2, int16_t x3, int16_t y3,// uint16_t t)
drawTriangle function draws a triangle with three corner location x, y and z, and t color.
fillTriangle function draws a filled triangle with three corner location x, y and z, and t color.
Step 11: Displaying Text
tft.setCursor(x,y); //setCursor(int16_t x, int16_t y)
This code sets the cursor position to of x and y
.
tft.setTextColor(t); //setTextColor(uint16_t t)
tft.setTextColor(t,b); //setTextColor(uint16_t t, uint16_t b)
The first line sets the color of the text. Next line sets the color of text and its background.
.
tft.setTextSize(s); //setTextSize(uint8_t s)
This code sets the size of text by s. s is a number between 1 and 5.
.
tft.write(c); //write(uint8_t c)
This code displays a character.
tft.println("");
tft.print("");
The first function displays a string and moves the cursor to the next line.
The second function just displays the string.
.
showmsgXY(x,y,sz,&FreeSans9pt7b,"");
//void showmsgXY(int x, int y, int sz, const GFXfont *f, const char *msg)
void showmsgXY(int x, int y, int sz, const GFXfont *f, const char *msg)
{ uint16_t x1, y1;
uint16_t wid, ht;
tft.setFont(f);
tft.setCursor(x, y);
tft.setTextColor(0x0000);
tft.setTextSize(sz);
tft.print(msg);
}
This function changes the font of the text. You should add this function and font libraries.
.
for (int j = 0; j < 20; j++) {
tft.setCursor(145, 290);
int color = tft.color565(r -= 12, g -= 12, b -= 12);
tft.setTextColor(color);
tft.print("");
delay(30);
}
This function can fade your text. You should add it to your code.
Step 12: Displaying Images
Displaying Monochrome Images
static const uint8_t name[] PROGMEM =
{ //Add image code here. }
tft.drawBitmap(x, y, name, sx, sy, 0x0000);
First you should convert your image to hex code. Download the software from the following link. if you don’t want to change the settings of the software, you must invert the color of the image and make the image horizontally mirrored and rotate it 90 degrees counterclockwise. Now add it to the software and convert it. Open the exported file and copy the hex code to Arduino IDE. x and y are locations of the image. sx and sy are sizes of image. you can change the color of the image in the last input.
.
RGB Color Image Displaying
const uint16_t name[] PROGMEM = {
//Add image code here. }
tft.drawRGBBitmap(x, y, name, sx, sy);
First, you should convert your image to code.Use this link to convert the image:...
Upload your image and download the converted file that the UTFT libraries can process. Now copy the hex code to Arduino IDE. x and y are locations of the image. sx and sy are size of the image.
Step 13: Predesigned Templates - Loading
In this template, We just used a string and 8 filled circles that change their colors in order. To draw circles around a static point, You can use sin(); and cos(); functions. you should define the PI number. To change colors, you can use color565(); function and replace your RGB code.
Attachments
Step 14: Logo Presentation
In this template, We converted a.jpg image to.c file and added to the code, wrote a string and used the fade code to display. Then we used scroll code to move the screen left. Download the.h file and add it to the folder of the Arduino sketch.
Attachments
Step 15: Charts
In this template, We used draw lines, filled circles, and string display functions.
You can find more chart templates here .
Attachments
Step 16: Music and Other Templates
In this template, We added a converted image to code and then used two black and white arcs to create the pointer of volumes. Download the .h file and add it to the folder of the Arduino sketch.
You can find more animated templates (Like the following GIFs) by clicking on this link
Step 17: Screen Saver
In this template, We just display some images by RGB bitmap and bitmap functions. Just make a code for touchscreen and use this template. Download the.h file and add it to the folder of the Arduino sketch.
Attachments
Step 18: Final Remarks
- The speed of playing all the GIF files are edited and we made them faster or slower for better understanding. The speed of motions depends on the speed of your processor or type of code or size and thickness of elements in the code.
- You can add the image code in the main page but it fills all the main page. So you can make a.h file and add in the folder of the sketch.
- In this article, We just discussed about displaying elements on LCD. Follow our next tutorials to learn using touch screens and SD Cards.
- If you have the problem with including the Libraries, change the "" sign to <>.
× SPECIAL OFFER (VALID UNTIL NOVEMBER 1ST 2018): If you order the 3.5″ LCD from ElectroPeak, our technical staff will design your desired template for free! Just send an email to info@electropeak.Com containing your order number and requirements ;)
.
You can also read this project on ElectroPeak's official website....
Participated in the
Make it Glow Contest 2018
Be the First to Share
Recommendations
6 Discussions
6 months ago
Trying to track down what pin definitions they used for the tft, what file are they in?
1 year ago
i cant upload it to a micro sd right? thats only for bmp or am i wrong
Reply 1 year ago
yes you are right. SD is for images only
1 year ago
the code is way to large to upload whta do i do?
Reply 1 year ago
you have to change your micro controller with larger flash.
Reply 1 year ago
Which Arduino do you use? For larger codes, you need Arduino Mega or Due | https://www.instructables.com/id/Absolute-Beginners-Guide-to-TFT-LCD-Displays-by-Ar/ | CC-MAIN-2020-24 | refinedweb | 2,945 | 66.94 |
Opened 8 years ago
Closed 8 years ago
Last modified 7 years ago
#9402 closed (duplicate)
Whitespace validates in any field that is required
Description
How to reproduce:
Create a form with a CharField that has required=True .
Put whitespace into the field ( for example 4 spaces ).
Submit the form. It will validate as is_valid().
The problem lies in fields.py at line 111 ( django trunk ):
def clean(self, value): """ Validates the given value and returns its "cleaned" value as an appropriate Python object. Raises ValidationError for any errors. """ if self.required and value in EMPTY_VALUES: raise ValidationError(self.error_messages['required']) return value
At line 46 is the following:
# These values, if given to to_python(), will trigger the self.required check. EMPTY_VALUES = (None, '')
Problem is that any amount of whitespace will get through this check. I don't know how you guys think about this ( I mean, whitespace is data ;-) ), but filling in whitespace has pretty much the same effect as filling in nothing.
Proposed fix:
if self.required and value.rstrip() in EMPTY_VALUES:
I know I should do this with a patch etc. but I don't know how to do this. I hope this is sufficient.
Thanks in advance,
Hdevries.
Change History (3)
comment:1 Changed 8 years ago by hdevries
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
comment:2 Changed 8 years ago by brosner
- Resolution set to duplicate
- Status changed from new to closed
comment:3 Changed 7 years ago by anonymous
- milestone post-1.0 deleted
Milestone post-1.0 deleted
if value is None .rstrip() will raise an Error. I'm not an experienced Python programmer, so my bad for that ;-). | https://code.djangoproject.com/ticket/9402 | CC-MAIN-2016-26 | refinedweb | 280 | 67.96 |
explanation
;
Hi,can I know what is the meaning for the above coding?I have find the explanation in internet,but not very clear about it. Thank you
explanation to your code - Java Beginners
explanation to your code sir,
I am very happy that you have...)?And i have imported many classes.but in your code you imported a very few classes.sir i need your brief explanation on this code and also your guidance
What would you rate as your greatest weaknesses?
must say that I am not a very aggressive person, although I know I can quietly... with the interviewer.
4. Is there something you did- or didn’t do- that you are now... nice words or a pat on the back- whatever it is, I always work to clear up
JSP and Servlet did not run - JSP-Servlet
JSP and Servlet did not run I tried to run this program but when I clicked submit button it give me; HTTP Status 404- and did not give me display...
Thanks Hi,
Thanks for your reply - I noticed that you have changed
Submit Your Article
automatically publish your articles to our high traffic area for greatest
result. Now... I did it"
success stories, tips and hints, instructions, motivational... and over again? Well,
we've got good news. You can now submit your articles
Please Help Now
Please Help Now i want to put this map in ajax oriented codeigniter website
thanks in advance
plz help me now plz
very urgent
JSP Parse did not work - Java Server Faces Questions
JSP Parse did not work I have these codes..."
"Good"
"Very Good"
"Excellent"
DropDown.java:
import java.io....("Feedback");
out.print("Selected Values are: ");
for(int i=0;i
DropDown
DropDown
Deployment of your example - Struts
Deployment of your example In your Struts2 tutorial, can you show how you would war it up so it can be deployed into JBOss? There seems to be a lot of unnecessary files in it, or am I mistaken Dear Sir ,
I am very new in Struts and want to learn about validation and custom validation. U have given in a such nice way... validation and one of custom validation program, may be i can understand.Plz
I think you should be earning more money at this point of your career. Why isn?t it happening?
I think you should be earning more money at this point of your career. Why... of the work I have done so far. I have always enjoyed what I did. I feel it is somewhat...- it should also be clear that the reason is now in the past), I have always had
Help Very Very Urgent - JSP-Servlet
Help Very Very Urgent Respected Sir/Madam,
I am sorry..Actually the link u have sent was not my actual requirement..
So,I send my requirement... and Enter New Name..
Now what I require is: When I click or select any
Struts Tutorials
as popular as Struts. If you need to brush up your knowledge on JUnit I can recommend... types of cleanup you can do to improve your Struts configurations.
Prerequisites... and on top of Struts, is now an integral component of any professional Struts
Programming help Very Urgent - JSP-Servlet
..
Now what I require is: When I click or select any of the ID from Combo box,both...Programming help Very Urgent Respected Sir/Madam,
Actually my code... present in the database.. When I click or select any of the ID,it automatically
JSP,JDBC and HTML(Very Urgent) - JSP-Servlet
)Delete,3)Update and 4)Query with a submit button.
PROCESS:
Now when I click... also. Now for Query,When I click combo box and select an ID, it must come... exact requirement in which if I get an immediate help,I will be very much grateful
example explanation - Java Beginners
example explanation can i have some explanation regarding the program given as serialization xample.... Hi friend,
import java.io.*;
import java.util.*;
import java.util.Date;
import java.io.Serializable
Java Code Explanation
args[])
{
int n,i,res=0,sum=0,dif...(System.in);
n=in.nextInt();
for(i=1;i<=n;i++)
res=res+i;
res=res*res;
for(i=1;i<
Struts Alternative
Struts Alternative
Struts is very robust... article "Coding your second Jakarta Struts Application", and prepare... to your business objects. This is another major difference to Struts which is built
explanation - Java Beginners
explanation I have create small java appication. I don't know about garbage collection, memory leak. I want reference about these and how to use my java application. Hi Friend,
Please visit the following links
Developing Simple Struts Tiles Application
applications. Here are
the steps necessary for adding Tiles to your Struts...
the appropriate html and did the following things:
Referenced the /WEB-INF/struts...
Developing Simple Struts Tiles Application
Struts
Struts How Struts is useful in application development? Where to learn Struts?
Thanks
Hi,
Struts is very useful in writing web applications easily and quickly.
Developer can write very extensible and high
struts - Struts
struts I want to know clear steps explanation of struts flow..please explain the flow clearly
Designing your web sites
templates:
I should be very heavy
Design should be good... registering the domain your
next task is to design good web site for you. To
design your web site you should have some knowledge of HTML and designing tools
like
When you look back on the position you held last, do you think you have done your best in it?
;
If you say that you did, it could mean that your best is already... developments in your career.
62. Give me a reason why I should hire you when... for the department. I think I should make a good choice... (follow with your strongest
Get Noticed with Your Resume
/hobbies. Ideally your resume should not be longer than a page- two if you are very... that you mention what you did in your experience section. You need to show how...
Get Noticed with Your Resume
Struts Books
components
How to get started with Struts and build your own... to internationalize your Struts applications
Tips for managing errors...
Request Dispatcher. In fact, some Struts aficionados feel that I
huffman code give the explanation for this code
huffman code give the explanation for this code package bitcompress...) {
boolean s[] = huffcodes[value];
for (int i = 0; i < s.length; i++) {
if (!next_filter.receive_bit (s[i]))
return (false
SQL NOW() Function
SQL NOW() Function
NOW ( ) Function provides you the current date and time according to
your computer's system date and time.
The SQL syntax for the Now
help i want it now the answer pleas...
help i want it now the answer pleas... write a program that will display the exactly output as below:
Hints: declare and initialize value of array in double type.Read and write all elements of array.perform the multiply
You have been working with this current firm for a long time. Don?t you think it would be difficult now to switch over t
for the requirements of the job.
42. Can I contact your current employer... quality.
E.g. “Well I can’t really call it worry, but I am very... you think it would be difficult now to switch over to a new company
Ask Programming Questions and Discuss your Problems
manner. Now, User have to login for asking any query. Login is very simple. Just...
Ask Programming Questions and Discuss your Problems
Dear Users, Analyzing your plenty of problems
struts
struts <p>hi here is my code in struts i want to validate my form fields but it couldn't work can you fix what mistakes i have done</p>...
}//execute
}//class
struts-config.xml
<struts
Annotations are using now a days?
Annotations are using now a days? i have a doubt in Annatation, if we use Annatation we must hardcoding the code/data but sunmicrosystem itself says that hardcoding is not recommended
Struts Articles
it.
Struts is a very popular framework for Java Web applications... development speed and the quality of your applications.
Struts... previous Struts experience. I notice in many cases that some sort of ?paradigm
Struts - Struts
Struts Hello
I have 2 java pages and 2 jsp pages in struts... for getting registration successfully
Now I want that Success.jsp should display... with source code to solve the problem.
For read more information on Struts visit
hi... - Struts
also its very urgent Hi Soniya,
I am sending you a link. I hope that, your problem will be solved. Please visit for more information...hi... Hi Friends,
I am installed tomcat5.5 and open
SQL NOW() Function
SQL NOW() Function
NOW ( ) Function provides you the current date and time according to
your computer's system date and time.
The SQL
java.lang.ClassNotFoundException: - Struts
.
Thanks Thanks alot,I finally got it connected(MAVEN)
now no any page...java.lang.ClassNotFoundException: Hi,
I cant connect my eclipse(ganymede) to maven
Even I got some errors when launching my first application
Struts Frameworks
Struts Frameworks
Struts framework is very useful in the development of web...; Maintainability of any application is
very crucial in long run. So, all the business are now... highly maintainable web
based enterprise applications. Struts is also being
turorials for struts - Struts
turorials for struts hi
till now i dont about STRUTS. so want beginers struts tutorials notes. pls do
Textarea - Struts
Textarea Textarea Hi, this is ramprasad and i am using latest... characters.Can any one? Given examples of struts 2 will show how to validate... done run your application and it will validate your text area, which will not take
Struts Book - Popular Struts Books
very well. This is the first Struts book ever published and the one I bought when... to your own case. Struts is an open-source product distributed by the Apache... very dissapointed in this book, as I purchased it thinking it would give real
Developing Struts Application
. This is not JSTL
but Struts Tag Library. We should note the following very carefully...Developing Struts Application
If we are asked to give a very brief
Struts Guide
your favorite directory and copy struts-blank.war, struts-documentation.war...
Struts Guide
- This tutorial is extensive guide to the Struts Framework
BSNL Broadband users - save yourself!
; next ?> Finish
Now, turn on your modem wait until the LINK becomes a steady... below is for educational purpose only.
I amnot responsible for any misuse... facilities of upto 2 mpbs. But a large number of users
of this service
Your competitor presses you to reveal some confidential information about your current or previous employer.
Situation: Your competitor presses you to reveal some confidential information about your current or previous employer.
... reason could be that the company is testing your integrity- if someone could cajole
Very simple `Hello world' java program that prints HelloWorld
and run it. I am
assuming that latest version of JDK is installed on your machine... in the DOS/Windows world.
Execute the byte code
Now you can execute the byte
Struts - Jboss - I-Report - Struts
Struts - Jboss - I-Report Hi i am a beginner in Java programming and in my application i wanted to generate a report (based on database) using Struts, Jboss , I Report
Improve Your Assertiveness at Work
Improve Your Assertiveness at Work
... not work in team environments where interpersonal relationships are very important... earlier are clearly unhealthy. Now let us move on to define a set of healthy
Outsourcing Writing to India Is Easy Now
Outsourcing Writing to India Is Easy Now
Many people want to take outsourcing... with it. But now, no need to
worry! In the fast rising business in India... and make an informed choice before you decide to
outsource your writing work
Struts Interview Questions
;
Question: Can I setup Apache Struts to use
multiple... are the disadvantages of Struts?
Answer: Struts is very robust framework and is being... global exception
handling tags in your struts-config.xml or define the exception
Controlling your program
Controlling your program
... will be executed.
Now, to terminate a statement following a switch
statement use break... is and that too without
making any errors. Until now we have learnt how to use
Right Way of Planning Your Articles
brainstorming. You can then combine your ideas and
information for writing a nice...Right Way of Planning Your Articles
Article writing is a creative as well..., it is very important to plan out all the events that would take place Projects
learning easy
Using Spring framework in your application
Project in STRUTS...
In this tutorial I will show you how to integrate Struts and Hibernate... or the Struts ActionServlet. It is very fast and enables the user to manipulate
Interview Questions and Answers
when you failed in spite of your best efforts?
This is a very common situation..., as this project was strategically very important to them. I was asked to brief the top... about your goals- both short term and long term.
This is a very you-specific
Google maps GPS tracking
Now you can pinpoint your position with the aid of Google map
that is now... in use and is comes equipped in almost all cars and automobiles, has
now been...
GPS that can show your position. Simply turning on an option under the
"Tools
Integrate Struts, Hibernate and Spring
of your changes. This is repetitive
task in the programming, so its is very....
Your browser should show the default welcome page that comes with
struts...
Integrate Struts, Hibernate and Spring
Struts 2 Tutorial
Struts 2 Framework with examples. Struts 2 is very
elegant and flexible front... Beans, ResourceBundles, XML etc.
Struts 2
Training! Get Trained Now!!!
Struts 2 Features
It is very extensible as each class of the framework
Browser Back/Forward - Struts
Browser Back/Forward Hi,
Greetings to all.
I have developed a web application using Struts 2.
Now, i want to enable browser back/forward... your reply.
Thanks,
Paddy Hi friend,
For more information
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://www.roseindia.net/tutorialhelp/comment/2957 | CC-MAIN-2015-18 | refinedweb | 2,356 | 67.04 |
Getting the current Kotlin version is easy, but the actual
KotlinVersion class is much more interesting. This post shows how to get the Kotlin version programmatically, but then looks at the details of the
KotlinVersion class, including how it demonstrates a great way to write an
equals method and more.
Note that this demo is part of my new book, Kotlin Cookbook, from O’Reilly Media.
Also, I was lucky enough to be interviewed by Hadi Harriri on his Talking Kotlin podcast, and this class came up. That episode has not yet been released, but should be out soon depending on his current backlog.
To start, here is the trivial one-liner to find out which version of Kotlin is executing your code:
fun main() { println("The current Kotlin version is ${KotlinVersion.CURRENT}") }
At the time of this writing, the current release version of Kotlin is 1.3.50, and when you run this script on that version that’s what you get.
Where life gets interesting is when you look at how the
KotlinVersion class is implemented. The next series of snippets will examine that in some detail. The
KotlinVersion class in the standard library is in the
kotlin package, and begins:
public class KotlinVersion(val major: Int, val minor: Int, val patch: Int ) : Comparable<KotlinVersion> {
The class is marked
public, which isn’t necessary (
public is the default) but is typical of library classes. Then follows the primary constructor, which takes three integer values, labeled
major,
minor, and
patch. After the colon after the signature shows that the class implements the
Comparable interface for instances of itself, which is already pretty interesting. The
Comparable interface in Kotlin is just like its counterpart in Java. It establishes a “natural ordering” on instances of the class.
The
Comparable interface in the standard library consists of:
public interface Comparable<in T> { public operator fun compareTo(other: T): Int }
Again, the word
public is not necessary either on the class or the function, but doesn’t hurt anything. The
compareTo function is labeled an
operator function. In this case, the function is used whenever you use
<, >, ==, or one of the combination comparison functions,
<=, >=, or
!=. The function returns an integer whose value doesn’t matter, but should be negative, zero, or positive if the current object is less than, equal to, or greater than its argument.
Returning to the
KotlinVersion class, the implementation of
compareTo is:
override fun compareTo(other: KotlinVersion): Int = version - other.version
This assumes that the
KotlinVersion class has a
version property. The primary constructor didn’t show one, so the implementation provides a private property of that name and the function to compute it:
private val version = versionOf(major, minor, patch) private fun versionOf(major: Int, minor: Int, patch: Int): Int { require(major in 0..MAX_COMPONENT_VALUE && minor in 0..MAX_COMPONENT_VALUE && patch in 0..MAX_COMPONENT_VALUE) { "Version components are out of range: $major.$minor.$patch" } return major.shl(16) + minor.shl(8) + patch }
So the
version property is computed from the
major,
minor, and
patch values. The
require statement is a pre-condition that verifies the individual values fall within the required range. For all three, the minimum is zero and the maximum is
MAX_COMPONENT_VALUE. Like most constants,
MAX_COMPONENT_VALUE is found in the companion object:
companion object { public const val MAX_COMPONENT_VALUE = 255 @kotlin.jvm.JvmField public val CURRENT: KotlinVersion = KotlinVersion(1, 3, 50) }
Note the use of both
const and
val together. From a Java perspective, the properties inside the companion object are effectively static, and the
val keyword indicates they’re both
final as well. The
const modifier means the value is a compile-time constant, rather than being specified at runtime. The max value is therefore hard-wired to 255, and on this version of Kotlin the
CURRENT value is an instance of the
KotlinVersion class where
major,
minor, and
patch values are 1, 3, and 50, respectively.
That takes care of the
require block in the
versionOf function. What about the actual value it returns? That’s computed using the shift-left (or left-shift, but the other way reads better) operator function,
shl. That is an infix function that shifts the current value by the specified number of bits. Its signature is given by:
public final infix fun shl( bitCount: Int ): Int
This is an infix function, so the idiomatic way to invoke it would be
major shl 16,
minor shl 8, etc, but the form used here works anyway. Basically, the function shifts by two bytes for
major and one byte for
minor, which gives them enough of an offset that it is very unlikely a different set of major/minor/patch values will result in the same version. For the record, using 1, 3, and 50 gives 65,536 for
1 shl 16 and 768 for
3 shl 8, and the sum from the
versionOf function is 66,354:
@Test fun `left-shift for major, minor, and patch of 1, 3, and 50`() { assertEquals(65536, 1 shl 16) assertEquals(768, 3 shl 8) assertEquals(66354, (1 shl 16) + (3 shl 8) + 50) }
The
major,
minor, and
patch values are therefore combined into a single integer, which is used for the ordering. The next interesting part is how the
KotlinVersion class implements the standard overrides of
toString,
equals, and
hashCode:
override fun toString(): String = "$major.$minor.$patch" override fun equals(other: Any?): Boolean { if (this === other) return true val otherVersion = (other as? KotlinVersion) ?: return false return this.version == otherVersion.version } override fun hashCode(): Int = version
There’s nothing terribly surprising about the overrides of
toString or
hashCode. The former is just formatting, and the latter reuses that
version calculation just discussed, which is pretty convenient since the left-shifted offset mechanism described above is exactly how Josh Bloch recommended creating a decent
hashCode function in his Effective Java book for the last twenty-some-odd years. 🙂
The real fun is in the override of the
equals function. The
KotlinVersion class, like all Kotlin classes, extends
Any. As a reminder, the
Any class looks like:
package kotlin public open class Any { public open operator fun equals(other: Any?): Boolean public open fun hashCode(): Int public open fun toString(): String }
Returning to the implementation of equals in
KotlinVersion, the first check uses the triple equals operator
=== to see if the current reference and the argument are both pointing to the same instance. If so, the result is equal and no further checking is necessary.
If the two objects are different, the code needs to check the
version property. Because the argument to the
equals function is nullable, you can’t simply access the
version property without checking for
null first. The safe cast operator,
as?, is used to check that. If the argument is not null, this casts it to an instance of
KotlinVersion. If the argument is null, the safe cast operator returns null, so the Elvis operator,
?:, is used to simply return
false rather than continue.
That’s really interesting, actually. The “
return false” statement aborts the assignment of the
otherVersion property. The results is
Nothing, a class almost guaranteed to confuse Java developers, but beyond the scope of this discussion. Suffice it to say that because
Nothing is a subclass of every other class, the resulting type of
otherVersion is
KotlinVersion, as desired.
Assuming we make it to the last line in the
equals method, now there is a value for
otherVersion and a value for the current
version. The comparison then checks
version == otherVersion.version for equality (since they’re both
Int values) and returns the result.
That’s quite a lot of power for three lines of code, and is a great example of how to implement an equivalence check for a nullable property (which happens to be another recipe in the book).
To complete the story, the class has a secondary constructor that can be used when the patch value is unknown.
public constructor(major: Int, minor: Int) : this(major, minor, 0)
Then there are two overloads of the
isAtLeast function:
public fun isAtLeast(major: Int, minor: Int): Boolean = this.major > major || (this.major == major && this.minor >= minor) public fun isAtLeast(major: Int, minor: Int, patch: Int): Boolean = this.major > major || (this.major == major && (this.minor > minor || this.minor == minor && this.patch >= patch))
A couple of tests show how the basic comparisons work:
@Test fun `comparison of KotlinVersion instances work`() { val v12 = KotlinVersion(major = 1, minor = 2) val v1341 = KotlinVersion(1, 3, 41) assertAll( { assertTrue(v12 < KotlinVersion.CURRENT) }, { assertTrue(v1341 <= KotlinVersion.CURRENT) }, { assertEquals(KotlinVersion(1, 3, 41), KotlinVersion(major = 1, minor = 3, patch = 41)) } ) } @Test fun `versions are Ints less than max`() { val max = KotlinVersion.MAX_COMPONENT_VALUE assertAll( { assertTrue(KotlinVersion.CURRENT.major < max) }, { assertTrue(KotlinVersion.CURRENT.minor < max) }, { assertTrue(KotlinVersion.CURRENT.patch < max) } ) }
Because the
KotlinVersion class implements
Comparable, it can be used in a range and has a
contains method. In other words, you can write:
@Test fun `check current version inside range`() { assertTrue(KotlinVersion.CURRENT in KotlinVersion(1,2)..KotlinVersion(1,4)) }
What you can not do, however, is to iterate over that range, because ranges are not progressions, but that’s a post for another day.
I hope you enjoyed this deep dive into what is arguably a trivial, but highly instructive, class in the Kotlin library. The GitHub repository for the book is located here and contains this example as well as many, many others. | https://kousenit.org/2019/11/09/a-deep-dive-into-the-kotlinversion-class/ | CC-MAIN-2020-29 | refinedweb | 1,566 | 54.63 |
.NET Remoting with Events in Visual C++
In my previous column, I introduced the basics of .NET remoting. I showed how to create a remoted class, host it in a server application, and call methods of the class from a client application.
The communication in that simple example was all client-driven. When the client wanted information from the server, it called methods of the remoted object such as Greet() or Records(). These methods don't take parameters, but there's no restriction on remoted objects. You could easily design a system where the client passes parameters to the server as arguments on a method call. For example, the client applications could be used to process orders, and the method calls could pass along information such as item codes, quantities, and ship dates. If the only new information that enters your system is from your client, the remoting model as presented will work perfectly for you.
But, in many systems there is input from several directions at once. For example, the central office might change the prices of the items for which orders are being taken. How can you be sure that all the clients have the most up-to-date prices at all times?
What you want is event handling: The server can raise an event (PriceChanged perhaps) and the client (or multiple clients) can all handle that event. Events are used throughout .NET when one piece of code needs to notify other pieces of code that something has happened. You write an event handler to deal with button clicks and other user interactions with a WinForm application, among other things.
In this sample, I'll add a button to the server application (a WinForm app with a big Listen button) and have the handler for the click event raise a custom event. I'll have the remoting client actually handle that event by displaying a message box. Your job is to run with that and create something useful in your own application.
Defining the Event and Delegate
The delegate represents the event handler. It must be known to both the client and the server. I added this line to the file that declares Greeting::Greeter, the remoted object:
public __delegate void RemoteAlert(String* str);
This means that any function that takes a string and returns void can be used as a RemoteAlert delegate. Delegates are type-safe function pointers: A function that takes an integer, or that takes a string and returns another string, cannot be used as a RemoteAlert delegate. The full signature and return type of the function are part of the definition of the delegate.
The event handler is a function that matches the signature of the delegate: In this example, it must be a void function that takes a String*. The client application implements a class to hold this function, and passes a reference to an instance of the class up to the server, to be added to the list of event handlers maintained there. The class must be known to the server code, either because the server code includes a header file that defines it or because the server code has a reference to an assembly that defines it.
This is a real problem for many developers: The handler class must be known to the server. They discover that events appear to work only when the server application and client application are in the same folder—in other words, when they are not really remoting. Many have discovered that copying the client application to the remote server machine also enables events to work properly over remoting. Copying a client application to the server machine feels awkward. It also sets you up for frustrating debugging or maintenance work because you might have to copy files again and again, and forgetting to copy might make the application fail even though there's nothing wrong with the code.
I have a solution to this issue that's a little more trouble at the beginning and then a lot less trouble afterwards. I define a base class (RemoteHandlerBase) with a pure virtual function (I called mine HandleAlert()) that matches the signature of the delegate. This class is in the same namespace and assembly as the remoted object, Greeter. Then, in the client, I define a derived class, RemoteHandler, that overrides and implements HandleAlert(). The instance that's passed up to the server is actually an instance of RemoteHandler, but upcasts are always allowed, so the server can think of it as an instance of RemoteHandlerBase. When the server calls HandleAlert(), thanks to good old polymorphism, the implementation in the derived class is actually called. It works like a charm and you never have to copy your client application to the server.
Changing the Server
Here is the base class, which is included in the project that defines the remoted object:
namespace Greeting { public __gc class RemoteHandlerBase: public MarshalByRefObject { public: void Alert(String* s) { //polymorphism rules :-) HandleAlert(s); } protected: virtual void HandleAlert(String* s)=0; }; }
Notice that the class must inherit from MarshalByRefObject: A reference will be passed to the server from the client, but the methods will execute on the client. Alert() is a non-virtual wrapper around the virtual function; it will be called from the UI code.
The remoted object needs to change as well: It needs to keep a list of event handlers and to provide a static Alert() function:
public __gc class Greeter: public MarshalByRefObject { public: __event RemoteAlert* RemoteAlertEvent; String* Greet(String* name); String* Greet(); Data::DataSet* Records(); static void Alert(String* s); Greeter(); private: static Collections::ArrayList* greeters=0; };
RemoteAlertEvent is actually a list of events. It will take new items with += and maintains the list. I added the static Alert() because the server code actually has no access to Greeter instances: There is one Greeter object, created as a result of client calls, and the server code isn't using it. (The Greeter class is remoted as a server-activated singleton, so there's only one instance, but by changing only the configuration file I might make it client activated, and then there could be many instances at once, each associated with a different client application.) Adding a static method saved me from any instance management issues on the server side. It uses the greeters list to access all the instances that have been created. The constructor adds instances to the list. Here are the implementations of the constructor and Alert():
Greeter::Greeter() { if (!greeters) greeters = new Collections::ArrayList(); greeters->Add(this); } void Greeter::Alert(String* s) { for (int i=0; i < greeters->Count; i++) (static_cast<Greeter*>(greeters->get_Item(i))) ->RemoteAlertEvent.
using delegate for receiving data from serial port in VC++(win32)Posted by Zahra Babaei on 01/16/2011 08:24am
Something MissingPosted by g-m@n on 01/31/2007 09:48am
I think there's something missing here. Tried this and all I get is an Exception "This remoting proxy has no channel sink ..." of course there's no help available anywhere for the exception thrown.Reply | http://www.codeguru.com/cpp/cpp/cpp_mfc/functions/article.php/c6989/NET-Remoting-with-Events-in-Visual-C.htm | CC-MAIN-2015-48 | refinedweb | 1,179 | 57.91 |
for connected embedded systems
df
Report disk space free (POSIX)
Syntax:
Report disk space free:
df [-abdhw] [-n node] [file...]
Report mapping points:
df -m [-w] [-n node]
Options:
- -a
- (QNX extension) Display all block devices, with the exception of any for which no size information is available. Information will be displayed for a block device even if it's not mounted as a filesystem.
- -b
- (QNX extension) Display disk space in blocks of 512 bytes (default is units of 1K).
- -d
- (QNX extension) Show duplicate devices (i.e. multiple prefixes or mounts to the same device). If -d isn't specified, only the first mapping that resolves to a particular filesystem will be shown.
- -h
- (QNX extension) Display a header.
- -m
- (QNX extension) Instead of displaying free disk space, display a map of prefix mappings available under / on the specified node (or the node df is running on if -n isn't specified). This will show the name the directory appears as under /, and the actual directory it maps to (including its node prefix //n/). This option is very useful when debugging prefix problems in a network.
- -n node
- (QNX extension) Use the specified node's prefix tree to resolve the possible pathname(s) to mounted filesystems.
- -w
- (QNX extension) Warn about prefix mappings that hit or exceed five levels of nesting. This usually indicates that a namespace hasn't been "sensibly" configured.
- file
- The pathname of a file within the hierarchy of the desired filesystem.
Description:
The df utility provides disk space information as well as mappings of prefix namespace resolution under /. The utility has two invocation modes.
- df [-abdhw] [-n node] [file...]
- In this mode, df prints the amount of available space for filesystems to which the user has read access. Filesystems are specified by file operands. When no file operands are specified, df produces information for every filesystem available under / (i.e. nothing that requires a //n/ prefix).
- df -m [-w] [-n node]
- In this (map) mode, df prints prefix mapping points (directories) available under / and the actual filesystem point they resolve to. The mapping point is displayed as a full path, with a node prefix. You invoke this mode by specifying the -m option.
When displaying disk space information, df produces output that consists of one line of information for each specified filesystem. If -h is specified, the output contains a one-line header indicating the meaning of each column. The fields on the output lines are, in order:
- filesystem name
- The name of the filesystem (i.e. the name of the block special file, including node number).
- total space
- The total formatted capacity of the disk drive or partition in question.
- total available user space
- The total amount of space available to the user. This is the sum of space used + space free.
- space used
- The total amount of space allocated to all files within the filesystem.
- space free
- The total amount of space available within the filesystem for the creation of new files by unprivileged users. When this figure is less than or equal to zero, it's not possible to create any new files on the filesystem without first deleting others.
- percentage used
- The percentage of the normally available space that is currently allocated to files. This is the fraction:
- space used/total available user space
- filesystem mount point
- The directory below which the filesystem hierarchy appears.
If a file operand is specified, this column will show the actual mount point of the filesystem within which the file resides, including the node prefix.
If no file operand is specified, this column will show the path through which the listed filesystem is accessed. You should note that depending on prefix mappings, a pathname may not be a mount point but rather an alias prefix.
Note that entries will be skipped when information on the filesystem cannot be obtained, except when the -a option is used, in which case block special files and their sizes will be listed even if they are not mounted as filesystems.
Examples:
Print information about the filesystems accessible under /:
df
Print information about the filesystem that /usr/src resides on:
df /usr/src
Show information on prefix mappings accessible under /, with warnings about deep-nesting:
df -mw
Files:
df writes its output to the standard output. If an error occurs, a diagnostic message will be written to the standard error. The standard input is not used.
Exit status:
- 0
- Successful completion.
- >0
- An error occurred. | http://www.qnx.com/developers/docs/qnx_4.25_docs/qnx4/utils/d/df.html | crawl-003 | refinedweb | 746 | 63.8 |
Overview
Atlassian Sourcetree is a free Git and Mercurial client for Windows.
Atlassian Sourcetree is a free Git and Mercurial client for Mac.
Pyramid_health
Simple healthcheck endpoint for Pyramid, with maintenance mode and application checks.
- PyPI:
- Bitbucket:
Installation
Install using setuptools, e.g. (within a virtualenv):
$ pip install pyramid_health
Setup
Once pyramid_health is installed, you must use the config.include mechanism to include it into your Pyramid project's configuration. In your Pyramid project's __init__.py:
config = Configurator(.....) config.include('pyramid_health')
Alternately you can use the pyramid.includes configuration value in your .ini file:
[app:myapp] pyramid.includes = pyramid_health
Usage
Pyramid_health configuration (values are defaults):
[app:myapp] healthcheck.url = /health healthcheck.disablefile = /tmp/maintenance # touch this file to activate healthcheck.maintenance_code = 299 # Code to return in maintenance mode healthcheck.failure_code = 503 # Code to return when one or more checks fail
Operation
When your application is healthy, pyramid_health endpoint returns 200 OK. When you enable the maintenance mode, the endpoint returns 299 MAINTENANCE and logs Health response: MAINTENANCE. If the request to the healthcheck endpoint asks for the application checks, and one application check or more return an error, the endpoint returns 503 ERROR and logs Health response: ERROR (<all-check-results>).
Application checks
The application checks are routines in your application that subscribe to pyramid_health.HealthCheckEvent event, execute a specific health check and report the outcome as a status (OK or ERROR) and an optional message.
The application checks are not called unless you explicitely request it with the request param checks set to true or all (like: GET /health?checks=all)
To add an application check in your application:
from pyramid.events import subscriber from pyramid_health import HealthCheckEvent @subscriber(HealthCheckEvent) def db_check(event): try: db.ping() except: event.report(name='db', status='NOK', message='ping failed') else: event.report(name='db', status='OK')
Notes:
- You may or may not report succeeding checks
Maintenance mode
In maintenance mode, the healthcheck endpoint's response is changed to inform the HTTP client that this backend is unavailable. Typically a loadbalancer polling the backends would stop sending traffic to a backend in maintenance mode.
The response status code is 299 MAINTENANCE by default. You can change it with healthcheck.maintenance_code. | https://bitbucket.org/Ludia/pyramid_health | CC-MAIN-2017-43 | refinedweb | 368 | 51.44 |
"non-static variable cannot be referenced from a static context" is biggest nemesis of some one who has just
Now before finding answer of compiler error "non-static variable cannot be referenced from a static context", let's have a quick revision of static. Static variable in Java belongs to Class and its value remains same for all instance. static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance(). So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance.
public class StaticTest {
private int count=0;
public static void main(String args[]) throws IOException {
count++; //compiler error: non-static variable count cannot be referenced from a static context
}
}
Why non static variable can not be called from static method
In summary since code in static context can be run even without creating any instance of class, it does not make sense asking value for an specific instance which is not yet created.
How to access non static variable inside static method or block
You can still access any non static variable inside any static method or block by creating an instance of class in Java
and using that instance to reference instance variable. This is the only legitimate way to access non static variable
on static context. here is a code example of accessing non static variable inside static context:
public class StaticTest {
private int count=0;
public static void main(String args[]) throws IOException {
StaticTest test = new StaticTest(); //accessing static variable by creating an instance of class
test.count++;
}
}
So next time if you get compiler error “non-static variable cannot be referenced from a static context” access static member by creating an instance of Class. Let me know if you find any other reason on why non-static variable cannot be referenced from a static context.
Other Java Tutorials you may find useful:
8 comments : variable this cannot be referenced from a static context" or "non static variable super cannot be referenced from a static context".
Thank you for this resource. Together with other articles on your blog it saved me hours of my life and i'm happy to learn/understand these things more thoroughly!
Matt . And non statics are low priority . They only executes when they called .In other words we can say STATIC is predefine and non statics are user define ,according to will . To differentiate between static and non static and also to resolve the problem of clashig between STATICS and NON-STATICS every platform gives this utility . Yup this is a utility.
Find output:
public class MyClass {
int myVar;
public static void setMyVar(int myVar)
{
this.myVar = myVar;
}
public int getMyVar()
{
return this.myVar;
}
public static void main(String args[])
{
MyClass mc = new MyClass();
mc.setMyVar(10);
System.out.println(mc. getMyVar());
}
}
Thank you for you clear, concise, straightforward explanation. That is all that is necessary to help a brother out. You wouldn't think it would be so hard to find a clear thinker..
I am sorry friends this didnt work for me.
package JavaLearning;
public class MainFile{
int abc=8;
public static void main(String[] args) {
Mainfile mF = new MainFile();
System.out.println("Add is "+mF.abc);
}
}
@Qaiser Muhammad: You made a mistake. Mainfile mF = new MainFile(); in this line you given class name wrong. You used lower case of 'f' in Mainfile.
just replace following it execute fine,
MainFile mF = new MainFile(); | http://javarevisited.blogspot.com/2012/02/why-non-static-variable-cannot-be.html?showComment=1373639342023 | CC-MAIN-2014-52 | refinedweb | 651 | 51.89 |
What Are Packages in Java?
A set of classes and interfaces grouped together are known as Packages in JAVA. The name itself defines that pack (group) of related types such as classes, sub-packages, enumeration, annotations, and interfaces that provide name-space management. Every class is a part of a certain package. When you need to use an existing class, you need to add the package within the Java program.
Why Are They Used For?
The benefits of using Packages in Java are as follows:
- The packages organize the group of classes into a single API unit
- It will control the naming conflicts
- The access protection will be easier. Protected and default are the access level control to the package
- Easy to locate the related classes
- Reuse the existing classes in packages
You can categorize packages into:
- Built-in Packages
- User-defined Packages
The built-in packages are from the Java API. The JAVA API is the library of pre-defined classes available in the Java Development Environment. Few built-in packages are below:
- Java.lang–Bundles the fundamental classes
- Java.io - Bundle of input and output function classes
- Java.awt–Bundle of abstract window toolkit classes
- Java.swing–Bundle of windows application GUI toolkit classes
- Java.net–Bundle of network infrastructure classes
- Java.util–Bundle of collection framework classes
- Java.applet–Bundle of creating applet classes
- Java.sql -Bundle of related data processing classes
The built-in packages are again categorized into extension packages. These extension packages start with javax. This is for all the Java languages, which have lightweight component classes.
- Javax.swing
- Javax.servlet
- Javax.sql
Note: The default package imported with no declaration is java.lang package.
User-defined packages are bundles of groups of classes or interfaces created by the programmer for their purpose.
Packages in Java Working Mechanism
In the above example, Java is the package name, awt is the subpackage name and event is the class name. University is the user-defined package name, Department is the subpackage name, and Staff is the class name. Consider a folder inside a file directory. The directory Java is accessible through classpath, to make sure that the classes are easy to locate.
Add Built-in Packages in Java Program
Example 1
Code 1:
import java.util.*; //get all classes from subpackage loads Date class
import java.util.Scanner; //get one specific class Scanner
public class PackageImportExample
{
public static void main(String args[])throws Exception
{
// Instantiate a scanner object
Scanner scanObj = new Scanner(System.in);
System.out.print("Kindly Enter Your UserName :");
String sName = scanObj.nextLine();
System.out.println("UserName is: " + sName);
scanObj.close();
// Instantiate a Date class from Util package
Date currdate = new Date();
System.out.println(currdate.toString());
//Without importing java.net package use complete qualified name to access the class InetAddress
java.net.InetAddress ipAddress=java.net.InetAddress.getLocalHost();
System.out.println("My IP Address :"+ipAddress.getHostAddress());
}
}
To get the use of a package or a class from a library, you need the help of the keyword “import”.
In the above code, there are three ways to import the package.
Import One Specific Class From a Package
- import java.util.scanner
In the above program, you have included only one scanner class from util subpackage. It will get the user value and display.
Import One Whole Package
- import java.util.*
In the above program, the * denotes all the classes from the util package. Along with other classes, it loads the date class as well. The date class displays the current date and time.
Use Complete Qualified Name
java.net.InetAddress ipAddress=java.net.InetAddress.getLocalHost();
The InetAddress class is available in the java.net package, without using the import keyword. Directly call the InetAddress class with the complete package name java.net.InetAddress. This will get the IP address.
Create Your Own Packages in Java
To create a package, you should be aware of the Java file system directory. This is similar to the files and folders organized on your computer. You need the help of the keyword “package” to create your own package. The declaration of the package should be the first statement before any import statements in the Java class.
Before creating your own package, you need to keep in mind that all the classes should be public so that you can access them outside the package.
Let us consider our example of a User-defined package - University.Department.Staff.
Now, create your university package.
Example 2
Code 2:
//creates user defined package university
package university;
public class WelcomeMessage
{
//has one method ShowMessage()
public void ShowMessage()
{
System.out.println("Welcome to our University");
}
}
The above command will create a folder name ‘university’ in the current directory.
Note: –d is used to save the class file in the directory and the ‘.’ (dot) denotes the package in the current directory. To avoid name conflicts, please use lower case for package names.
Let us create the department sub-packages in Java.
A package within another package is a sub-package.
Example 3
Code 3:
//creates sub package within university package
package university.department;
public class DepartmentGoal
{
//has one method DepartmentGoalMessage()
public void DepartmentGoalMessage()
{
System.out.println("Department Message Displayed");
}
}
The above command will create a folder name department inside the folder university.
Let us create the staff class within the department subpackage.
Code 4:
//creates class Staff inside department sub package within university package
package university.department;
public class Staff
{
//has two methods for handling staffs
public void AddStaff()
{
System.out.println("Staff Added !");
}
public void RemoveStaff()
{
System.out.println("Staff Removed !");
}
}
Now the user-defined packages in Java and its class are ready to use. Let us see how to include these classes in the Java program.
Add User-Defined Package in Java Program
By using the keyword “import”, you can add the user-defined packages in Java.
Code 5:
import university.department.Staff;
//import user defined package
public class MyOwnPackageExample
{
public static void main(String args[])
{
Staff mystaff = new Staff();
mystaff.AddStaff();
mystaff.RemoveStaff();
}
}
Code 6:
import university.department.Staff;
//import user defined package
import university.department.DepartmentGoal;
public class MyOwnPackageExample
{
public static void main(String args[])
{
//DepartmentGoal class object created by import that class;
DepartmentGoal dgoal =new DepartmentGoal();
dgoal.DepartmentGoalMessage();
Staff mystaff = new Staff();
mystaff.AddStaff();
mystaff.RemoveStaff();
}
}
Note: The import statements should appear after the package statement in package creating files.
Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.
Conclusion:
A Java package is a set of classes, interfaces, and sub-packages that are similar. In Java, it divides packages into two types: built-in packages and user-defined packages.
Built-in Packages (packages from the Java API) and User-defined Packages are the two types of packages (create your own packages). Packages help you prevent name conflicts and write more maintainable code.
For gaining more expertise in Packages in Java, Simplilearn’s java certification program can assist you in broadening your horizon. The course comprises 250+ hours of applied learning, 20 lesson-end, and 6 phase-end projects, and has 4 industry-aligned capstone projects, which will provide you with a first-hand learning experience.
This Full Stack Java Developer course will teach you the fundamentals of front-end, middleware, and back-end Java web development. You'll learn how to develop applications, test and deploy code, and use MongoDB to store data, among other things.
Have any questions for us? Leave them in the comments section of this article, and our experts will get back to you on them, as soon as possible! | https://www.simplilearn.com/tutorials/java-tutorial/packages-in-java | CC-MAIN-2022-05 | refinedweb | 1,267 | 50.23 |
31 August 2012 12:20 [Source: ICIS news]
LONDON (ICIS)--Second-quarter net profit at Poland's Synthos sank 48% year on year to zlotych (Zl) 117m ($35m, €28m) from Zl 225m as its synthetic rubber division faced margin squeezes on tougher markets, the company said on Friday.
Sales revenues rose 22% year on year to Zl 1.63bn from Zl 1.34bn, Synthos, ?xml:namespace>
“While the Q2 figures show the first signs of margin erosion in the rubber segment (rubber represented 65% of the unadjusted and 76% of the adjusted Q2 consolidated EBITDA [earnings before interest, tax, depreciation and amortisation]), we expect the headwinds to intensify in Q3 when the full effect of the butadiene and SBR price slump is accounted for (prices came down more rapidly in June),” analyst Piotr Drozd at Prague-based investment bank WOOD & Company wrote in a note to investors.
The rubber segment’s EBITDA margins eroded to 17.7% in the second quarter from 22% in the first quarter if this year and from 33.8% in the second quarter of last year, Drozd noted.
The styrenics segment fared better in the second quarter with the EBITDA margin up from 2.5% a year ago to 4.9%, but it experienced an EBITDA contraction against the first quarter of this year, falling to Zl 25m from Zl 40m, he added.
($1 = Zl 3.35, €1 = Zl 4 | http://www.icis.com/Articles/2012/08/31/9591526/rubber-margin-erosion-takes-toll-on-q2-net-profit-at-polands-synthos.html | CC-MAIN-2014-10 | refinedweb | 235 | 69.72 |
Voila, an open-source python library that is used to turn the jupyter notebook into a standalone web application It supports widgets to create interactive dashboards, reports, etc. Voila launches a kernel when it is connected to a notebook and executes all the cells but it does not stop the kernel there so that the user can interact with the output.
Voila converts the jupyter notebook into HTML and returns it to the user as a dashboard or report with all the inputs excluded and the outputs included. Voila supports all the python libraries for widgets such as bqplot, plotly, ipywidgets, etc.
Voila is framework and language agnostic which means that voila can work with any jupyter kernel whether it is C++ or Python, etc. because it is built on jupyter standard protocols.
Voila is useful in many ways because of its extensibility and usability, it can serve as a solution for Data Science or Business Analyst professionals to share their work which is relevant for the end-user or client. In this article, we will explore how easily and effortlessly we can use Voila to create reports and dashboards.
Implementation of Voila in Python:
Like any other library, we will install Voila using pip install voila. After installing voila we need to open the jupyter notebook to check that a new tab named Voila is added in the toolbar.
- Importing required libraries
As Voila supports Plotly so we will be using plotly in this article, other than that we will be using pandas for loading the data.
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
We will be using stock data of a firm which can be downloaded from any financial website like Yahoo Financial, I have downloaded data for ‘Biocon Pharmaceuticals’ and stored it in a CSV file. The data contains Date, Opening Price, Closing price, etc.
df = pd.read_csv(‘biocon.csv’)
df.head()
c. Adding Some Information regarding Stock
We will add some information regarding the company whose dataset we are working on i.e. Biocon Pharmaceuticals so that our dashboard/application will be informative.
info = ”’Biocon Limited is a globally recognized, innovation-led organization that is enabling access to high quality, advanced therapies for diseases that are chronic, where medical needs are largely unmet and treatment costs are high. We are driven by the belief that the pharmaceutical industry has a humanitarian responsibility to provide essential drugs to patients who are in need and to do so with the power of innovation. In line with this belief, Biocon has developed and commercialized a differentiated portfolio of novel biologics, biosimilars, and complex small molecule APIs in India and several key global markets, as well as, generic formulations in the U.S. and Europe. We are a leading global player for biosimilars and APIs for statins, immunosuppressants and other speciality molecules, with customers in over 120 countries.”’
print(info)
d. Using Plotly to create Charts
We will create different plots that are used to analyze the stock market data. We will use the markdowns for giving the name of the charts so that it reflex in the dashboard/application.
- Candlestick Chart
fig1 = go.Figure(data=[go.Candlestick(x=df['Date'],
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'])])
fig1.show()
- Line Chart
fig2 = px.line(df, x='Date', y='High')
fig2.show()
- OHLC Chart
fig3 = go.Figure(data=go.Ohlc(x=df['Date'],
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close']))
fig3.show()
- Area Chart
fig4 = px.area(df, x=df['Date'], y=df['High'])
fig4.show()
Converting Notebook to Web Application
Now we will use Voila to create the dashboard/application in just a single click. As seen above now we will click the Voila tab in the toolbar section to launch voila. As soon as we click Voila it will launch voila in a new window and start executing the commands one by one.
After Execution, the Dashboard/Application is created which will display all the outputs without the code. I have added markdowns for different sections as you will see below in the images of the Voila Dashboard/Application.
- Info Section
- Analysis using Charts
In the above images, we saw how Voila rendered our jupyter notebook and converted it into a dashboard/application. All the graphs are created using plotly so these graphs are highly interactive and downloadable. We can also launch voila using the command prompt by using Voila <filename.ipynb>
Similarly, we can create a different application using different Python libraries which are used to control data using widgets.
Conclusion:
In this article, we saw how we can use Voila to create a dashboard/application. We created a stock analysis dashboard/application using plotly and Voila. Voila is blazingly fast and we can share the results created using voila to others also. It is highly extensible, flexible, and has high usability.. | https://analyticsindiamag.com/complete-guide-to-voila-to-turn-a-jupyter-notebook-into-a-standalone-web-application/ | CC-MAIN-2020-45 | refinedweb | 822 | 53.61 |
″ in “Additional compiler arguments”
- Open Project Properties > Flex Build Packaging > BlackBerry Tablet OS > Advanced tab.
- Add “-forceAirVersion 2.5″
-″ to “2.6″.
Hi Jason,
Will you make the playbook_overrides.swc available?
Forgot to upload the ZIP. Updated. Thanks!
Hey Jason, I ran into a (hopefully) minor issue while attempting this process.
I did as you suggested, and even tried your included TwitterTrendsFinal project, and get the same results.
As a quick side-note, when launching on the desktop, it seems to run as expected; this issue I’m reporting only seems to pertain to launching to a device or simulator:
————————
Error occurred while packaging the application:
Packaging failed:1
C:\Users\\AppData\Local\Temp\bar-app6665679692599201187.xml: error 102: Invalid namespace
Error: AIR validation failed
————————
Let me know if I can provide any more information.
Looks like you’re using a prerelease build of FB. We’ll follow up on the prerelease forums. If anyone has issues with the public build, please post your issues here in comments.
Hi Julian, I am having a problem publishing to the simulator using your workaround for Flash Builder 4.5 Premium. On the simulator I receive “error unable to start application”. In Flash Builder I receive the following error:
Deployment Failed: Sending Launch request…
Info: Action: Launch
Info: Launching AIRHelloWorld.debug.testbG9Xb3JsZC5kZWJ1ZyAgICA…
result::Failed
Info: done
I deleted the virtual machine and created it again and all of sudden it works. :o)
Thanks for this Jason. I’ve applied this to the Flash Builder 4.5 release and I am able to debug in the simulator again.
Pingback: Migrating from Flex 4.0 to 4.5 « Killerspaz's Blog
hey jason,
im following your directions to a tee but when i go to package my flex application i get one of two errors:
when i change the application descriptor file air version to 2.5 i get,
namespace 2.5.0 in the application descriptor file should be equal or higher than the minimum version 2.6.0 required by flex sdk
or, if i leave it as 2.6.0 and go to package i get,
error 102: invalid namespace
Error: AIR validation failed
i have the overrides.swc in my build path as well as the library overrides.fxpl and it still wont package right..
also your twitter trends throws me the same error as i explained above….
any ideas?
Don’t change the namespace in your application descriptor. That step isn’t in the instructions. If you were on pre-release, I did have older instructions that included this step. Instead, use the BlackBerry packaging option -forceAirVersion 2.5.
yeah im using the FB 4.5 release version but if i dont change the namespace i get,
error 102: invalid namespace
Error: AIR validation failed
and thats with -forceAirVersion 2.5 in the packaging options, thats why im so confused
Does that AIR validation failed show up as a Problem in FB or as text in the Console? If it’s in the Console, it sounds like a wrong version of ADT is being used for packaging.
Could be a bad or old BB SDK or Flex SDK w/ AIR overlay.
yeah thats whats weird everything is new and updated..brand new flex 4.5 sdk bb tablet sdk 1.0.1. the problem is displayed as a pop up error in fb, nothing is displayed in the console thats why im confused.
I’m also having this same problem with the namespaces. Is there a resolution for this?
If it’s a popup error, then it’s likely a bad version of ADT in your blackberry SDK. Check your SDK location and confirm that its what you expect. Go to preferences > flash builder > target platforms > BlackBerry Tablet OS and confirm the SDK path.
You might also try creating a clean workspace in File > Switch Workspace > Other…
It’s not coming as a popup but as an error in the Problems section. I’ve tried both of the resolutions but they did not fix the issue. My Blackberry SDK is the latest from the download site.
I’ve contacted RIM for some help. I’ll write up a new post when I hear back.
Would like to take a look at the source code for playbook_overrides.zip.
Would it be possible for you to mail it to me?
Thanks
It’s there in the ZIP. Open the FXPL file in Flash Builder.
Hey Jason,
I am having the same issue that Mark Z is having.
I get: error 102: invalid namespace
Error: AIR validation failed.
I didn’t change the descriptor and left it at 2.6. I also have the most current BlackBerry Tablet SDK 1.0.1 and the release version of FB 4.5. I saw that you said that it might be a bad ADT but I’m not getting the error in the console. Nothing even shows up in the console I just immediately get a pop up with the above error. I also uninstalled EVERYTHING and re-installed it just to make sure I am starting completely fresh. Do you have any idea what might be wrong, I’m in a huge whole here because I need to update my app but can’t get it packaged.
Jason,
Do you have any news on the issue with Brian and Mark Z as i have the same issue.
When I set the namespace as 2.6, it appears to work. However, the run on desktop mode in Flash Builder 4.5 launches in a portrait shaped window. Do you know how to fix how this launches? The resolutions appeared correct for the device.
I’ve updated to post with the fix in the troubleshooting section. Change your namespace from “2.6.0″ to “2.6″. The bug is logged for RIMs next release. Thanks everyone for the feedback.
What if mine is 2.6 and it still doesnt work?
Can you be more specific, what’s the error you’re getting? Same AIR validation failed?
yeah same error 102, just like everyone previously. so i made sure my namespace said 2.6, tried again and still get the same error. any ideas?
Try the attached playbook_overrides.zip. In there is a TwitterTrendsFinal.fxp. Let me know if that works for you.
For your project, try to do a clean build and double check all the other settings. Make sure you edited the -app.xml in your /src directory and not the one in bin-debug.
hey jason,
I tried what you said, cleaning the project, created a new workspace, and reinstalled everything (all the sdks and FB). I still get error 102 air packaging failed. I am using Windows 7 64-bit, if thats an issue. Also your twittertrendsfinal.fxp throws me the same exact error. I even tried changing the air-config and airmobile-config and flex-config xmls in the flex sdk to swf version 10 and player version 10.0.0 and that still didnt work, so I changed it all back.
I started new mobile project with sdk 4.5 and did the steps you mentioned above, when I run the application it stucks with a solid white screen on desktop and playbook. when I delete -swf-version=10 it works on desktop but not on playbook………….. so nothing works on playbook….what can I do????
I’am only putting a simple list in the view which will navigate to another view after clicking an item ( I don’t think it is 2.6 dependant)
I’m seeing the same as Ehab. Also, when I run the debugger on the device, the application is throwing a error about not finding the class SoftKeyboardEvent. The app never seems to get to frame 2 in that even preinitialize never fires. Adding a ref to this class makes the error go away, but still never gets past the splash screen. I’ve not had the opportunity to look at the overrides SWC source yet though.
DK
OK, I got it: for the “Blackberry Tablet OS target” option to appear, the simulator must be installed.
I’m getting the same problem.
I didn’t get it until I tried to add in an icon.
“Namespace 0.0.0 in the application descriptor file should be equal or higher than the minimum version 2.6.0 required by Flex SDK.”
This is what I have.
Whats going on here?
The solution seems to work in general, but I have a problem with the Spark DataGrid. In the Playbook the app just hangs. In the FB simulator I get following error:]
…which is caused by my code line…
at packages.DominoUtilities::DominoMobileViewUtilities/viewcolumns_loaded()[D:\Flash Builder 4.5\FlexMobile4Domino2.0\src\packages\DominoUtilities\DominoMobileViewUtilities.as:330]
…which is this line…
container.addElement(this._dataGrid);
I’m adding a Spark DataGrid object to a Spark Group container.
Here is the full error message:
TypeError:]
at spark.components::DataGrid$/setPartProperty()[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\DataGrid.as:1136]
at spark.components::DataGrid/setGridProperty()[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\DataGrid.as:1168]
at spark.components::DataGrid/partAdded()[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\DataGrid.as:2626]
at spark.components.supportClasses::SkinnableComponent/findSkinParts()[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\supportClasses\SkinnableComponent.as:736]
at spark.components::DataGrid/findSkinParts()[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\DataGrid.as:2580]
at spark.components.supportClasses::SkinnableComponent/attachSkin()[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\supportClasses\SkinnableComponent.as:701]
at spark.components.supportClasses::SkinnableComponent/validateSkinChange()[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\supportClasses\SkinnableComponent.as:443]
at spark.components.supportClasses::SkinnableComponent/createChildren()[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\supportClasses\SkinnableComponent.as:406]
at spark.components::DataGrid/createChildren()[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\DataGrid.as:2220]
at mx.core::UIComponent/initialize()[E:\dev\hero_private\frameworks\projects\framework\src\mx\core\UIComponent.as:7624]
at mx.core::UIComponent/[E:\dev\hero_private\frameworks\projects\framework\src\mx\core\UIComponent.as:7485]
at mx.core::UIComponent/addChildAt()[E:\dev\hero_private\frameworks\projects\framework\src\mx\core\UIComponent.as:7189]
at spark.components::Group/addDisplayObjectToDisplayList()[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\Group.as:2037]
at spark.components::Group/[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\Group.as:1628]
at spark.components::Group/addElementAt()[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\Group.as:1387]
at spark.components::Group/addElement()[E:\dev\hero_private\frameworks\projects\spark\src\spark\components\Group.as:1345]
at packages.DominoUtilities::DominoMobileViewUtilities/viewcolumns_loaded()[D:\Flash Builder 4.5\FlexMobile4Domino2.0\src\packages\DominoUtilities\DominoMobileViewUtilities.as:330]
at packages.DominoUtilities::DominoDBUtilities/common_XML_result()[D:\Flash Builder 4.5\Flex4SoapgateQ2.0\src\packages\DominoUtilities\DominoDBUtilities.as:2214]
at packages.DominoUtilities::DominoDBUtilities/dbviewcolumns_result()[D:\Flash Builder 4.5\Flex4SoapgateQ2.0\src\packages\DominoUtilities\DominoDBUtilities.as:2164]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.rpc::AbstractOperation/[E:\dev\hero_private\frameworks\projects\rpc\src\mx\rpc\AbstractOperation.as:249]
at mx.rpc::AbstractInvoker/[E:\dev\hero_private\frameworks\projects\rpc\src\mx\rpc\AbstractInvoker.as:318]
at mx.rpc::Responder/result()[E:\dev\hero_private\frameworks\projects\rpc\src\mx\rpc\Responder.as:56]
at mx.rpc::AsyncRequest/acknowledge()[E:\dev\hero_private\frameworks\projects\rpc\src\mx\rpc\AsyncRequest.as:84]
at DirectHTTPMessageResponder/completeHandler()[E:\dev\hero_private\frameworks\projects\rpc\src\mx\messaging\channels\DirectHTTPChannel.as:451]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
Ignore my last comment. Somehow the mx.DateGrid classes made it into my code stream. That obviously won’t work. I fixed my code and it is now working perfectly.
Nice solution. Thanks.
I’m getting the blank screen. How do I know what to look for since I’m not getting any error messages? I’m using 4.5.1 with debug token to the playbook device. But, what is weird is that debug to desktop is also now showing blank screen. Any ideas?
The icon installs on the device, but it runs just a white screen only.
Thanks,
Don Kerr
Manager, Space City Adobe User Group
Did you remember to set in -swf-version=10 in compiler arguments?
works for me
1. created project.
2. added 2 lines into compiler configuration
3. added playbook_override path to libs
Works on latest downloaded Flex Builder and Playbook SDK 2 June 2011:
FlashBuilder_4_5_LS10.exe
BlackBerryTabletSDK-Air-Installer-1.0.2-Win-201105191426.exe
Pingback: How to use Flex 4.5 with Air 2.5 on the Blackberry PlayBook « priyeshsheth
Hey.. your post was very useful as I was getting nuts chasing a solution for this issue. I’ve followed all those steps and it finally launches.
The proplem, now, is that I’m not able to design the UI in design mode (under mxml file) because of a “circular dependency issue” between Flex 4.5′s mobile.swc and your playbook_ovverides.swc. It reports a SWC Load Error.
Any suggestion to make it work?
Thank you doubly, man!
It used to work for me on Flex 4.5 but I now get the blank screen since I updated to 4.5.1. I checked and the configuration is correct.
4.51 works for anyone?
Best regards, Ben
The playbook_overrides.swc will not work with 4.5.1. I’ll post a blog explanation shortly.
Pingback: Using Flex 4.5.1 on the BlackBerry PlayBook « Jason's Flex Blog
Actually, I just had to set Flex 4.5 as compilation target in the Flex Compiler properties to make it work again. I hope RIM will release an update for AIR 2.7 soon
Pingback: What is the Difference between Adobe Flex and Adobe AIR? | Adobe Expressed
Hi,
I tried to use playbook_overrides with Flash Builder 4.5 updated to 4.5.1.
I am getting the following error
Class flash.events::SoftKeyboardEvent could not be found.
Is there any solution?
As noted in Update 3 above, this workaround is no longer required. Please use the standard project setup for SDK 4.5.1 and BlackBerry Tablet OS.
I get the error below and I don’t know what to do.
Error occurred while packaging the application:
Compilation failed…
The app xml file (myapp-app.xml) has the correct air namespace:
Yes, I use the air 2.7 and Flashbuilder 4.5
Any idea? Solution? Workaround? Please!
Thanks
I’m also getting the blank screen and seriously starting to lose interest. I’m using 4.5.1 and have uninstaller, installer, cleared project, recreated projectsm tested both ADL Version 2.6.0.19120 and ADL Version 2.7.1.19610. No errors, no log no nothing. Has 4.5.1 been tested at all?
The interesting part is that I made my code to run once or twice in the beginning but after a restart of FB it stopped working and has only worked once since then, dont ask me why. So im not sure its runtime related, seems more like Adobe has seriously damaged the build process somehow.
Be sure that you’re not using any of the workarounds listed in this post. As I mention in the updates, this workaround is no longer required.
Check your project to make sure you do not have -swf-version=10 or -forceAirVersion 2.5 where referenced above. Since I can’t reproduce your problem, my first suggestion is to launch an on-device debug session from your project and see if the debugger will report anything suspicious like a VerifyError.
If you still get this error, check your workspace log for any additional information.
Win: C:\Users\username\Adobe Flash Builder 4.5\.metadata\.log
Mac: /Users/username/Documents/Adobe Flash Builder 4.5/.metadata/.log
I am getting below error
Deployment Failed: Info: Sending request: Launch
Info: Action: Launch
Info: Launching Main.debug.testDev_Main_debug_527d75fe…
result::Already Running
Info: done | http://blogs.adobe.com/jasonsj/2011/05/flex45_air25_playbook.html | CC-MAIN-2014-10 | refinedweb | 2,671 | 53.37 |
1.1 anton 1: \ source location handling 2: 1.19 ! anton 3: \ Copyright (C) 1995,1997,2003,2004: 1.3 pazsan 20: \ related stuff can be found in kernel.fs 1.1 anton 21: 1.9 anton 22: \ this stuff is used by (at least) assert.fs and debugs.fs 1.1 anton 23: 1.10 anton 24: : loadfilename#>str ( n -- addr u ) 1.12 anton 25: included-files 2@ rot min 2* cells + 2@ ; 1.10 anton 26: 27: : str>loadfilename# ( addr u -- n ) 28: included-files 2@ 0 ?do ( addr u included-files ) 29: i over >r 2* cells + 2@ 30: 2over str= if 31: rdrop 2drop i unloop exit 32: endif 33: r> loop 1.11 anton 34: drop 2drop 0 ; 1.10 anton 35: 1: | http://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/source.fs?annotate=1.19;sortby=log;f=h;only_with_tag=MAIN;ln=1 | CC-MAIN-2021-17 | refinedweb | 129 | 80.07 |
WordPress.com Implements the Twitter API 39
This morning Matt Mullenweg announced on his blog that WordPress.com has enabled posting and reading blogs via the Twitter API. Now any Twitter app that supports a custom API URL (Tweetie is one such) can be used to either post updates to a WordPress.com blog, or to read updates from blogs to which one has subscribed. Dave Winer calls the move by Automattic, WordPress.com's parent company, "deeply insidious," and notes that 10 years ago he did a similar thing in his Manila blogging platform when the Blogger API came out. Winer opines that Automattic's move has made the Twitter API into an open standard, due to WordPress.com's large base. Winer notes (in a comment on the above-linked post), "The fun starts if they [WordPress] relax some of the limits of the Twitter API and fix some of the glaring problems."
I felt a great disturbance ... (Score:5, Funny)
Re:I felt a great disturbance ... (Score:5, Funny)
I felt a great disturbance in the Blogosphere, as if millions of rants were posted but were abruptly truncated at 140 characters. I fear som
Fixed.
Re:I felt a great disturbance ... (Score:4, Funny)
I feel the same. It's terrible to be supporting a new protocol that's worse! But the most important reason I am against this is that it wil
<posted via Twitteriffic>
Just another API (Score:3, Informative)
They're just adding a feature for who use Twitter apps. It's not like this will become the only supported way to post or read blog replies, so what does it matter? They do support other blog posting API's too.
Whoosh (Score:1)
Did you *really* believe anyone thought wordpress was limiting their blogging s/w to 140 characters?
Re:Whoosh (Score:4, Funny)
I hoped and dreamed!
Re: (Score:2)
Misleading summary... (Score:5, Informative)
I thought it strange that this move would be called "deeply insidious". Here's the context in Dave Winer's blog post:
Since there is effectively now dozens of twitter clients capable of connecting to wordpress via this api, the api becomes a de-facto standard for accessing blogs.
Re: (Score:2, Insightful)
The funny thing is, the Twitter API is actually far better-designed and more well-specified than the previous piles of hacks that Winer foisted on us.
XML-RPC? Completely schemaless, you have no way of knowing what anything actually means in it. No namespace support either. RSS? It still doesn't do namespaces (the dc: elements are HARDWIRED). SOAP? Started the same way, ended up with a horribly overwrought schema (XSD) and even that only after well after Winer left it behind.
Re: (Score:2)
Bring on the AC Winer-hate!
The Twitter API is nothing more than a REST implementation. Seriously, how can you compare the Twitter API with XML-RPC or SOAP? If you want to rant about the last two, you should have at least compared them with REST. The Twitter API might be far better designed because it offers a limited amount of functionality, versus REST, XML-RPC and SOAP that provide a protocol to implement web-based APIs.
Besides, how should I know what POSTing to
/statuses/update means: the "Twitter API RP
Re:Misleading summary... (Score:5, Interesting)
Frankly, I'd much rather see OpenMicroBlogging [wikipedia.org] being used and promoted rather than the Twitter API. It's used in StatusNet and identi.ca and allows for seamless subscriptions between various OpenMicroBlogging-enabled sites. It's sort of like the XMPP/Jabber of microblogging.
StatusNet also supports the Twitter API, but I don't know of any clients that let me point to identi.ca instead of Twitter. I use Gwibber [launchpad.net], though which natively supports both of them and more.
Re: (Score:1, Troll)
no thanks
Re: (Score:1)
"You keep using that word. I do not think it means what you think it means."
The word 'insidious' has rather negative connotations [dict.org], but I don't understand (from Winer's post) how WordPress may have done this with malintent. Does he have something against open standards? Does he think that WordPress has it in for Identica or others?
Is this another WP security hole? (Score:2, Interesting)
Probably....
So who will be the first to use it?
Finally a use for Twitter I can support... (Score:5, Interesting)
It will let me post to my blog. I have a Twitter account only because I was interested to see how it worked. I have made exactly 2 Tweets. Once I realized i would need friends who cared what I was doing, I realized it wasn't for me. I am happily living a rather dull existence
:)
I have just realized a hitch with using this for updating my blog: I don't have a blog, and with few friends who would want to read it, not much reason to start one.
I know its old fashioned but if I think of interesting things to say, I say them to my wife or my friends face to face
:P
Re: (Score:2)
I know its old fashioned but if I think of interesting things to say, I say them to my wife or my friends face to face
:P
Egads! Ye Luddite!! And what a way to lose wife and friends!!!
Re: (Score:1)
Why not identi.ca? (Score:3, Interesting)
Re: (Score:1)
There is too much spam on twitter already (Score:1)
Its disturbing that they are now going to let even more people in...
Watch This Space (Score:2, Insightful)
Definitely a company to watch.
News? (Score:1, Insightful)
Blog CMS gets a new module. Who cares?
Re: (Score:1)
IE adds ActiveX control to post XML. Who cares?
Something where you can read each item once. (Score:2)
They need to come up with something that lets you read each item exactly once - no duplicates, and no missing items.
Here's a Twitter feed in XML. [twitter.com] That's updated every 60 seconds, and if you miss something, it's gone.
Twitter has an RSS feed capability, but it doesn't properly support the "already read this ID" feature; every poll gets you a dump of the relevant inbox. (Some server side implementations of RSS get this right. Some have problems because they're front-ended by caching servers which lack
Re: (Score:2)
The "already read this ID" feature of what? That's not a feature of Atom or RSS feeds. They just supply a feed of items; it's up to the client to filter them if it wants to remove already-read entries.
Or are you saying that Twitter doesn't provide persistent IDs for entries?
Re: (Score:2)
RSS supports an "etag", which is supposed to indicate if the feed has something new. When the client polls an RSS server, and gets XML data, the data includes an etag value. When you poll an RSS feed, you supply the etag value from last time. If the feed hasn't changed, the client is supposed to get a 304 status.
Some RSS feed servers implement this, and some don't. Twitter doesn't. So polling Twitter via RSS results in far more network traffic than it should, and extra client work throwing out dupli
Re: (Score:3)
Etag is nothing to do with RSS. It's an HTTP feature [wikipedia.org].
And since Twitter supports if-modified-since, you can use that instead.
slow news day (Score:1)
Re: (Score:1)
A quick search of the wordpress plugins directory shows over 500 twitter related plugins so this is news because?
Because they needed a press release with embedded hype-terms?
don't care (Score:1)
Open standard tied to a single website (Score:2, Insightful)
Yeah, it's nice that WordPress gets support for Twitter protocol.
So, would the Twitter clients please stop thinking that Twitter is the only site that speaks Twitter protocol?
I've been using identi.ca, and you can post on identi.ca using Twitter API. All you need to do is to change the base URL. And Twitter clients as a rule don't let you do that. People hard-code their clients to point to twitter.com. I've seen a lot of pointless forks of Twitter clients that differ from the base version only in that they
blowback (Score:2)
The twitter company problem made and released their API so their product would become more embedded in things. That happened. But I bet they never thought that the API spec would be re-implemented by another company. Its an interesting development. Their market power was able to create a de-facto standard but then the standard was non entirely theirs.
Of course, the market leading API has been reimplemented many times before. AMD makes x86 chips. Wine and ReactOS make Windows. | http://tech.slashdot.org/story/09/12/12/2153209/wordpresscom-implements-the-twitter-api | CC-MAIN-2013-20 | refinedweb | 1,501 | 74.39 |
Download presentation
Presentation is loading. Please wait.
Published byRoxana Willard Modified over 2 years ago
1
The Interpretation of Financial Statements Chapter 16 © Luby & O’Donoghue (2005)
2
Why use ratio analysis Provides framework Comparison to previous years Trends identified Identify areas of concern Targets can be set Comparison to other similar organisations
3
Limitations Accounting statements present a limited picture Accounting policies can distort any inter-firm comparisons and trend analysis Historical Ratios can be misleading if used in isolation Effects of inflation ignored Year end figures in statements may not be representative of whole year
4
Ratio analysis ProfitabilityEfficiencyLiquidity Capital Structure Investment
5
Data for ratio illustrations Profit Statements for year ended 31 December Balance sheet as at 31 December Turnover 9,885 Fixed assets 8,595 Less cost of sales Opening stock500 Current assets Net purchases6,800 Stock850 Closing stock(850)(6,450) Debtors780 Gross profit 3,435 Bank1201,750 less expenses (1,200) Net operating profit (PBIT)2,235 Current liabilities Less interest payable (162) Creditors585 Net profit before tax 2,073 Bank/ short term loans500(1,085)665 Less taxation (413) Profit after interest and tax 1,660 Long term liabilities less dividends preference (100) Debentures (1,800) less dividends ordinary (800) 7,460 Retained profit for the year760 Retained profit b/f 1,200 Capital and reserves Retained profit c/f 1,960 Ordinary shares8,000 4,000 Preference shares 1,000 Market price of shares1.21 Retained profit 1,960 8 million ordinary shares issued Reserves 500 7,460
6
Profitability LiquidityEfficiency Capital Structure Capital StructureInvestment against capital employed Gross profit margin Net profit margin Expenses to sales Return on capital employed Return on owners equity Measured againstsales
7
Gross Profit x 100 Sales This indicates the margin of profit between sales and cost of sales. PROFITABILITY Gross profit margin €3,435 x 100=34.7% €9,885
8
Net Profit x 100 Sales This shows the amount of profit after all expenses are deducted. PROFITABILITY Net profit margin €2,235 x 100 =22.6% €9,885
9
Expenses x 100 Sales This shows the percentage of sales needing to cover expenses. This ratio assesses the ability of management in controlling expenses of the business. Expenses to sales PROFITABILITY € 1,200 x 100 = 12.1% €9,885
10
Net Profit x 100 Capital employed This shows the ratio of net profit to the investment in the business. Return on Capital Employed (ROCE) PROFITABILITY share capital + reserves + Loans Usually net profit before interest and tax €2,235 x 100 =24.1% €9,260
11
Net Profit x 100 Shareholders funds This ratio assesses the return (profit) for the ordinary (equity) shareholders alone. Return on Owners Equity (ROOE) PROFITABILITY Should only relate to ordinary shareholders Can be before or after interest and tax €1,660 x 100 =22.3% €7,460
13
Sales _ Fixed Assets This shows the number of times that the fixed assets are turned over in the period. A high rate of return indicates that a business is operating efficiently and is making the best possible use of assets. A low rate suggests inefficient use of assets. Fixed asset turnover EFFICIENCY €9,885 =1.2 : 1 €8,595
14
Sales _ Total assets This shows the number of times that the total net assets are turned over in the period. A high rate of return indicates that a business is operating efficiently and is making the best possible use of assets. A low rate suggests inefficient use of assets. Total asset turnover EFFICIENCY €9,885 =1.067 : 1 €9,260
15
Cost of sales Average stock Stock turnover is the average number of times per year that the whole value of stock is purchased and resold. The quicker stock is told the quicker profit will be made on that item. A low rate of turnover shows that old stock is being left on the shelves. Stock turnover EFFICIENCY €6,450 =9.6 times 675
16
Stock can also be measured by examining the number of days on average that stock is held. Average stock x 365 Cost of sales Stock days EFFICIENCY €675 x 365 =38.2 days €6,450
17
Trade Debtors x 365 Credit Sales Indicates how quickly debtors pay. This ratio can be expressed as the number of days credit taken by debtors. Debtors days EFFICIENCY €780 x 365 =28.8 days €9,885
18
Trade Creditors x 365 Credit Purchases Indicates how long before creditors are paid. This ratio can be expressed as the number of days credit taken before payment. Creditors days EFFICIENCY €585 x 365 =31.4 days €6,800
19
Note: the combination of net profit margin and the asset turnover gives the return on capital employed. Profit Margin x Asset Turnover Sales xNet Profit x 100 = Net Profit x100 Capital Employed SalesCapital Employed Return on Capital Employed (ROCE )
21
Current Assets Current Liabilities This is a measure of the short term solvency of a business. Current ratio LIQUIDITY €1,750 =1.6 : 1 €1,085
22
Current ratios – sector norms Industry TypeCurrent Ratio Manufacturing2.5 – 4.5 : 1 Wholesalers2 : 1 Retail/Supermarkets0.8 : 1 Hotels, restaurants, fast foods0.4 : 1
23
Current Assets - Stock Current Liabilities Also know as quick ratio. Indicates the ability of a business to pay off short term liabilities without resorting to the liquidation of stock or the sale of fixed assets. Acid-test ratio LIQUIDITY €900 =0.8 : 1 €1,085
25
Capital structure Capital structure measures the funding mix of a business.
26
Financing Through debtThrough equity Interest must be paid on the debt Dividends will be paid to shareholders Interest is tax deductibleDividends are not tax deductible Debt generally cheaperEquity requires higher returns to compensate for risk Debt is risky because interest must be paid Dividends are at discretion of management and may be deferred Loan must be repaidEquity does not require repayment CAPITAL STRUCTURE
27
Preference shares and long term loans All shareholders funds and long term loans This is the ratio of fixed interest debt and capital to ordinary share capital. Gearing €2,800 =0.38 : 1 €7,460 38% CAPITAL STRUCTURE
28
Gearing The higher the ratio of debt to equity, the more dependent the organisation is upon borrowed funds, and the greater the risk that it will be unable to meet interest payments on these funds as they fall due. Low gearing = where debt is less than capital & reserves. Neutral gearing = debt = capital & reserves. High gearing = debt is greater than capital & reserves. < 100% = 100% > 100% CAPITAL STRUCTURE
29
Profit before interest Interest payable The ability of a company to meets its interest commitments, measured by expressing the profit before interest as a multiple of the interest paid and payable. Interest cover €2,235 =13.8 : 1 €162 CAPITAL STRUCTURE
31
Profit available for ordinary dividend Number of equity shares issued Earnings is measured in pence / cents and is concerned with the profits available to ordinary shareholders from which a dividend can be paid. Earnings per share (EPS) INVESTMENT €1,560 =€0.195 ie 19.5 cent 8,000
32
Market Price Earnings per share Market price as a multiple of the latest earnings per share. Used as a relative measure of stock market performance. Relates the EPS to the price the shares sell at in the market. The greater the PE the greater the demand for shares. Price/earnings ratio (PE) INVESTMENT €1.21 =6.2 times €0.195
33
Price/earnings ratio (PE) The P/E ratio depends mainly on four things: The overall level of the stock market (e.g. bull or bear). The industry in which the company operates. The company’s record. The markets view on the company’s prospects. INVESTMENT P/E ratio Commentary <8The market feels that these companies have poor future prospects and/or are trading in unfashionable business sectors. 8-12The market feels that these companies have reasonable prospects but are unsure regarding if and when these companies will shine. 12-20The market feels these companies have very good prospects and that these prospects are beginning to be reflected in the share price as demand for the share increases. Companies with P/Es of 15 are considered good safe blue chip investments >20These are the boom stocks or high flyers. Their potential is generally reflected already in their share price and the demand for the share is on the increase. These type of companies tend to be young high flyers who retain all their profits for future growth.
34
Profit available to pay dividend Dividends paid and proposed This ratio indicates the proportion of available profits, which is distributed to shareholders, and the amount which is retained by the organisation. Dividend cover INVESTMENT €1,560 =2 times €800
35
Dividend per share Price per share The real rate of return on investment in shares. Dividend yield INVESTMENT 0.10 x 100 =8.3% 1.21
36
Dividend yield The average dividend yield for the major world markets over the last twenty years Dividend Yield % UK Ireland Eurobloc (ex UK) USA Japan Asia pacific (ex Japan) 2.7% 1.8% 2.4% 1.5% 0.9% 3.1% (Source: Irish Times Business Supplement)
37
Setting the context The age of the business The size of the business The economic and political environment Industry Trends
38
Company performance – number of years Have sales increased or decreased and by what percentage? Has operating profit increased or decreased and by what percentage? Has loan interest increased or decreased and by what percentage? Check the long-term loans in the balance sheet to see if they have increased/decreased. Compare profit after tax to see if it has increased or decreased. Calculate percentage increase/decrease in fixed assets. If assets have been increased, has this been financed through increased loans or issued share capital? Check to see if the business has cash or an overdraft, and is this increasing or decreasing? Check current assets and liabilities for any major increases. Check the percentage increase/ decrease in long-term loans.
39
Company comparison Check both businesses are in the same industry/sector Compare the size of each business. This is normally done, by comparing the total asset levels in the balance sheet (fixed assets + current assets- current liabilities). Compare sales and profit levels. Compare financing. For example is one company highly geared and the other low geared? Compare cash balances/overdraft levels.
40
Sector overviews Hospitality and tourism performance is commented on throughout chapter 16 and should be read and studied carefully. For a retail overview the performance of Arnotts is analysis in a case study from page 339 of the text book.
41
Hospitality ratios RatioFormula Occupancy ratios Rooms occupied x 100 Rooms available Number of guests x 100 Guest capacity Actual room revenue x100 Potential room revenue Average room rate Room revenue Rooms occupied Average rate per guest Room revenue Number of guests Average spend Sales Number of covers Sales mix Rooms revenue x 100 Total hotel revenue Food revenue x 100 Total hotel revenue Bar revenue x 100 Total hotel revenue
Similar presentations
© 2017 SlidePlayer.com Inc. | http://slideplayer.com/slide/3857957/ | CC-MAIN-2017-17 | refinedweb | 1,860 | 52.6 |
.de SE \" start example .sp .5 .RS .ft CR .nf .. .de EE \" end example .fi .sp .5 .RE .ft R .. .TL Bash \- The GNU shell* .AU Chet Ramey Case Western Reserve University chet@po.cwru.edu .FS *An earlier version of this article appeared in The Linux Journal. .FE .NH 1 Introduction .PP .B Bash is the shell, or command language interpreter, that will appear in the GNU operating system. The name is an acronym for the \*QBourne-Again SHell\*U, a pun on Steve Bourne, the author of the direct ancestor of the current .UX shell \fI/bin/sh\fP, which appeared in the Seventh Edition Bell Labs Research version of \s-1UNIX\s+1. .PP Bash is an \fBsh\fP\-compatible shell that incorporates useful features from the Korn shell (\fBksh\fP) and the C shell (\fBcsh\fP), described later in this article. It is ultimately intended to be a conformant implementation of the IEEE POSIX Shell and Utilities specification (IEEE Working Group 1003.2). It offers functional improvements over sh for both interactive and programming use. .PP While the GNU operating system will most likely include a version of the Berkeley shell csh, Bash will be the default shell. Like other GNU software, Bash is quite portable. It currently runs on nearly every version of .UX and a few other operating systems \- an independently-supported port exists for OS/2, and there are rumors of ports to DOS and Windows NT. Ports to \s-1UNIX\s+1-like systems such as QNX and Minix are part of the distribution. .PP The original author of Bash was Brian Fox, an employee of the Free Software Foundation. The current developer and maintainer is Chet Ramey, a volunteer who works at Case Western Reserve University. .NH 1 What's POSIX, anyway? .PP .I POSIX is a name originally coined by Richard Stallman for a family of open system standards based on \s-1UNIX\s+1. There are a number of aspects of \s-1UNIX\s+1 under consideration for standardization, from the basic system services at the system call and C library level to applications and tools to system administration and management. Each area of standardization is assigned to a working group in the 1003 series. .PP The POSIX Shell and Utilities standard has been developed by IEEE Working Group 1003.2 (POSIX.2).\(dd .FS \(ddIEEE, \fIIEEE Standard for Information Technology -- Portable Operating System Interface (POSIX) Part 2: Shell and Utilities\fP, 1992. .FE: .IP \(bu Aspects of the shell's syntax and command language. A number of special builtins such as .B cd and .B exec are being specified as part of the shell, since their functionality usually cannot be implemented by a separate executable; .IP \(bu A set of utilities to be called by shell scripts and applications. Examples are programs like .I sed, .I tr, and .I awk. Utilities commonly implemented as shell builtins are described in this section, such as .B test and .B kill . An expansion of this section's scope, termed the User Portability Extension, or UPE, has standardized interactive programs such as .I vi and .I mailx; .IP \(bu A group of functional interfaces to services provided by the shell, such as the traditional \f(CRsystem()\fP C library function. There are functions to perform shell word expansions, perform filename expansion (\fIglobbing\fP), obtain values of POSIX.2 system configuration variables, retrieve values of environment variables (\f(CRgetenv()\fP\^), and other services; .IP \(bu A suite of \*Qdevelopment\*U utilities such as .I c89 (the POSIX.2 version of \fIcc\fP), and .I yacc. .PP Bash is concerned with the aspects of the shell's behavior defined by POSIX.2. The shell command language has of course been standardized, including the basic flow control and program execution constructs, I/O redirection and pipelining, argument handling, variable expansion, and quoting. The .I special builtins, which must be implemented as part of the shell to provide the desired functionality, are specified as being part of the shell; examples of these are .B eval and .B export . Other utilities appear in the sections of POSIX.2 not devoted to the shell which are commonly (and in some cases must be) implemented as builtin commands, such as .B read and .B test . POSIX.2 also specifies aspects of the shell's interactive behavior as part of the UPE, including job control and command line editing. Interestingly enough, only \fIvi\fP-style line editing commands have been standardized; \fIemacs\fP editing commands were left out due to objections. .PP While POSIX.2 includes much of what the shell has traditionally provided, some important things have been omitted as being \*Qbeyond its scope.\*U There is, for instance, no mention of a difference between a .I login shell and any other interactive shell (since POSIX.2 does not specify a login program). No fixed startup files are defined, either \- the standard does not mention .I .profile . .NH 1 Basic Bash features .PP Since the Bourne shell provides Bash with most of its philosophical underpinnings, Bash inherits most of its features and functionality from sh. Bash implements all of the traditional sh flow control constructs (\fIfor\fP, \fIif\fP, \fIwhile\fP, etc.). All of the Bourne shell builtins, including those not specified in the POSIX.2 standard, appear in Bash. Shell \fIfunctions\fP, .B PS1 , .B IFS , and .B PATH . Bash implements essentially the same grammar, parameter and variable expansion semantics, redirection, and quoting as the Bourne shell. Where differences appear between the POSIX.2 standard and traditional sh behavior, Bash follows POSIX. .PP The Korn Shell (\fBksh\fP) is a descendent of the Bourne shell written at AT&T Bell Laboratories by David Korn\(dg. .B RANDOM and .B REPLY , the .B typeset builtin, the ability to remove substrings from variables based on patterns, and shell arithmetic. .FS \(dgMorris Bolsky and David Korn, \fIThe KornShell Command and Programming Language\fP, Prentice Hall, 1989. .FE .B RANDOM expands to a random number each time it is referenced; assigning a value to .B RANDOM seeds the random number generator. .B REPLY is the default variable used by the .B read builtin when no variable names are supplied as arguments. The .B typeset builtin is used to define variables and give them attributes such as \fBreadonly\fP.: .SE $ echo $((3 + 5 * 32)) 163 .EE .LP For interactive use, Bash implements ksh-style aliases and builtins such as .B fc (discussed below) and .B jobs . Bash aliases allow a string to be substituted for a command name. They can be used to create a mnemonic for a \s-1UNIX\s+1 command name (\f(CRalias del=rm\fP), to expand a single word to a complex command (\f(CRalias news='xterm -g 80x45 -title trn -e trn -e -S1 -N &'\fP), or to ensure that a command is invoked with a basic set of options (\f(CRalias ls="/bin/ls -F"\fP). .PP The C shell (\fBcsh\fP)\(dg, originally written by Bill Joy while at Berkeley, is widely used and quite popular for its interactive facilities. Bash includes a csh-compatible history expansion mechanism (\*Q! history\*U), brace expansion, access to a stack of directories via the .B pushd , .B popd , and .B dirs builtins, and tilde expansion, to generate users' home directories. Tilde expansion has also been adopted by both the Korn Shell and POSIX.2. .FS \(dgBill Joy, An Introduction to the C Shell, \fIUNIX User's Supplementary Documents\fP, University of California at Berkeley, 1986. .FE .PP There were certain areas in which POSIX.2 felt standardization was necessary, but no existing implementation provided the proper behavior. The working group invented and standardized functionality in these areas, which Bash implements. The .B command builtin was invented so that shell functions could be written to replace builtins; it makes the capabilities of the builtin available to the function. The reserved word \*Q!\*U was added to negate the return value of a command or pipeline; it was nearly impossible to express \*Qif not x\*U cleanly using the sh language. There exist multiple incompatible implementations of the .B test , and leaves the behavior undefined when more arguments are supplied. Bash uses the POSIX.2 algorithm, which was conceived by David Korn. .NH 2 Features not in the Bourne Shell .PP There are a number of minor differences between Bash and the version of sh present on most other versions of \s-1UNIX\s+1. The majority of these are due to the POSIX standard, but some are the result of Bash adopting features from other shells. For instance, Bash includes the new \*Q!\*U reserved word, the .B command builtin, the ability of the .B read builtin to correctly return a line ending with a backslash, symbolic arguments to the .B umask builtin, variable substring removal, a way to get the length of a variable, and the new algorithm for the .B test builtin from the POSIX.2 standard, none of which appear in sh. .PP Bash also implements the \*Q$(...)\*U command substitution syntax, which supersedes the sh `...` construct. The \*Q$(...)\*U construct expands to the output of the command contained within the parentheses, with trailing newlines removed. The sh syntax is accepted for backwards compatibility, but the \*Q$(...)\*U form is preferred because its quoting rules are much simpler and it is easier to nest. .PP The Bourne shell does not provide such features as brace expansion, the ability to define a variable and a function with the same name, local variables in shell functions, the ability to enable and disable individual builtins or write a function to replace a builtin, or a means to export a shell function to a child process. .PP Bash has closed a long-standing shell security hole by not using the .B $IFS variable to split each word read by the shell, but splitting only the results of expansion (ksh and the 4.4 BSD sh have fixed this as well). Useful behavior such as a means to abort execution of a script read with the \*Q.\*U command using the \fBreturn\fP builtin or automatically exporting variables in the shell's environment to children is also not present in the Bourne shell. Bash provides a much more powerful environment for both interactive use and programming. .NH 1 Bash-specific Features .PP This section details a few of the features which make Bash unique. Most of them provide improved interactive use, but a few programming improvements are present as well. Full descriptions of these features can be found in the Bash documentation. .NH 2 Startup Files .PP Bash executes startup files differently than other shells. The Bash behavior is a compromise between the csh principle of startup files with fixed names executed for each shell and the sh \*Qminimalist\*U behavior. An interactive instance of Bash started as a login shell reads and executes .I ~/.bash_profile (the file .bash_profile in the user's home directory), if it exists. An interactive non-login shell reads and executes .I ~/.bashrc . A non-interactive shell (one begun to execute a shell script, for example) reads no fixed startup file, but uses the value of the variable .B $ENV , if set, as the name of a startup file. The ksh practice of reading .B $ENV for every shell, with the accompanying difficulty of defining the proper variables and functions for interactive and non-interactive shells or having the file read only for interactive shells, was considered too complex. Ease of use won out here. Interestingly, the next release of ksh will change to reading .B $ENV only for interactive shells. .NH 2 New Builtin Commands .PP There are a few builtins which are new or have been extended in Bash. The .B enable builtin allows builtin commands to be turned on and off arbitrarily. To use the version of .I echo found in a user's search path rather than the Bash builtin, \f(CRenable -n echo\fP suffices. The .B help builtin provides quick synopses of the shell facilities without requiring access to a manual page. .B Builtin is similar to .B command in that it bypasses shell functions and directly executes builtin commands. Access to a csh-style stack of directories is provided via the .B pushd , .B popd , and .B dirs builtins. .B Pushd and .B popd insert and remove directories from the stack, respectively, and .B dirs lists the stack contents. On systems that allow fine-grained control of resources, the .B ulimit builtin can be used to tune these settings. .B Ulimit allows a user to control, among other things, whether core dumps are to be generated, how much memory the shell or a child process is allowed to allocate, and how large a file created by a child process can grow. The .B suspend command will stop the shell process when job control is active; most other shells do not allow themselves to be stopped like that. .B Type, the Bash answer to .B which and .B whence, shows what will happen when a word is typed as a command: .SE $ type export export is a shell builtin $ type -t export builtin $ type bash bash is /bin/bash $ type cd cd is a function cd () { builtin cd ${1+"$@"} && xtitle $HOST: $PWD } .EE .LP Various modes tell what a command word is (reserved word, alias, function, builtin, or file) or which version of a command will be executed based on a user's search path. Some of this functionality has been adopted by POSIX.2 and folded into the .B command utility. .NH 2 Editing and Completion .PP One area in which Bash shines is command line editing. Bash uses the .I readline library to read and edit lines when interactive. Readline is a powerful and flexible input facility that a user can configure to individual tastes. It allows lines to be edited using either emacs or vi commands, where those commands are appropriate. The full capability of emacs is not present \- there is no way to execute a named command with M-x, for instance \- but the existing commands are more than adequate. The vi mode is compliant with the command line editing standardized by POSIX.2. .PP Readline is fully customizable. In addition to the basic commands and key bindings, the library allows users to define additional key bindings using a startup file. The .I inputrc file, which defaults to the file .I ~/.inputrc , is read each time readline initializes, permitting users to maintain a consistent interface across a set of programs. Readline includes an extensible interface, so each program using the library can add its own bindable commands and program-specific key bindings. Bash uses this facility to add bindings that perform history expansion or shell word expansions on the current input line. .PP Readline interprets a number of variables which further tune its behavior. Variables exist to control whether or not eight-bit characters are directly read as input or converted to meta-prefixed key sequences (a meta-prefixed key sequence consists of the character with the eighth bit zeroed, preceded by the .I meta-prefix character, usually escape, which selects an alternate keymap), to decide whether to output characters with the eighth bit set directly or as a meta-prefixed key sequence, whether or not to wrap to a new screen line when a line being edited is longer than the screen width, the keymap to which subsequent key bindings should apply, or even what happens when readline wants to ring the terminal's bell. All of these variables can be set in the inputrc file. .PP The startup file understands a set of C preprocessor-like conditional constructs which allow variables or key bindings to be assigned based on the application using readline, the terminal currently being used, or the editing mode. Users can add program-specific bindings to make their lives easier: I have bindings that let me edit the value of .B $PATH and double-quote the current or previous word: .SE # Macros that are convenient for shell interaction $if Bash # edit the path "\eC-xp": "PATH=${PATH}\ee\eC-e\eC-a\eef\eC-f" # prepare to type a quoted word -- insert open and close double # quotes and move to just after the open quote "\eC-x\e"": "\e"\e"\eC-b" # Quote the current or previous word "\eC-xq": "\eeb\e"\eef\e"" $endif .EE .LP There is a readline command to re-read the file, so users can edit the file, change some bindings, and begin to use them almost immediately. .PP Bash implements the .B bind builtin for more dyamic control of readline than the startup file permits. .B Bind is used in several ways. In .I list mode, it can display the current key bindings, list all the readline editing directives available for binding, list which keys invoke a given directive, or output the current set of key bindings in a format that can be incorporated directly into an inputrc file. In .I batch mode, it reads a series of key bindings directly from a file and passes them to readline. In its most common usage, .B bind takes a single string and passes it directly to readline, which interprets the line as if it had just been read from the inputrc file. Both key bindings and variable assignments may appear in the string given to .B bind . .PP The readline library also provides an interface for \fIword completion\fP. When the .I completion character (usually TAB) is typed, readline looks at the word currently being entered and computes the set of filenames of which the current word is a valid prefix. If there is only one possible completion, the rest of the characters are inserted directly, otherwise the common prefix of the set of filenames is added to the current word. A second TAB character entered immediately after a non-unique completion causes readline to list the possible completions; there is an option to have the list displayed immediately. Readline provides hooks so that applications can provide specific types of completion before the default filename completion is attempted. This is quite flexible, though it is not completely user-programmable. Bash, for example, can complete filenames, command names (including aliases, builtins, shell reserved words, shell functions, and executables found in the file system), shell variables, usernames, and hostnames. It uses a set of heuristics that, while not perfect, is generally quite good at determining what type of completion to attempt. .NH 2 History .PP Access to the list of commands previously entered (the \fIcommand history\fP) is provided jointly by Bash and the readline library. Bash provides variables (\fB$HISTFILE\fP, \fB$HISTSIZE\fP, and \fB$HISTCONTROL\fP) and the .B history and .B fc builtins to manipulate the history list. The value of .B $HISTFILE specifes the file where Bash writes the command history on exit and reads it on startup. .B $HISTSIZE is used to limit the number of commands saved in the history. .B $HISTCONTROL provides a crude form of control over which commands are saved on the history list: a value of .I ignorespace means to not save commands which begin with a space; a value of .I ignoredups means to not save commands identical to the last command saved. \fB$HISTCONTROL\fP was named \fB$history_control\fP in earlier versions of Bash; the old name is still accepted for backwards compatibility. The .B history command can read or write files containing the history list and display the current list contents. The .I history library, generally incorporated directly into the readline library, implements a facility for history recall, expansion, and re-execution of previous commands very similar to csh (\*Qbang history\*U, so called because the exclamation point introduces a history substitution): .SE $ .EE .LP The command history is only saved when the shell is interactive, so it is not available for use by shell scripts. .NH 2 New Shell Variables .PP There are a number of convenience variables that Bash interprets to make life easier. These include .B FIGNORE , which is a set of filename suffixes identifying files to exclude when completing filenames; .B HOSTTYPE , which is automatically set to a string describing the type of hardware on which Bash is currently executing; .B command_oriented_history , which directs Bash to save all lines of a multiple-line command such as a \fIwhile\fP or \fIfor\fP loop in a single history entry, allowing easy re-editing; and .B IGNOREEOF , whose value indicates the number of consecutive EOF characters that an interactive shell will read before exiting \- an easy way to keep yourself from being logged out accidentally. The .B auto_resume variable alters the way the shell treats simple command names: if job control is active, and this variable is set, single-word simple commands without redirections cause the shell to first look for and restart a suspended job with that name before starting a new process. .NH 2 Brace Expansion .PP Since sh offers no convenient way to generate arbitrary strings that share a common prefix or suffix (filename expansion requires that the filenames exist), Bash implements \fIbrace expansion\fP, a capability picked up from csh. Brace expansion is similar to filename expansion, but the strings generated need not correspond to existing files. A brace expression consists of an optional .I preamble , followed by a pair of braces enclosing a series of comma-separated strings, and an optional .I postamble . The preamble is prepended to each string within the braces, and the postamble is then appended to each resulting string: .SE $ echo a{d,c,b}e ade ace abe .EE .LP As this example demonstrates, the results of brace expansion are not sorted, as they are by filename expansion. .NH 2 Process Substitution .PP On systems that can support it, Bash provides a facility known as \fIprocess substitution\fP. .I : .SE $ cmp <(old_prog) <(new_prog) .EE .NH 2 Prompt Customization .PP One of the more popular interactive features that Bash provides is the ability to customize the prompt. Both .B $PS1 and .B $PS2, the primary and secondary prompts, are expanded before being displayed. Parameter and variable expansion is performed when the prompt string is expanded, so any shell variable can be put into the prompt (e.g., after an \fIsu\fP. Before printing each primary prompt, Bash expands the variable .B : .SE $ PS1='\eu@\eh [\et] \eW($SHLVL:\e!)\e$ ' chet@odin [21:03:44] documentation(2:636)$ cd .. chet@odin [21:03:54] src(2:637)$ .EE .LP The string being assigned is surrounded by single quotes so that if it is exported, the value of .B $SHLVL will be updated by a child shell: .SE chet@odin [21:17:35] src(2:638)$ export PS1 chet@odin [21:17:40] src(2:639)$ bash chet@odin [21:17:46] src(3:696)$ .EE .LP The \fP\e$\fP escape is displayed as \*Q\fB$\fP\*U when running as a normal user, but as \*Q\fB#\fP\*U when running as root. .NH 2 File System Views .PP Since Berkeley introduced symbolic links in 4.2 BSD, one of their most annoying properties has been the \*Qwarping\*U to a completely different area of the file system when using .B cd , and the resultant non-intuitive behavior of \*Q\fBcd ..\fP\*U. The \s-1UNIX\s+1 kernel treats symbolic links .I. .PP Bash provides a .I logical view of the file system. In this default mode, command and filename completion and builtin commands such as .B cd and .B pushd which change the current working directory transparently follow symbolic links as if they were directories. The .B $PWD variable, which holds the shell's idea of the current working directory, depends on the path used to reach the directory rather than its physical location in the local file system hierarchy. For example: .SE $ cd /usr/local/bin $ echo $PWD /usr/local/bin $ pwd /usr/local/bin $ /bin/pwd /net/share/sun4/local/bin $ cd .. $ pwd /usr/local $ /bin/pwd /net/share/sun4/local $ cd .. $ pwd /usr $ /bin/pwd /usr .EE .LP One problem with this, of course, arises when programs that do not understand the shell's logical notion of the file system interpret \*Q..\*U differently. This generally happens when Bash completes filenames containing \*Q..\*U according to a logical hierarchy which does not correspond to their physical location. For users who find this troublesome, a corresponding .I physical view of the file system is available: .SE $ cd /usr/local/bin $ pwd /usr/local/bin $ set -o physical $ pwd /net/share/sun4/local/bin .EE .NH 2 Internationalization .PP One of the most significant improvements in version 1.13 of Bash was the change to \*Qeight-bit cleanliness\*U. \*Qodd\*U. .NH 2 POSIX Mode .PP Although Bash is intended to be POSIX.2 conformant, there are areas in which the default behavior is not compatible with the standard. For users who wish to operate in a strict POSIX.2 environment, Bash implements a \fIPOSIX mode\fP. When this mode is active, Bash modifies its default operation where it differs from POSIX.2 to match the standard. POSIX mode is entered when Bash is started with the .B -posix option. This feature is also available as an option to the \fBset\fP builtin, \fBset -o posix\fP. For compatibility with other GNU software that attempts to be POSIX.2 compliant, Bash also enters POSIX mode if the variable .B $POSIXLY_CORRECT is set when Bash is started or assigned a value during execution. .B $POSIX_PEDANTIC is accepted as well, to be compatible with some older GNU utilities. When Bash is started in POSIX mode, for example, it sources the file named by the value of .B $ENV rather than the \*Qnormal\*U startup files, and does not allow reserved words to be aliased. .NH 1 New Features and Future Plans .PP There are several features introduced in the current version of Bash, version 1.14, and a number under consideration for future releases. This section will briefly detail the new features in version 1.14 and describe several features that may appear in later versions. .NH 2 New Features in Bash-1.14 .PP. .PP. .PP Several of the features described earlier, such as .B "set -o posix" and .B $POSIX_PEDANTIC , are new in version 1.14. There is a new shell variable, .B OSTYPE , to which Bash assigns a value that identifies the version of \s-1UNIX\s+1 it's running on (great for putting architecture-specific binary directories into the \fB$PATH\fP). Two variables have been renamed: .B $HISTCONTROL replaces .B $history_control , and .B $HOSTFILE replaces .B $hostname_completion_file . In both cases, the old names are accepted for backwards compatibility. The ksh .I select construct, which allows the generation of simple menus, has been implemented. New capabilities have been added to existing variables: .B $auto_resume can now take values of .I exact or .I substring , and .B $HISTCONTROL understands the value .I ignoreboth , which combines the two previously acceptable values. The .B dirs builtin has acquired options to print out specific members of the directory stack. The .B $nolinks variable, which forces a physical view of the file system, has been superseded by the .B \-P option to the .B set builtin (equivalent to \fBset -o physical\fP); the variable is retained for backwards compatibility. The version string contained in .B $BASH_VERSION now includes an indication of the patch level as well as the \*Qbuild version\*U. Some little-used features have been removed: the .B bye synonym for .B exit and the .B $NO_PROMPT_VARS variable are gone. There is now an organized test suite that can be run as a regression test when building a new version of Bash. .PP The documentation has been thoroughly overhauled: there is a new manual page on the readline library and the \fIinfo\fP file has been updated to reflect the current version. As always, as many bugs as possible have been fixed, although some surely remain. .NH 2 Other Features .PP There are a few features that I hope to include in later Bash releases. Some are based on work already done in other shells. .PP In addition to simple variables, a future release of Bash will include one-dimensional arrays, using the ksh implementation of arrays as a model. Additions to the ksh syntax, such as \fIvarname\fP=( ... ) to assign a list of words directly to an array and a mechanism to allow the .B read builtin to read a list of values directly into an array, would be desirable. Given those extensions, the ksh .B "set \-A" syntax may not be worth supporting (the .B \-A option assigns a list of values to an array, but is a rather peculiar special case). .PP Some shells include a means of \fIprogrammable\fP. .PP It would also be nice to give the user finer-grained control over which commands are saved onto the history list. One proposal is for a variable, tentatively named .B HISTIGNORE , which would contain a colon-separated list of commands. Lines beginning with these commands, after the restrictions of .B $HISTCONTROL have been applied, would not be placed onto the history list. The shell pattern-matching capabilities could also be available when specifying the contents of .B $HISTIGNORE . .PP One thing that newer shells such as .B wksh (also known as .B dtksh ) provide is a command to dynamically load code implementing additional builtin commands into a running shell. This new builtin would take an object file or shared library implementing the \*Qbody\*U of the builtin (\fIxxx_builtin()\fP for those familiar with Bash internals) and a structure containing the name of the new command, the function to call when the new builtin is invoked (presumably defined in the shared object specified as an argument), and the documentation to be printed by the .B help command (possibly present in the shared object as well). It would manage the details of extending the internal table of builtins. .PP A few other builtins would also be desirable: two are the POSIX.2 .B getconf command, which prints the values of system configuration variables defined by POSIX.2, and a .B disown builtin, which causes a shell running with job control active to \*Qforget about\*U one or more background jobs in its internal jobs table. Using .B getconf , for example, a user could retrieve a value for .B $PATH guaranteed to find all of the POSIX standard utilities, or find out how long filenames may be in the file system containing a specified directory. .PP There are no implementation timetables for any of these features, nor are there concrete plans to include them. If anyone has comments on these proposals, feel free to send me electronic mail. .NH 1 Reflections and Lessons Learned .PP The lesson that has been repeated most often during Bash development is that there are dark corners in the Bourne shell, and people use all of them. In the original description of the Bourne shell, quoting and the shell grammar are both poorly specified and incomplete; subsequent descriptions have not helped much. The grammar presented in Bourne's paper describing the shell distributed with the Seventh Edition of \s-1UNIX\s+1\(dg is so far off that it does not allow the command \f(CWwho|wc\fP. In fact, as Tom Duff states: .QP Nobody really knows what the Bourne shell's grammar is. Even examination of the source code is little help.\(dd .FS \(dgS. R. Bourne, \*QUNIX Time-Sharing System: The UNIX Shell\*U, \fIBell System Technical Journal\fP, 57(6), July-August, 1978, pp. 1971-1990. .FE .FS \(ddTom Duff, \*QRc \- A Shell for Plan 9 and \s-1UNIX\s+1 systems\*U, \fIProc. of the Summer 1990 EUUG Conference\fP, London, July, 1990, pp. 21-33. .FE .LP The POSIX.2 standard includes a \fIyacc\fP grammar that comes close to capturing the Bourne shell's behavior, but it disallows some constructs which sh accepts without complaint \- and there are scripts out there that use them. It took a few versions and several bug reports before Bash implemented sh-compatible quoting, and there are still some \*Qlegal\*U sh constructs which Bash flags as syntax errors. Complete sh compatibility is a tough nut. .PP The shell is bigger and slower than I would like, though the current version is substantially faster than previously. The readline library could stand a substantial rewrite. A hand-written parser to replace the current \fIyacc\fP-generated one would probably result in a speedup, and would solve one glaring problem: the shell could parse commands in \*Q$(...)\*U constructs as they are entered, rather than reporting errors when the construct is expanded. .PP As always, there is some chaff to go with the wheat. Areas of duplicated functionality need to be cleaned up. There are several cases where Bash treats a variable specially to enable functionality available another way (\fB$notify\fP vs. \fBset -o notify\fP and \fB$nolinks\fP vs. \fBset -o physical\fP, for instance); the special treatment of the variable name should probably be removed. A few more things could stand removal; the .B $allow_null_glob_expansion and .B $glob_dot_filenames variables are of particularly questionable value. The \fB$[...]\fP arithmetic evaluation syntax is redundant now that the POSIX-mandated \fB$((...))\fP construct has been implemented, and could be deleted. It would be nice if the text output by the .B help builtin were external to the shell rather than compiled into it. The behavior enabled by .B $command_oriented_history , which causes the shell to attempt to save all lines of a multi-line command in a single history entry, should be made the default and the variable removed. .NH 1 Availability .PP As with all other GNU software, Bash is available for anonymous FTP from .I prep.ai.mit.edu:/pub/gnu and from other GNU software mirror sites. The current version is in .I bash-1.14.1.tar.gz in that directory. Use .I archie to find the nearest archive site. The latest version is always available for FTP from .I bash.CWRU.Edu:/pub/dist. Bash documentation is available for FTP from .I bash.CWRU.Edu:/pub/bash. .PP The Free Software Foundation sells tapes and CD-ROMs containing Bash; send electronic mail to \f(CRgnu@prep.ai.mit.edu\fP or call \f(CR+1-617-876-3296\fP for more information. .PP Bash is also distributed with several versions of \s-1UNIX\s+1-compatible systems. It is included as /bin/sh and /bin/bash on several Linux distributions (more about the difference in a moment), and as contributed software in BSDI's BSD/386* and FreeBSD. .FS *BSD/386 is a trademark of Berkeley Software Design, Inc. .FE .PP The Linux distribution deserves special mention. There are two configurations included in the standard Bash distribution: a \*Qnormal\*U configuration, in which all of the standard features are included, and a \*Qminimal\*U configuration, which omits job control, aliases, history and command line editing, the directory stack and .B pushd/popd/dirs, process substitution, prompt string special character decoding, and the .I select construct. This minimal version is designed to be a drop-in replacement for the traditional \s-1UNIX\s+1 /bin/sh, and is included as the Linux /bin/sh in several packagings. .NH 1 Conclusion .PP Bash is a worthy successor to sh. It is sufficiently portable to run on nearly every version of \s-1UNIX\s+1 from 4.3 BSD to SVR4.2, and several \s-1UNIX\s+1 workalikes. It is robust enough to replace sh on most of those systems, and provides more functionality. It has several thousand regular users, and their feedback has helped to make it as good as it is today \- a testament to the benefits of free software. | http://opensource.apple.com/source/bash/bash-80/bash/doc/article.ms | CC-MAIN-2016-26 | refinedweb | 6,003 | 66.13 |
How would you configure a DNS Name Server per NIC (eth0 vs eth1) interface on RHEL/Centos 6?
E.
I've added:
DNS1:10.0.0.2 > /etc/sysconfig/network-scripts/ifcfg-eth0
DNS1:19.168.0.2 > /etc/sysconfig/network-scripts/ifcfg-eth1
However these values get ignored, and it always defaults to the setting in resolv.conf
"nameserver 10.0.0.2" When eth0 is down, connections are sent over eth1 ... however DNS can no longer resolve as it's trying to reach 10.0.0.2.
How do I get it to respect the DNS settings in ifcfg rather than a default for resolv.conf?
Or how do I configure a different DNS Name Server for eth0 vs eth1?
Is there a better way of handling this?
Updated
We have two VLANS, each has it's own DNS server on it's respective subnet. These handle look-ups for local DNS (example.loc, guest.app etc), as well as forwarding when needed.
These are two separate servers in two separate physical locations. If possible I'd rather not run one server across the two subnets (one handles sensitive data).
If eth0 was to go down, I need eth1 to continue to be able to make DNS requests.
I thought about adding two IPs to resolv.conf, and then letting it fallover if it can't reach the server in the first subnet, but this seems inelegant (having to wait for the first server to timeout with every DNS query when eth0 is down).
nameserver 10.0.0.2
nameserver 192.168.0.2
resolv.conf
You can't easily do what you want.
Or how do I configure a different DNS Name Server for eth0 vs eth1?
The name lookup for a hostname happens through standard system libraries and isn't associated in any way with a particular "connection". In fact, at the time the DNS query happens, there is no connection, because your application hasn't even figured out the address to which it's going to connect (which is why it's using DNS in the first place).
How do I get it to respect the DNS settings in ifcfg rather than a default for resolv.conf?
The Linux resolver only has a single, global configuration (/etc/resolv.conf). There is no per-interface, per-domain, or per-connection setting of any sort. The settings in /etc/sysconfig/network-scripts/... are only used to populate /etc/resolv.conf, and generally if you specify DNS1 and DNS2 in these files, the last interface to come up will be what you see in /etc/resolv.conf.
/etc/resolv.conf
/etc/sysconfig/network-scripts/...
DNS1
DNS2
Is there a better way of handling this?
Can you tell us what you're actually trying to accomplish? We might be able to suggest better solutions if you can tell us more about your specific situation.
A DNS request is basically either
So there's no knowing at "request" time which Ethernet card is going to be involved. What you could reasonably ask would be "all requests ending in 'domain1.com' should go to 192.168.0.2, and all other requests should go to 10.0.0.2.".
I believe dnsmasq can do this (see How to configure dnsmasq to forward multiple DNS servers?). But before I found that out, I rolled my own in Twisted:
from twisted.internet import reactor
from twisted.names import dns
from twisted.names import client, server
class Resolver(client.Resolver):
def queryUDP(self, queries, timeout=None):
if len(queries) > 0 and (str(queries[0].name).endswith('.domain1.com'):
self.servers = [('192.168.0.2', 53)]
else:
self.servers = [('10.0.0.2', 53)]
return client.Resolver.queryUDP(self, queries, timeout)
resolver = Resolver(servers=[('10.0', 53)])
factory = server.DNSServerFactory(clients=[resolver])
protocol = dns.DNSDatagramProtocol(factory)
reactor.listenUDP(53, protocol, interface='127.0.0.1')
reactor.listenTCP(53, factory, interface='127.0.0.1')
reactor.run()
By posting your answer, you agree to the privacy policy and terms of service.
asked
3 years ago
viewed
9923 times
active | http://serverfault.com/questions/423882/configure-a-dns-server-per-nic-interface-eth0-eth1 | CC-MAIN-2016-30 | refinedweb | 683 | 68.77 |
This is a problem I encountered more than once, and today I finally found a "solution". I place "solution" in quotes because it's more of a workaround for something that seems to be a problem of the Python Windows installer.
I ran into the problem on a Windows 7 box running ActivePython 2.6, but according to this Python issue, others have encountered the problem with Windows XP and Python 3.x as well.
The problem manifests itself as follows. Prepare a simple script containing:
import sys print sys.argv
Execute it from the command-line:
C:\>python z.py 1 2 3 ['z.py', '1', '2', '3']
This looks right. But now execute it without prepending python:
C:\>z.py 1 2 3 ['C:\\z.py']
What gives? Doesn't the installer configure .py files to be run by the Python executable correctly, passing arguments to it as one would expect?
Now, I found a couple of non-solutions. The most popular was to setup the association with the assoc and ftype commands, as follows:
C:\>ftype Python26.File="C:\Python26\python.exe" "%1" %* C:\>assoc .py=Python26.File
But at no avail, the problem persisted.
What eventually solved it is fixing the relevant registry keys for Python. I set the HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command key to:
"C:\Python26\python26.exe" "%1" %*
Previously, %* was missing. Similarly, I set HKEY_CLASSES_ROOT\py_auto_file\shell\open\command to the same value. You can also set it accordingly for python26w.exe (the no-shell version of Python on Windows).
This worked, and now I got:
C:\>z.py 1 2 3 ['C:\\z.py', '1', '2', '3']
What causes the problem? In all likeness the ActivePython 2.6 installer, which doesn't set up the registry keys correctly. Now, this may not always happen, and some discussions point to it being dependent on other factors. For instance, I had another version of Python already installed on the machine when I executed the installer - this may have confused it. | http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/ | CC-MAIN-2017-09 | refinedweb | 338 | 70.9 |
Ext JS to React: Static and Config MembersJavaScript
This is part of the Ext JS to React blog series.
In the previous blog in this series, we looked at how to define classes with React. In this blog post, we’ll expand upon that by looking at adding static members to a class. Also, Ext JS has a special config system. It automatically generates getter and setter methods for config options defined in the class
config block. We’ll explore how to accomplish the same end goal within React.
Note: While not a requirement for React, this article’s code examples assume you’re starting with a starter app generated by create-react-app.
Statics
A static member can be a property or method and is used to retrieve information or handle something without creating an instance of the class the statics are defined on. These members belong to the class they are defined on. In fact, JavaScript itself has static members on its classes like Date’s parse method. You use this method like:
var milliseconds = Date.parse('Jan 1, 2017');
This static method will take in the date string, parse it, and return the number of milliseconds since the epoch. The static method is a handy mechanism to have versus having to create an instance and execute a function:
var milliseconds = new Date('Jan 1, 2017').getTime();
Ext JS statics
Ext JS classes can also define static members while using
Ext.define, but you must nest these members within the
statics object:
Ext.define('MyError', { statics : { codes : { NO_NETWORK : 1, SAVE_ERROR : 2, NO_PERMISSION : 3 }, fromAjax : function (response, doThrow) { var error; var hasErrors; // hasErrors = true; // uncomment to spoof a 404; if (hasErrors || response.status === 404) { error = new MyError({ code : MyError.codes.NO_NETWORK, text : response.statusText }); } if (doThrow) { throw error; } return error; } } }); Ext.define('Foo', { doSomething : function () { return Ext.Ajax .request({ url : '/foo' }) .then(this.handleAjax) .catch(function (response) { MyError.fromAjax(response, true); }); } }); var instance = new Foo(); instance .doSomething() .catch(console.log);
In this example, we have a
MyError class that holds a static
codes object. It allows easy code lookup and a method that can handle common errors from an ajax request.
React statics defined
We can create a simple example with React classes. The MyError class would be defined as:
export default class MyError { static codes = { NO_NETWORK: 1, SAVE_ERROR: 2, NO_PERMISSION: 3 } constructor(config) { Object.assign(this, config); } static fromAjax(response, doThrow) { let error; let hasErrors; // hasErrors = true; // uncomment to spoof a 404 if (hasErrors || response.status === 404) { error = new MyError({ code: MyError.codes.NO_NETWORK, text: response.statusText }); } if (doThrow) { throw error; } return error; } }
Using React statics
The Foo class has an asynchronous action called during its construction:
import React, { Component } from 'react'; import MyError from './MyError'; class Foo extends Component { constructor(props) { super(props); fetch('/foo') .then(response => { MyError.fromAjax(response, true); }) .catch(a => { // handle error here }); } render() { return ( <div>Hello there</div> ); } } export default Foo;
With ES2015, to define a member as static, you define it like you would a regular member. You need to prefix the member with the
static keyword. Note that the static keyword is a more modern inclusion in the JavaScript language and doesn’t have support across all browsers / browser versions. A transpiler such as Babel aims to rescue you from legacy JavaScript dependency and will handle the normalization of code using newer conventions such as the
static keyword within legacy browsers. If your application is created using Create React App much of the transpiling is taken care of for you behind the scenes (including the handling of
static).
Creating an instance of Foo in our application is very straightforward:
import React from 'react'; import Foo from './Foo'; export default() => <Foo />;
Note: For those not starting with create-react-app you can make use of the class properties Babel plugin.
Configs
As it evolved, Ext JS grew to include a way to define configurations for classes and manage the getting and setting of those configs. When you define a config within a
config: {} block, Ext JS will create getter and setter functions for you automatically. The getter function simply returns the underlying property that is used to store the value of the config. The setter sets the property but also calls an applier and updater function to allow the class to transform and/or react to the config being set.
Ext JS configs
An example of this would look like:
Ext.define('MyApp.view.Main', { config : { foo : 'bar' }, constructor: function (config) { this.initConfig(config); }, applyFoo : function (foo) { return Ext.Array.from(foo); }, updateFoo : function (foo, oldFoo) { // react to foo change } });
Configurations go within the
config object, which will kick off the getter and setter method generation upon class instantiation. The instance will then have
getFoo and
setFoo methods that should be used instead of direct property access. The
applyFoo method will be called by the generated
setFoo method to transform the value as needed. In this case we attempt to normalize the value passed to
setFoo into an array. The
updateFoo may be used to react to the
foo value change in order to do things like update the DOM or another instance property. You would use the getter and setter like:
var instance = new MyApp.view.Main(), value = instance.getFoo(); // would be [ 'bar' ] instance.setFoo('foobar'); value = instance.getFoo(); // would be [ 'foobar' ]
React configs
React doesn’t require a config system like Ext JS does. We will just use native JavaScript. We can actually use the properties without the need to execute a method in our code. For example, this class defines a getter and setter:
export default class Foo { constructor(config) { Object.assign(this, config); } get foo() { return this._foo; } set foo(foo = []) { if (foo && !Array.isArray(foo)) { foo = [foo]; } this._foo = foo; // react to foo change } }
As you can see, this native JavaScript version is pretty similar to the Ext JS equivalent except we don’t have to define the
config object. In order for this setter to have the same applier / updater hooks as Ext JS you can include one of two things. You can call separate before (applier) and after (updater) methods from within the setter. Or, you can integrate the applier / updater logic within the setter code itself. You would use the getter and setter a bit differently by accessing and setting the property directly instead of executing methods:
const instance = new Foo({ foo : 'bar' }); let value = instance.foo; console.log('value', value); // value [ 'bar' ] instance.foo = 'foobar'; value = instance.foo; console.log('value', value); // value [ 'foobar' ]
Using properties directly instead of executing methods feels a bit more intuitive and natural. Also, since it’s all native JavaScript, performance will be better. If the same was done using Ext JS, generated getter and setter methods would be introduced on class instantiation. If you liked the separate applier/updater methods that are executed, there is nothing stopping you from executing these in your setter.
Conclusion
Ext JS has one of the most powerful JavaScript class systems, but breaking it down begins to show you can accomplish the same thing with JavaScript alone. Statics and the config system is something that is utilized heavily within Ext JS and can be used in applications. Thankfully, the same thing can be done when transitioning to React. Stay tuned for the next blog post where we’ll take a look at how React enables the sharing of methods and properties between different classes! | https://moduscreate.com/blog/ext-js-react-static-config-members/ | CC-MAIN-2018-09 | refinedweb | 1,242 | 56.25 |
Investors in Flowserve Corp (Symbol: FLS) saw new options become available today, for the September 18th expiration. At Stock Options Channel, our YieldBoost formula has looked up and down the FLS options chain for the new September 18th contracts and identified one put and one call contract of particular interest.
The put contract at the $30.00 strike price has a current bid of $2.35. If an investor was to sell-to-open that put contract, they are committing to purchase the stock at $30.00, but will also collect the premium, putting the cost basis of the shares at $27.65 (before broker commissions). To an investor already interested in purchasing shares of FLS, that could represent an attractive alternative to paying $30.70 100%. Stock Options Channel will track those odds over time to see how they change, publishing a chart of those numbers on our website under the contract detail page for this contract. Should the contract expire worthless, the premium would represent a 7.83% return on the cash commitment, or 44.67% annualized — at Stock Options Channel we call this the YieldBoost.
Below is a chart showing the trailing twelve month trading history for Flowserve Corp, and highlighting in green where the $30.00 strike is located relative to that history:
Turning to the calls side of the option chain, the call contract at the $35.00 strike price has a current bid of $1.20. If an investor was to purchase shares of FLS stock at the current price level of $30.70/share, and then sell-to-open that call contract as a "covered call," they are committing to sell the stock at $35.00. Considering the call seller will also collect the premium, that would drive a total return (excluding dividends, if any) of 17.92% if the stock gets called away at the September 18th expiration (before broker commissions). Of course, a lot of upside could potentially be left on the table if FLS shares really soar, which is why looking at the trailing twelve month trading history for Flowserve Corp, as well as studying the business fundamentals becomes important. Below is a chart showing FLS's trailing twelve month trading history, with the $35.00 strike highlighted in red:
Considering the fact that the $35.00.91% boost of extra return to the investor, or 22.29% annualized, which we refer to as the YieldBoost.
Meanwhile, we calculate the actual trailing twelve month volatility (considering the last 252 trading day closing values as well as today's price of $30.70) to be 60%.. | https://www.nasdaq.com/articles/interesting-fls-put-and-call-options-for-september-18th-2020-07-16 | CC-MAIN-2021-43 | refinedweb | 435 | 63.9 |
A:
#include <stdio.h>
int main(void)
{ printf("hello"); return 0; }
with gcc -Wall -o hello hello.c. Run the exectable with strace hello. Are
you impressed? Every line you see corresponds to a system call. strace[1][2].:
# ls -l /dev/hda[1-3]
brw-rw---- 1 root disk 3, 1 Jul 5 2000 /dev/hda1
brw-rw---- 1 root disk 3, 2 Jul 5 2000 /dev/hda2
brw-rw---- 1 root disk 3, 3 Jul 5 2000 /dev/hda3):
crw-rw---- 1 root dial 4, 64 Feb 18 23:34 /dev/ttyS0
crw-r----- 1 root dial 4, 65 Nov 17 10:26 /dev/ttyS1
crw-rw---- 1 root dial 4, 66 Jul 5 2000 /dev/ttyS2
crw-rw---- 1 root dial 4, 67 Jul 5 2000 /dev/ttyS3:
% ls -l /dev/fd0 /dev/fd0u1680
brwxrwxrwx 1 root floppy 2, 0 Jul 5 2000 /dev/fd0
brw-rw---- 1 root floppy 2, 44 Jul 5 2000 /dev/fd0u1680.
It's an invaluable tool for
figuring out things like what files a program is trying to access. Ever have a program bail silently because it
couldn't find a file? It's a PITA!
I'm a physicist, not a computer scientist, Jim!
This isn't quite the same thing as `building all your modules into the kernel', although
the idea is the same. | https://www.linuxtopia.org/online_books/Linux_Kernel_Module_Programming_Guide/x431.html | CC-MAIN-2020-40 | refinedweb | 225 | 70.84 |
Swot analysis and company overview of starbucks
You are to imagine that you are the national Marketing Manager for a company that operates a chain of coffee shops. This can be any type of company from an established large multinational (i.e. Starbucks, Coffee Bean & Tea Leaf) to a small-medium enterprise (UK Based Costa Coffee) that manages coffee shops.
Your company has decided to launch a shop at the University of East Anglia.
The company’s Marketing Director has asked you to prepare a strategic marketing plan to “roll out” this new shop over the next five years
Introduction
In 1998, Starbucks successfully entered the European market through an acquisition strategy (Starbucks, 2011 p.1). Since then, Starbucks has gone on to become the market leader in the UK branded coffee shop market (CatererSearch, 2011 p.1); and their carefully planned strategy has resulted in high levels of customer loyalty which leave the competition far behind. Starbucks pride themselves on quality, and, this is something, which is inspired by passion. The firm are passionate about ethically sourcing the finest coffee beans, and this is something, which is translated into the company’s mission statement. A strong response to the firm’s external environment provides the firm with a competitive advantage, in that they are a firm, which are highly responsive to the changing needs of their consumers. This is supported by an adaptive and response approach to change, which sees the firm being able to set trends in their environment. Thus, it can be seen that the firm support a gradualist model of change (Gersick, 1999 p.101) and this is a strategy, which further promotes an integrated marketing mix.
In addition, the firm can be seen to have strong links to their customers, and follow a vigorous customer relationship management programme. A sense of belonging is felt within the stores, and an atmosphere is created in which consumers feel they can relax and take a break from the outside world. Thus, as Starbucks (2011 p.1) note ‘every store is part of a wider community’, and in this sense it can be seen that the firm promote corporate social responsibility activities in order to bring together the firm’s partners, customers and the community. This in turn must therefore be reflected wherever the firm chooses to locate. This paper will conduct an industry analysis of the coffee sector within the UK, once this has been established, it will move on to look specifically at the strength and weaknesses of Starbucks, noting the intangible capabilities of the firm which contribute to a unique competitive advantage (Henry, 2007 p.42). Secondly, the paper will move on to produce a strategic marketing plan, which on the basis of solid marketing objectives will seek to provide a comprehensive overview of how Starbucks can successfully launch a store at East Anglia University.
Industry analysis
PEST analysis
Political
Relationships between coffee producing nations and the government. Pressure to provide a fair price to producers.
State and legal controls.
Economic
UK coffee market is set to double in size over the next decade (Manson, 2007 p.1).
Annual worth of £1.3bn this reflects a 15% growth rate.
International coffee prices are dropping.
Oversupply of coffee production.
Social
11 million consumers visiting a coffee shop at least once a week (Manson, 2007 p.1).
The coffee shop is becoming a social gathering location.
Social concerns over fair-trade and fair price coffee. Consumers are demanding more from retailers.
Consumer preferences may change over time. Starbucks must review the external environment.
Technological
Technology to improve overall operational efficiencies.
Use of IT for ordering systems
Developments in technology facilitate quicker service in store.
SWOT analysis of Starbucks
Strengths
Very profitable organisation, average revenue of $5000million each year.
Global coffee brand with a large customer base. This customer loyalty enables the firm to gain customers regardless of location.
Listed in the top 100 companies to work for.
Strong commitment to CSR and the firm’s stakeholders.
Instantly recognizable brand.
Weaknesses
New product development, focus on both innovation and creativity. For example; as well as staple items the firm invent new drinks to entice customers.
Predominant focus in the USA thus a rather concentrated business risk.
Lack of diversification into other areas. This could lead the firm susceptible to moves from their competitors.
Opportunities
Further advancements of their Fair-trade products
Global expansion. In particular in BRICS economies such as China and India (Wilson and Purushothaman, 2003 p.19).
Co-branding, further development of their supermarket range.
Starbucks are noted as the favourite coffee shop amongst UK Retailers, the firm must draw on this success during a strategy of expansion (Manson, 2007 p.1).
Threats
The company are susceptible to a rise in cost of coffee, groups are pushing for a larger percentage of price to go to the producers of the coffee.
Rise in competition for example; McDonalds are now targeting a similar market to Starbucks.
Dynamic external environment and changing consumer needs, this therefore requires a flexible strategic focus.
Economic difficulties such as the most recent recession have resulted in customers tightening their belts. The consequence of which is consumers moving to cheaper alternatives or cutting back on luxuries such as takeaway coffee.
Market being taken up by non specialized players such as Marks and Spencer (Manson, 2007 p.1).
Characteristics of the product
The unique selling points of Starbucks products are that it is of the highest quality. Starbucks ensure they produce the highest quality coffee, and treat all products with great care. This results in a highly developed product, which, consumers enjoy. Furthermore, the product is one, which is developed with passion, and this is reflected in how Starbucks treat the product they are serving. In addition to the coffee being sold, Starbucks offer a variety of other products, which offer variety to the consumer. The wide range of goods on offer provides an additional unique selling point as consumers have a wide variety of choice. Furthermore, Starbucks have a unique approach to how they source their products, and have an ethical focus this is something which is line with changing consumer demands. Therefore, Starbucks are known as a sustainable company.
Marketing objectives
To develop a strong customer loyalty base within the University of East Anglia within the first year.
To promote a wider community involvement and become a central player in the community by 2012.
To develop a market share within the University of 30% by 2012.
To develop products, which are in line with different seasons and changing student, tastes.
To create a location on campus which promotes communication and socializing amongst both students and staff.
Demographic analysis – target market
Primary data was collected in the form of a questionnaire in order to gather opinions on the demographics of students at East Anglia, which would provide further information regarding the target market of the firm. The questionnaire results highlighted that the main customers are student’s aged 18-21 and staff members who go to get coffee in between lessons. The results showed that people purchase coffee to socialize, and this is something, which Starbucks must promote through the atmosphere they create in store. In addition, the results highlighted that it is predominately females who visit Starbucks and it is females who purchase the non-traditional drinks such as Frappuccino’s and Iced Tea. Therefore, demographically it was males who purchased traditional drinks such as coffee and tea. Furthermore it can be expected that all those visiting the on campus Starbucks will be in some way associated with the University, therefore, it is unlikely that members of the public will use the branch if it is located on the university campus. Therefore, it may be more beneficial for the company to locate near to the university but in a location, which is accessible to the general public. This will in turn boost the atmosphere of the store as different communities will combine, and it will also ensure that Starbucks are able to maintain their revenue even during quiet university times, for example; during the summer holidays.
The primary data has therefore promoted that the following marketing plan to be targeted towards female students aged18-22. In addition, it projected an image of such female students drinking non-conventional drinks and therefore, as the store is planned to launch in the spring, it is expected that the store should launch a variety of seasonal drinks in line with changing consumer needs.
Marketing strategy
4p’s of marketing
Product
High quality coffee with a unique twist. For example; gingerbread lattes, chai tea lattes. Taking coffee and giving it a modern and contemporary twist.
Alternatives to coffee and tea such as Frappuccino’s and Iced tea. In the summer these will be high sellers. Such products will change seasonally and will provide incentives for students to try new products in store.
Price
Prices are standardized across the majority of Starbucks branches (exc airports and train stations). Starbucks recognise that students do not have the highest budgets however and will therefore aim to have a promotion each week, which, highlights one choice of drink at a reduced price. Furthermore, an equivalent to a ‘happy hour’ will take place during quiet hours in the day (2:30-4pm) in which, offers will be run.
Place
Staff will be presented in the traditional Starbucks uniform and will conform to the American culture in which smiles and a friendly attitude are the norm. This promotes the idea that Starbucks should be somewhere where the customer feels welcome.
The stores will be comfortable and modern. Comfy seats will be provided and window bars will be placed so that consumers can people watch whilst they sip their coffee. Throughout the stores free Wi-Fi will be offered enabling students to work in groups within store.
Promotion
Stores will be used to promote an atmosphere, which encourages socializing. Newspapers will be made available and different playlists will be used in order to allow the consumer to get involved with the choice of music. Furthermore, competitions will be used in which students will be given the chance to design their own summer drink. This will provide a great way of getting Starbucks recognised on campus, and will allow the firm to gain access to the creativity and ideas, which the students have.
The launch event will be one, which offers a fun opportunity for students to learn more about coffee, sample goods and enter competitions to win gift cards etc. This will attract attention towards the opening and will provide Starbucks with the chance to showcase their arrival.
Customer relationship management strategy
Customer relationship management is vitally important (Reinartz et al, 2004 p.293) and is something, which is gaining increased attention in the academic and professional literature. An understanding of how to manage customer relationships can provide the key to gaining a competitive advantage and thus, this is something, which Starbucks must aim to maintain in order to remain market leader (Porter, 1998 p.19). Different customers have different value to the firm, and most importantly different customers can be seen to have subjective individual perceptions. Thus, Starbucks must recognise that customer satisfaction is subjective, and often difficult to measure. However, one way to gain access to customer information is to offer a programme of feedback in which, customers are given the option to offer their opinion on Starbucks. This will enable Starbucks to improve based on such points, and overall could see the firm experiencing higher levels of overall satisfaction (Kamakura et al, 2002 p.295). In addition to such, customer relationship management can be promoted by using social media/marketing to communicate with consumers. Thus, it is expected that Starbucks will provide links to their websites and will extend their Facebook page to have one unique to the campus store. The use of a loyalty card in store will also promote good customer relationship management, and such a strategy will enable Starbucks to gain access to information, which could provide them with information, which will further contribute to a competitive advantage.
Marketing communication activities
As previously mentioned, social marketing is gaining in popularity and is a method of communicating to a wide number of consumers in an effective and cheap manner. However, in addition experiential marketing will be used, which is a new development in marketing which aims to get the customer to form an emotional attachment to the brand (Schmitt, 1999 p. 11). Therefore, Starbucks will offer events, which allow the customer to connect with the brand, for example; trying out the product and attending events, which have been organized by Starbucks. As well as creating an emotional attachment, which is noted in the literature as being linked to customer loyalty, this enables the firm to develop a community spirit within the area.
Resource plan
The key resource needed to bring the marketing plan to life is staff. Staff need to be treated as an intangible capability, and a capability witch can provide the firm with a competitive advantage. If customers feel happy and welcome when in a Starbucks branch they are more likely to return (Dick and Basu, 1994 p.100). Furthermore, financial resources will be needed in order to ensure that the stores are delivered to a high specification. Thus, it is important that money is spent on comfortable seating and lounging areas to provide an atmosphere, which encourages relaxing. As a final point, expenditure must be spent on staff training, this will ensure that high quality coffee is produced, and that staff have all the necessary skills needed to facilitate it. As noted by Hayes (2007 p.12) it is important workers are skilled when dealing with new innovations.
Monitoring and control activities
A system of monitoring and control is vital to this operation. Starbucks must ensure that feedback communication channels are in place in order to allow the firm to grow and improve. If students are not visiting the brand despite extensive marketing then the firm needs to know why and seek to improve this. During any marketing activities, monitoring must take place to gain customer information, tastes, and desires. By directly communicating with the consumers, the firm will be able to carry out their own personal market research. This is in line with Henry (2007 p.36) who notes that a firm must be aware of their external environment in order to be competitive. To operate in a manner, which is not aligned to customer preferences, is to operate dangerously.
Conclusions
In line with the marketing objectives laid out, it can be seen that Starbucks are set to open a branch on the University campus. This will provide the firm with access to a large target market and will enable the firm to gain a presence and a relationship with the University. Community is a key word, and it is important that Starbucks quickly place themselves as a member of the community. Launch events and the inclusion of students will help them to do this. Furthermore, the products offered, although relatively standardized will be slightly altered to meet customer desires. For example; seasonal menus and new drinks to entice customers in. Integrated marketing is important, and in this manner, the 4p’s of marketing have been carefully presented in order to ensure that every action Starbucks do as part of their marketing strategy is one, which promotes one clear message to the consumer.
Request Removal
If you are the original writer of this essay and no longer wish to have the essay published on the UK Essays website then please click on the link below to request removal:
Request the removal of this essay | http://www.ukessays.com/essays/marketing/swot-analysis-and-company-overview-of-starbucks-marketing-essay.php | CC-MAIN-2014-42 | refinedweb | 2,619 | 52.49 |
Python Password Generator
Learn how to create a random password generator in Python.
We know that passwords are a real security threat. To keep your account safe and prevent your password from being hacked you have to make your password hard enough that nobody can guess.
Keeping you updated with latest technology trends, Join DataFlair on Telegram
Password Generator
It is a tool that generates passwords based on the given guidelines that you set to create an unpredictable strong password for your accounts.
The Password generator tool creates a random and customized password for users that helps them to create a strong password which provides greater security.
Password Generator Python Project
The objective of this project is to create a password generator using python. The password generator project will be build using python modules like Tkinter, random, string, pyperclip.
In this project, the user has to select the password length and then click on the “Generate Password” button. It will show the generated password below. If the user clicks on the “Copy To Clipboard” button, then it will copy the password automatically.
Project Prerequisites
To build this project we will use the basic concept of python and libraries – Tkinter, pyperclip, random, string.
- Tkinter is a standard GUI library and is one of the easiest ways to build a GUI application.
- pyperclip module allows us to copy and paste text to and from the clipboard to your computer
- The random module can generate random numbers
- string module contains a number of functions to process the standard python string.
To install the libraries we can use pip installer from the command line:
pip install tkinter pip install pyperclip pip install random pip install strings
Download Project Code
Download the source code of the password generator project: Python Password Generator
Project File Structure
Let’s check the step to build a Password Generator using Python
- Import modules
- Initialized Window
- Select Password Length
- Define Functions
Steps to create random password generator
1. Import Libraries
The first step is to import libraries
from tkinter import * import random, string import pyperclip
2. Initialize Window
root = Tk() root.geometry("400x400") root.resizable(0,0) root.title("DataFlair - PASSWORD GENERATOR")
- Tk() initialized tkinter which means window created
- geometry() set the width and height of the window
- resizable(0,0) set the fixed size of the window
- title() set the title of the window
Label(root, text = 'PASSWORD GENERATOR' , font ='arial 15 bold').pack() Label(root, text ='DataFlair', font ='arial 15 bold').pack(side = BOTTOM)
Label() widget use to display one or more than one line of text that users can’t able to modify.
- root is the name which we refer to our window
- text which we display on the label
- font in which the text is written
- pack organized widget in block
3. Select Password Length
pass_label = Label(root, text = 'PASSWORD LENGTH', font = 'arial 10 bold').pack() pass_len = IntVar() length = Spinbox(root, from_ = 8, to_ = 32 , textvariable = pass_len , width = 15).pack()
- pass_len is an integer type variable that stores the length of a password.
- To select the password length we use Spinbox() widget.
- Spinbox() widget is used to select from a fixed number of values. Here the value from 8 to 32
4. Function to Generate Password
pass_str = StringVar() def Generator(): password = '' for x in range (0,4): Password = random.choice(string.ascii_uppercase) + random.choice(string.ascii_lowercase) + random.choice(string.digits) + random.choice(string.punctuation) for y in range(pass_len.get()- 4): password = password + random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.punctuation) pass_str.set(password)
- pass_str is a string type variable that stores the generated password
- password = “” is the empty string
- First loop will generate a string of length 4 which is a combination of an uppercase letter, a lowercase letter, digits, and a special symbol and that string will store in password variable.
- The second loop will generate a random string of length entered by the user – 4 and add to the password variable. Here we minus 4 to the length of the user because we already generate the string of length 4.
We have done this because we want a password which must contain an uppercase, a lowercase, a digit, and a special symbol.
Now the password is set to the pass_str() variable.
Button(root, text = "GENERATE PASSWORD" , command = Generator ).pack(pady= 5) Entry(root , textvariable = pass_str).pack()
- Button() widget used to display button on our window
- command is called when the button is click
- Entry() widget used to create an input text field
- textvariable used to retrieve the current text to the entry widget
5. Function to Copy Password
def Copy_password(): pyperclip.copy(pass_str.get()) Button(root, text = 'COPY TO CLIPBOARD', command = Copy_password).pack(pady=5)
pyperclip.copy() used to copy the text to clipboard
Python Password Generator Output
Summary
With these steps, we have successfully created a random password generator project using python. We used popular tkinter library to rendering graphics in our display window and we also learned about pyperclip and random library.
We learned how to create buttons, input textfield, labels, and spinbox. In this way, we successfully created our password generator python project. Hope you enjoyed it. | https://data-flair.training/blogs/python-password-generator/ | CC-MAIN-2020-45 | refinedweb | 859 | 52.9 |
RIF example UC9: BPEL Orchestration of Rule-Based Web Services
Kindly send comments on this page to GaryHallmark
Contents
- RIF example UC9: BPEL Orchestration of Rule-Based Web Services
- Summary
- Background
- Source data and rules
- Translation of PR with only assert actions into RIF Core
- Issues
- Changes
Summary
This use case is about rules that score a credit report represented as an XML document.
The source rules are production rules (PR) with actions other than assert, suggesting that we invent a PR dialect that extends RIF Core in order to translate these rules to RIF. It turns out that most of the rules can be restated as PR with only assert actions, and these restated PR can be translated to RIF Core augmented with aggregation. That is the route we will take.
We will express the translated rules in a "human readable" RIF because their elaboration as XML probably does not help understand the key issues of mapping production rules to RIF at this point.
Background
Use case BPEL Orchestration of Rule-Based Web Services is about rules that score a credit report represented as an XML document. The sources are provided as Oracle Rule Language (RL), a production rule language with its roots in CLIPS but with a more modern Java-like syntax. (Note that business users do not program in RL directly.)
The use case is loosely based on a commercial credit application.
Source data and rules
The actual application has about 100 rules. Each rule interprets one or a few credit report attributes, and typically increments an overall credit score variable. We show just a fragment of the credit report document, and a redacted ruleset in RL containing the definition of the credit score variable, a variable indicating whether credit is approved, and two rules with priorities.
RL relies on the Java API for XML Binding (JAXB) to translate XML schema to Java classes, and to translate XML instance documents to Java objects.
First we show the "original" ruleset in RL (before transforming to assert actions).
JAXB processing of credit report schema
The schema of a simple credit report document such as the following
<credit-report> <name>Joe Slacker</name> <ssn>923764388</ssn> <income>45000</income> ... </credit-report>
results in a Java class such as the following
class CreditReport { String name; String ssn; BigDecimal income; }
Original production rules
The following RL ruleset then references the credit report
ruleset creditScoring { int score = 0; boolean approved = false; rule r1 { // If applicant's income is between 40000 and 50000 then add 40 priority = 1; if (fact CreditReport cr && cr.income > 40000 && cr.income <= 50000) { score += 40; } } rule r2 { // approve if total score is over 300 priority = 0; // must execute after the scoring rules if (true) { approved = score > 300; } } }
Production rules using assert actions and aggregation
The above can be rewritten to use only assert actions and aggregation:
ruleset creditScoring2 { class ScoreIncrement { int value; } class Approved {} rule r1 { // If applicant's income is between 40000 and 50000 then add 40 if (fact CreditReport cr && cr.income > 40000 && cr.income <= 50000) { assert(new ScoreIncrement(value: 40)); } } rule r2 { // approve if total score is over 300 if (aggregate (fact ScoreIncrement si) : sum(si.value) score && score > 300) { assert(new Approved()); } } }
Translation of PR with only assert actions into RIF Core
The following translation assumes the following
- frame syntax for translating Java and RL class references
xpath builtins differentiated from logical functions with preceding '&'
- a new SUM builtin that can perform closed-world aggregation
- rules with no universally quantified variables do not need an enclosing "forall"
ScoreIncrement[value->40] :- Exists ?income ( And ( CreditReport[income->?income] &numeric-greater-than(?income 40000) &numeric-greater-than(50000 ?income) )) Approved[] :- Exists ?increment ?score ( And ( ScoreIncrement[value->?increment] ?score = &SUM(?increment) &numeric-greater-then(?score 300) ))
Issues
A few issues with the above translation are worth disussion.
Naming
How do we attach the ruleset and rule names? There is no place in the ASN or concrete syntax at present.
I don't know what to do about namespace prefixes in the human-readable syntax. I omitted them.
Datatypes
Literals such as 300 and 40000 are not tagged as 300^^int or 40000^^BigDecimal. Is this required?
Builtins and ordering of conjuncts
Order matters. CreditReport[income->?income] must come before &numeric-greater-than(?income 40000) so that ?income is bound.
Aggregation
Adding &SUM is easy syntactically, but the semantics are non-monotonic. How do we extend Core semantics to support aggregation?
Translation of arbitrary PR
Neither r1 nor r2 from the original creditScoring ruleset has a head (neither rule asserts a fact into working memory). R2 doesn't even have a body. How can these actions be expressed?
A notion of priority is needed because r2 must execute after r1 in order to read the total score.
Changes
GaryHallmark rewrote most of this page on June 22, 2007 to rephrase as PR with assert actions and aggregation and to use the "latest" Core syntax (not all approved) | http://www.w3.org/2005/rules/wg/wiki/UC9_Worked_Example.html | CC-MAIN-2013-48 | refinedweb | 827 | 53.21 |
How to replace intrementally?
I have a question, I’m a noob, and don’t know anything about programming. How can I lets say replace numbers from “x” to “y” in fours?
I want to edit unix times from 1588384800 to 1588393920 and change the date to the next day. And each column contains 4 of the same unix time.
I may not be realistically possible without programming, but your description cries out for posting a short sample of the data as well…
@Alan-Kilborn There are thousand of timestamps like this and want to change them to the current day always.
"timestamp": 1588464027, }, { "timestamp": 1588464027, }, { "timestamp": 1588464027, }, { "timestamp": 1588464027, }, { "timestamp": 1588464052, }, { "timestamp": 1588464052, }, { "timestamp": 1588464052, }, { "timestamp": 1588464052,
What comes immediately to my mind are questions like
Current day but keeping time?
Current day and current time?
Current day and fixed other time?
@Ekopalypse These are I believe times from 05. 03. 02:00 to 04:32. I want to change them to 05. 04. 02:00 to 04:32. I don’t need a program or anything just how can I do them manually? They increment in 25.
those timestamp look like unix timestamps, if this is the case then you can simply add 86400 seconds to it.
@Ekopalypse How can I highlight all of them, there are 1500 timestamps, 4 of each and they are similar til 1588. But I’m an idiot of not thinking adding 86400, this was a big help already and gave me some ideas.
If you only want to highlight them then use
find dialog, goto mark tab, use the following regex
\d{10}
check regular expression in search mode and press mark all
@Ekopalypse This is great, and how can I add 86400 to all of them? :’)
because you said
I don’t need a program or anything just how can I do them manually?
the obvious answer would be by typing in the sum of the existing value
and 86400 but I get the impression that you want to do something
slightly different. I assume you want to select all timestamp
instances and then automatically add 86400 to them, correct?
If so, then you need some kind of script/program. If not, then
I still haven’t understood how you want to change these timestamps.
@Ekopalypse Yes that’s correct, I thought it would be easy, now I have every timestamp selected and I thought with the replace or Column Editor I can add 86400 to all of them.
@Levente-Horváth What if I do Find What: \d{10}, and Replace With: \d{10}+86400
No, you do not have it selected, you just highlighted it, this is different and no, regex is not a calculator.
If you have to do such things more often then I would recommend to
install one of the scripting plugins like PythonScript, LuaScript and create
a little script to do this for you.
If you want to go that way we certainly can give you help solving this.
@Levente-Horváth said in How to replace intrementally?:
Replace With: \d{10}+86400
I thought @Ekopalypse makes it clear above that things DO NOT work that way.
@Ekopalypse Then I will do it that way, whatever it takes.
So you are going to install, e.g. PythonScript plugin via the plugin admin?
If yes, what should the script do? Just add one day aka 86400 seconds?
Or more flexible like you’ve been asked to enter the seconds you want to add?
@Ekopalypse I just want to add 86400 to the existing numbers.
ok, once you installed PythonScript, goto plugins->Python Script->New Script
give it a meaningful name and save it.
Paste the following into the newly create document and save it.
from Npp import editor def add_a_day(m): return int(m.group(0)) + 86400 editor.rereplace('\d{10}', add_a_day)
Goto to plugin->Python Script->Scripts and execute your newly created script.
If you want to add it to the toolbar play with the configuration menu of pythonscript.
@Ekopalypse said in How to replace intrementally?:
editor.rereplace(’\d{10}’, add_a_day)
Perhaps the OP’s data contains other 10 digit numbers, not related to timestamps??
I might go with this instead:
editor.rereplace('"timestamp": \K\d{10}', add_a_day)
Ensures that we are only changing the timestamp values.
@Alan-Kilborn No, it doesn’t contain any other 10 digit number, but I thank all of you, it works! | https://community.notepad-plus-plus.org/topic/19349/how-to-replace-intrementally | CC-MAIN-2021-17 | refinedweb | 740 | 73.68 |
src/examples/yang.c
Flow in a rotating bottom-driven cylindrical container
A cylindrical container is partially filled with liquid. The bottom disk spins at constant speed. A steady state is eventually reached for which the hydrostatic pressure due to the deformation of the free-surface balances the centrifugal force. This is analogous to the solid body rotation in “Newton’s bucket” but more complex due to the development of boundary layers and recirculations generated by the discontinuous velocity boundary condition between the rotating bottom disk and the stationary walls.
This example reproduces one of the cases studied by Wen Yang, 2018 in his PhD.
We use the two-phase axisymmetric Navier–Stokes solver with swirl.
#include "grid/multigrid.h" #include "axi.h" #include "navier-stokes/centered.h" #include "navier-stokes/swirl.h" #include "two-phase.h" #include "tension.h" #include "axistream.h" #include "view.h"
Boundary conditions
The left boundary is the “bottom” of the container. The azimuthal velocity component w on the bottom disk is \Omega r with the angular velocity \Omega = 1 and r = y.
u.t[left] = dirichlet(0); w[left] = dirichlet(y);
The “top” boundary is a no-slip stationary wall.
u.t[right] = dirichlet(0); w[right] = dirichlet(0);
The cylinder wall is also no-slip and stationary.
u.t[top] = dirichlet(0); w[top] = dirichlet(0);
Parameters
The independent parameters are the aspect ratio of the cylindrical container H/R (unity here), the aspect ratio of the fluid layer \displaystyle G = h/R the Froude number \displaystyle Fr = \frac{R\Omega^2}{g} with g the acceleration of gravity, the Reynolds number of the liquid \displaystyle Re = \frac{R^2\Omega}{\nu_l} the Weber number \displaystyle We = \frac{\rho_l\Omega^2R^3}{\sigma} the ratio of gas to liquid densities and dynamic viscosities \displaystyle \rho_r = \rho_g/\rho_l \displaystyle \mu_r = \mu_g/\mu_l The values correspond to those used by Yang for figure 5.9 in his PhD (see also p. 106).
double G = 0.25, Fr = 0.88, Re = 3063, We = 3153, rhor = 1.205/1.2107e3, mur = 18.2e-6/6.09e-2;
Setup
The domain is the square box of unit size (i.e. R = 1), and the angular velocity \Omega is one (see the boundary condition for w above). The gives the values for viscosities, densities and surface tension below. Note that surface tension is commented out since it has very little influence but slows down the calculation.
int main() { N = 128; mu1 = 1./Re; rho2 = rho1*rhor; mu2 = mu1*mur; // f.sigma = 1./We; DT = 0.1; run(); }
We add gravity (given by the Froude number).
event acceleration (i++) { face vector av = a; foreach_face(x) av.x[] -= 1./Fr; }
The initial interface is flat and positioned at z = RG.
event init (i = 0) { fraction (f, G - x); } #if 0 event snapshots (i += 100) { scalar psi[]; psi[left] = dirichlet (0); psi[right] = dirichlet (0); psi[top] = dirichlet (0); axistream (u, psi); dump(); } #endif
Results
We output the timestep, the total kinetic energy and the total mass.
event logfile (i += 10) { double ke = 0.; foreach (reduction(+:ke)) ke += dv()*rho(f[])*(sq(u.x[]) + sq(u.y[]) + sq(w[])); fprintf (stderr, "%g %g %g %g\n", t, dt, ke, statsf (f).sum); }
We make a movie of the streamlines and isolines of the azimuthal velocity component. They can be directly compared with figure 5.9 of Yang, 2018, reproduced below. Results are close but not identical.
Streamlines (left) and azimuthal velocity (right). Interface in red.
Streamlines and interface reproduced from Yang, 2018, Figure 5.9.
event movie (t += 1; t <= 300) { view (fov = 22.7232, quat = {0,0,-0.707,0.707}, tx = -0.12824, ty = -0.446981, width = 830, height = 432); box();
We compute the axisymmetric streamfunction \psi from the velocity components.
scalar psi[]; psi[left] = dirichlet (0); psi[right] = dirichlet (0); psi[top] = dirichlet (0); axistream (u, psi);
The values for the isolines are the same as in Yang, 2018, caption of Figure 5.9, p. 107.
squares ("psi", linear = true, spread = -1); isoline ("psi", n = 21, min = 0, max = 0.006); isoline ("psi", -0.0012, lc = {0,1,0}); draw_vof ("f", lc = {1,0,0}, lw = 2); translate (y = -1.15) { box(); squares ("w", linear = true, spread = -1); isoline ("w", n = 21, min = 0, max = 1); draw_vof ("f", lc = {1,0,0}, lw = 2); } save ("movie.mp4"); } #if 0 // TREE event adapt (i++) { adapt_wavelet ({u,w}, (double[]){1e-3,1e-3,1e-3}, minlevel = 5, maxlevel = 8); } #endif | http://basilisk.fr/src/examples/yang.c | CC-MAIN-2021-39 | refinedweb | 749 | 68.36 |
Overview of RST Types and Namespaces¶
The information on this page is outdated. Package descriptions can be found here
This page shall give a short summary of the stable RST Types and their semantic structuring into distinct namespaces. As such, it shall give component developers a brief overview of the overall library and describe the rationale behind the different namespaces. Ideally, parts of this page will be auto-generated in the future (cf. #630) from the respective type folder in the RST repository, which can also be accessed directly via the repository browser:
this page is work in progress
Rationale for Package Names¶
Geometry¶
Geometry is a branch of mathematics concerned with questions of shape, size, relative position of figures, and the properties of space. (source)Related:
Kinematics¶
Kinematics is the branch of classical mechanics that describes the motion of bodies (objects) and systems (groups of objects) without consideration of the forces that cause the motion. (source)
Dynamics¶
In the field of physics, the study of the causes of motion and changes in motion is dynamics. In other words the study of forces and why objects are in motion. Dynamics includes the study of the effect of torques on motion. (source)
Vision¶
In electrical engineering and computer science, image processing is any form of signal processing for which the input is an image (source)
Audition¶
Audio signal processing, sometimes referred to as audio processing, is the intentional alteration of auditory signals, or sound. (source)
Stochastics¶
The use of the term stochastic to mean based on the theory of probability (source)
Communication Patterns¶
Refers to additional prototypes for advanced communication patterns at the integration level such as the Task-State pattern.
The term was introduced (?) in Robotics in a paper by Christian Schlegel. We could cite this as a source here.
Related:
- ROS Action lib
TODO
- add related work for each namespace | https://code.cor-lab.de/projects/rst/wiki/Namespaces | CC-MAIN-2021-43 | refinedweb | 311 | 50.67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.