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
Combine Two Querysets in Django (with different models) Today, I stumbled upon a use case where I needed to have a querysets that had objects from different models. Django has a neat "contenttypes framework" which is a good way to achieve this. So here are my notes on what I learned today, and I hope it will help someone in the future. NOTE: If you can design your models from scratch this is not the best approach to follow. Read my note under step 5. The Models Let us consider the following models: class Bmw(models.Model): series = models.CharField(max_length=50) created = models.DateTimeField() class Meta: ordering = ['-created'] def __str__(self): return "{0} - {1}".format(self.series, self.created.date()) class Tesla(models.Model): series = models.CharField(max_length=50) created = models.DateTimeField() class Meta: ordering = ['-created'] def __str__(self): return "{0} - {1}".format(self.series, self.created.date()) The Queries We can get list of Bmw's and Teslas separatley like so >>> Bmw.objects.filter() [<Bmw: Bmw Series 1 - 2013-08-04>, <Bmw: Bmw Series 2 - 2010-01-15>] >>> Tesla.objects.filter() [<Tesla: Tesla Series 2 - 2015-03-29>, <Tesla: Tesla Series 1 - 2011-09-10>] But what if we want the two querysets combined, say we want to display all cars in our dealership page by creation date. So we want something like [<Car: Tesla Series 2 - 2015-03-29>, <Car: Bmw Series 1 - 2013-08-04>, <Car: Tesla Series 1 - 2011-09-10>, <Car: Bmw Series 2 - 2010-01-15>] How do we do that? Here are two viable approaches. Using Chain from itertools Using itertools chain is one approach. from itertools import chain def get_all_cars(): bmws = Bmw.objects.filter() teslas = Tesla.objects.filter() cars_list = sorted( chain(bmws, teslas), key=lambda car: car.created, reverse=True) return cars_list Here we get the queryset for Bmws and queryset of Teslas, and pass them to the chain function which combines these two iterables and makes a new iterator. We then pass this list to the sort function and specify that we want to sort it by the created date. Finally we say that we want the order to be reversed. Here is the result [<Tesla: Tesla Series 2 - 2015-03-29>, <Bmw: Bmw Series 1 - 2013-08-04>, <Tesla: Tesla Series 1 - 2011-09-10>, <Bmw: Bmw Series 2 - 2010-01-15>] This is a good approach if the queryset is small. However if we are dealing with larger querysets and need to involve pagination, every time we need to query the entire database and sort by the created date. Even if we slice the list, then we have to manually keep track of our slice index and created date for sorting, and the whole approach could get messy. The contenttypes Framework Django's contenttypes framework is really a good option for this use case. From the docs:. I would urge you to read up more on it Content Types in our models From the docs: Adding a foreign key from one of your own models to ContentType allows your model to effectively tie itself to another model class. So we add a new model to our models called car which uses the Generic Relations. class Car(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') created = models.DateTimeField() class Meta: ordering = ['-created'] def __str__(self): return "{0} - {1}".format(self.content_object.series, self.created.date()) We then update our models and define a post save handler. def create_car(sender, instance, created, **kwargs): """ Post save handler to create/update car instances when Bmw or Tesla is created/updated """ content_type = ContentType.objects.get_for_model(instance) try: car= Car.objects.get(content_type=content_type, object_id=instance.id) except Car.DoesNotExist: car = Car(content_type=content_type, object_id=instance.id) car.created = instance.created car.series = instance.series car.save() And we add the post save handler to our Tesla model. class Tesla(models.Model): series = models.CharField(max_length=50) created = models.DateTimeField() class Meta: ordering = ['-created'] def __str__(self): return "{0} - {1}".format(self.series, self.created.date()) post_save.connect(create_car, sender=Tesla) (and similarly added for Bmw model not show for brevity) So now every time an instance of Tesla or Bmw is created or updated, the corresponding Car model instance gets updated. Query using contenttypes framework Here is an updated query using the contentypes framework that we just set up. Notice how we have both Bmw and Tesla objects returned as Car instances. >>> Car.objects.filter() [<Car: Tesla Series 2 - 2015-03-29>, <Car: Bmw Series 1 - 2013-08-04>, <Car: Tesla Series 1 - 2011-09-10>, <Car: Bmw Series 2 - 2010-01-15>] Here we have returned car objects, so here is how we get to the actual car type a Car instance holds. >>> car = Car.objects.first() >>> car.content_object <Tesla: Tesla Series 2 - 2015-03-29> >>> car.content_object.series u'Tesla Series 2' Closing Notes Although this approach has an overhead of an extra table, for larger query sets I fell this is a cleaner approach. Let me know what you think or if you have any questions in the comments below.
https://howchoo.com/g/yzzkodmzzmj/combine-two-querysets-with-different-models
CC-MAIN-2019-39
refinedweb
855
57.37
In this guide we will observe one of Java's most dangerous vulnerabilities, CVE-2012-1723. We will analyze the conditions of the vulnerability and work through an example of practical exploitation through a drive-by attack. About the Vulnerability This vulnerability was identified in early 2012 before being widely exploited via the Blackhole Exploit Kit in July. Java 7u4 and earlier, Java 6u32 and earlier, Java 5u35 and earlier, and Java 1.4.2_37 and earlier are all vulnerable to this exploit. The exploit allows for sandbox escape and remote code execution on any target with a vulnerable JRE. I'm choosing CVE-2012-1723 for my first installment of this "Practice the Past" series because its a personal favorite of mine. While it is widely patched and has been acknowledged for almost 5 years, developing an exploit for this vulnerability touches on a wide array of invaluable topics. We will explore some of the inner workings of the JVM and package it all together in one of cyber-history's most lethal attack vectors. How it Works CVE-2012-1723 is a field access vulnerability that can lead to type confusion. When a pointer to an object of Type A exists in memory it is very important for security that this object is always of Type A. In order to enforce this, programming languages deploy type safety. In Java, types are recorded by associating a class tag with each object in memory. Static type verification is static analysis that occurs before code is run by working through the control flow. Dynamic type verification occurs during runtime and is inherently inefficient. Java relies almost entirely on complex static type safety and it analyses control flow when classes and methods are loaded by HotSpot. Static type safety saves us time but if it fails then type confusion can occur. As we will soon see, an attacker can benefit greatly from changing the type of an object in memory. In our implementation of this exploit we are going to take advantage of type confusing a ClassLoader object! So how does CVE-2012-1723 give us type confusion? Well, HotSpot has a variety of optimizations and caching procedures for JIT compilation. One of these involved multiple references to the same field in a single method. Upon investigating a GETSTATIC, PUTSTATIC, GETFIELD, or PUTFIELD instruction, HotSpot will verify the type and cache it. If there is a second field access instruction referring to the same field, its verification is pulled from cache and this particular instruction goes unchecked. We will be using the specific combination of GETSTATIC and PUTFIELD to type confuse a static object. Step 1: Forcing JIT Compilation We want to make sure the method that exploits the vulnerability is JIT compiled right before it executes. This way, HotSpot will perform the caching that was described. To do this, we are going to include a condition at the very beginning of the method that will potentially skip the rest of the method, with the exploit occurring immediately after the initial break. By calling the method many times in a way that satisfies the "skip" condition, we force the method to be JIT compiled when we eventually break past the condition. Since we are type confusing a ClassLoader, lets make the method take a ClassLoader instance and return an EvilClassLoader instance. We will avoid the vulnerability until the argument is not null. public class Confuser { public EvilClassLoader confuse(ClassLoader passedCL) { if (passedCL == null) return null; // Insert Vulnerability } } Next up we want to cause the confusion from our main class. Since this will be a drive-by attack, let's make the main class an Applet and confuse the compiler from the start() method. public class DriveBy extends Applet { static EvilClassLoader appletCL; @Override public void start() { try { Confuser confuser = new Confuser(); for (int i = 0; i < 100000; i++) confuser.confuse(null); Thread.sleep(1000); appletCL = confuser.confuse(getClass().getClassLoader()); EvilClassLoader.escapeSandbox(); } catch (Exception e) { } } } We have now succesfully forced the confuse method to be JIT compiled when we assign it to appletCL. The EvilClassLoader class will be written soon, but first lets get low-level and look at the heart of the vulnerability! Step 2: Implement Type Confusion To begin, lets add a static ClassLoader reference to our Confuser class. Since the static reference has to be legitimately verified once, lets call it with an assignment to a local variable in our confuse method. public class Confuser { private static ClassLoader confuserCL; public EvilClassLoader confuse(ClassLoader passedCL) { if (passedCL == null) return null; ClassLoader localCL = confuserCL; } } The local assignment gives us the GETSTATIC instruction, but to complete the vulnerability we need a PUTFIELD instruction too. But PUTFIELD is for instance data, so we can't just write this line in Java and compile it. Instead we are going to have to write a partially correct line that will compile and go in afterward to change the bytecode. So, as a placeholder we add the line: this.confuserCL = passedCL; Since confuserCL is static, referencing it from "this" looks peculiar. We do this because it will successfully compile, and adds an instruction to the bytecode that we will need later. As it stands, this method will generate the following bytecode: 0: aload_1 1: ifnonnull 6 4: aconst_null 5: areturn 6: getstatic #2 // Field confuserCL:Ljava/lang/ClassLoader; 9: astore_2 10: aload_0 11: pop 12: aload_1 13: putstatic #2 // Field confuserCL:Ljava/lang/ClassLoader; The first 6 bytes (0-5) are the skip condition, where ALOAD_1 pushes the method's argument onto the stack to be checked for null equivalence. Bytes 6-9 use GETSTATIC to assign our static ClassLoader to a local variable (ASTORE_2). After that are the two bytes generated by our unnecessary call to "this". The compiler loads "this" onto the stack with ALOAD_0 (an objects instance is often, but not always, the very first variable on the method's heap) and then just pops it off as it was not needed. Then the last two bytes load the method's argument onto the stack and put it into our static variable. So, we have a GETSTATIC that gets verified and a PUTSTATIC that goes unchecked. We want to change that PUTSTATIC into a PUTFIELD. But before we manipulate the bytecode, lets talk about what that implies. In the versions of Java aflicted with this vulnerability, static variables and instance variables are NOT stored in the same heaps of memory. In fact, static fields stay in the chunk of memory that the class and method is loaded into (called permanent generation), while instance fields go where their object goes (the young generation). This is efficient because objects share method code and static variables (hence the permanent generation is loaded once), and only their instance data is unique to their existence (which is loaded per instance). So if we send our ClassLoader object into the instance field, we have to be sure that the offset we pass it (which is the static field's offset) is valid. Luckily enough, the offsets for static variables in the permanent generation start higher than the offsets of the instance variables due to there being more metadata about the class than each object. So, by changing our PUTSTATIC instruction to PUTFIELD we can be sure that our ClassLoader will land on a valid offset assuming we make the instance memory large enough. To do this we must pad our object with a bunch of EvilClassLoader fields. In this example we will only need ~30, but depending on the complexity of the object executing the exploit, it will be greater. And since our ClassLoader will be type confused into one of these fields, we want our method to return whatever field it landed in. public class Confuser { private static ClassLoader confuserCL; public EvilClassLoader e00, e01, e02, e03, e04, e05, e06, e07, e08, e09; public EvilClassLoader e10, e11, e12, e13, e14, e15, e16, e17, e18, e19; public EvilClassLoader e20, e21, e22, e23, e24, e25, e26, e27, e28, e29; public EvilClassLoader confuse(ClassLoader passedCL) { if (passedCL == null) return null; ClassLoader localCL = confuserCL; this.confuserCL = passedCL; if (this.e00 != null) return this.e00; if (this.e01 != null) return this.e01; if (this.e02 != null) return this.e02; if (this.e03 != null) return this.e03; if (this.e04 != null) return this.e04; if (this.e05 != null) return this.e05; if (this.e06 != null) return this.e06; if (this.e07 != null) return this.e07; if (this.e08 != null) return this.e08; if (this.e09 != null) return this.e09; if (this.e10 != null) return this.e10; if (this.e11 != null) return this.e11; if (this.e12 != null) return this.e12; if (this.e13 != null) return this.e13; if (this.e14 != null) return this.e14; if (this.e15 != null) return this.e15; if (this.e16 != null) return this.e16; if (this.e17 != null) return this.e17; if (this.e18 != null) return this.e18; if (this.e19 != null) return this.e19; if (this.e20 != null) return this.e20; if (this.e21 != null) return this.e21; if (this.e22 != null) return this.e22; if (this.e23 != null) return this.e23; if (this.e24 != null) return this.e24; if (this.e25 != null) return this.e25; if (this.e26 != null) return this.e26; if (this.e27 != null) return this.e27; if (this.e28 != null) return this.e28; if (this.e29 != null) return this.e29; return null; } } So now, all we have to do is change the bytecode. Lets compile the class javac Confuser.java and inspect it with javap. javap -v Confuser.class When you scroll up to the confuse method, you will see the instructions we discussed earlier. Now lets open up the class file in a hex editor. Since we are interested in the PUTSTATIC instruction, lets search for the surrounding series of instructions ALOAD_0, POP, ALOAD_1, and PUTSTATIC. This translates to 2A572BB3 (). We want to change the B3 to B5 (PUTFIELD) and the 57 to 00 (POP to NOP). The reason for changing the POP is because we actually need the object instance (which was loaded by ALOAD_0) on the stack in order to properly call PUTFIELD. The useless reference to "this" earlier has conveniently put the instruction in place. After saving, the confuser class is complete! It will reliably exploit CVE-2012-1723 and type swap a ClassLoader into an EvilClassLoader. Step 3: Escalating our Privilege Now we need to implement an EvilClassLoader class that extends ClassLoader and contains a static method to break out of our JVM sandbox. Since Classloaders are responsible for assigning permissions when they load classes, let's use ours to manually load a Payload class with all permissions! We will do this by mimicking the usual process but including our own certificates and permissions. import java.io.InputStream; import java.security.AllPermission; import java.security.CodeSource; import java.security.Permissions; import java.security.ProtectionDomain; import java.security.cert.Certificate; public class EvilClassLoader extends ClassLoader { public static void escapeSandbox() throws Exception { InputStream in = DriveBy.appletCL.getResourceAsStream("Payload.class"); int classSize = in.available(); byte[] classBytes = new byte[classSize]; in.read(classBytes); Certificate[] certs = new Certificate[0]; CodeSource source = new CodeSource(null, certs); Permissions permissions = new Permissions(); // The Holy Grail of JVM exploitation! permissions.add(new AllPermission()); ProtectionDomain protectionDomain = new ProtectionDomain(source, permissions); Class payloadClass = DriveBy.appletCL.defineClass("Payload", classBytes, 0, classBytes.length, protectionDomain); Payload payload = (Payload) payloadClass.newInstance(); } } Step 4: Design a Payload The best way that I've found to design a payload for privileged classes is by implementing a PrivilegedExceptionAction and nuking the JVM SecurityManager immediately. For this example we'll just open up a command prompt as proof of concept. import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; public class Payload implements PrivilegedExceptionAction { public Payload() { try { AccessController.doPrivileged(this); } catch (PrivilegedActionException e) { e.printStackTrace(); } } @Override public Object run() throws Exception { System.setSecurityManager(null); Runtime.getRuntime().exec("cmd.exe /c start"); return null; } } Step 5: Package the Applet for a Drive-By So, now its time to compile our code. Make sure you don't overwrite your modified Confuser class! javac DriveBy.java Payload.java EvilClassLoader.java For a drive-by, we don't have to specify a manifest, so we can just package the jar without one. jar cvf exploit.jar *.class Finally, we just need to insert our applet in a webpage. <applet code="DriveBy.class" archive="exploit.jar"> Success! I sincerely hope you've enjoyed this first installment of Practice the Past! Project Code:
https://ethaniel.me/java/practice-the-past-cve-2012-1723
CC-MAIN-2019-04
refinedweb
2,078
59.7
Wraps RHS of a unary matrix operation. More... #include <MatVecOps.h> Wraps RHS of a unary matrix operation. The behavior of this class mirrors that of MatVecOp, refer there for a more complete description. This object grabs pointers to the lhs and rhs and sends them to the operator where the actual calculation gets performed. This object accepts a single object on the rhs. This object accepts two objects on the lhs. Definition at line 372 of file MatVecOps.h. Construct an object from a rhs consisting of a single matrix. Here we grab the pointer to the rhs element for use by the operator. Definition at line 386 of file MatVecOps.h. References SpatialOps::BinaryMatOp< OpT >::eval(). obtain a pointer to the multiple lhs and call the operator::launch method This is the interface for the lhs of the assignment operation. The pointers to the lhs and rhs operand are given to the operator using the OpT::launch method Definition at line 1201 of file MatVecOps.h.
https://software.crsim.utah.edu/jenkins/job/SpatialOps/doxygen/classSpatialOps_1_1BinaryRetMatUnaryOp.html
CC-MAIN-2017-47
refinedweb
168
58.89
fcSH4.0, XSH4.2, XSH5.0 fcntl(): XSH4.0, XSH4.2,XSH5.0, XNS4.0, XNS5.0. The standard allows for a list of variables, but does not specify them. These can vary with each vendor's implementation of this function. options. (That is, both file descriptors share the same file status options). The close-on-exec option (FD_CLOEXEC bit) associated with the new file descriptor is cleared so that the file will remain open across exec functions. Gets the value of the close-on-exec option associated with the file descriptor filedes. File descriptor options are associated with a single file descriptor and do not affect other file descriptors that refer to the same file. The argument parameter is ignored. Sets the close-on-exec option. [Tru64 UNIX] Retrieves the current times for the file identified by filedes. For the F_GETTIMES and F_SETTIMES requests, the function's third argument is a pointer to the struct attr_timbuf structure (defined in sys/fcntl1.h), which contains the file's atime (access time), mtime (modification time), and ctime (file attribute change time) values. These requests are useful for operations, such as backup and archiving, when it is necessary to save a file's current time values and then, after copying or moving the file, set back atime or mtime without changing ctime. [Tru64 UNIX] Sets the current times for the file identified by filedes. This request requires superuser privilege and returns the [EPERM] error on an attempt to set the file's times without this privilege. The following example illustrates how to use the F_GETTIMES and F_SETTIMES requests: # include <stdio.h> # include <sys/fcntl.h> # include <sys/fcntl1.h> main() { char buffer[1024]; int fd,bytesread; struct attr_timbuf tstamp; /* Create a file*/ fd=open("/usr/tmp/foo",O_CREAT|O_RDONLY); if(fd > 0) { /* Display the atime and ctime of the file */ printf("atime before reading the file:\n"); system("ls -lu /usr/tmp/foo"); printf("ctime before reading the file:\n"); system("ls -lc /usr/tmp/foo"); if(fcntl(fd,F_GETTIMES,&tstamp) < 0) { perror("fcntl:F_GETTIMES"); exit(1); } } else { perror("open"); exit(1); } printf("Sleeping for one minute because ls commands can \ show time change only in terms of hours and minutes...\n"); sleep(60); /* Access the file */ bytesread=read(fd,buffer,1024); if(bytesread >= 0) { /* Again display the atime and ctime of the file */ printf("\n\natime after reading the file:\n"); system( "ls -lu /usr/tmp/foo"); printf("ctime after reading the file:\n"); system( "ls -lc /usr/tmp/foo"); /* Now use F_SETTIMES to reinstate the original atime */ if(fcntl(fd,F_SETTIMES,&tstamp) < 0) { perror("fcntl:F_SETTIMES"); exit(1); } else { printf("\n\nAfter using F_SETTIMES, atime is reset \ without affecting ctime\n"); printf("\tatime:\n"); system( "ls -lu /usr/tmp/foo"); printf("\tctime:\n"); system( "ls -lc /usr/tmp/foo"); } } else perror("read"); system("rm -rf /usr/tmp/foo"); } Gets the file status options and file access modes for the file referred to by the filedes parameter. The file access modes can be extracted by using the mask O_ACCMODE on the return value. File status options and file access modes are associated with the file description and do not affect other file descriptors that refer to the same file with different open file descriptions. The argument parameter is ignored. Sets the file status options to the argument parameter, taken as type int, for the file to which the filedes parameter refers. The file access mode is not changed. [XNS5.0] If filedes refers to a socket, gets the process or process group ID currently receiving SIGURG signals when out-of-band data is available. Positive values indicate a process ID; negative values, other than -1, indicate a process group ID. If filedes does not refer to a socket, the results are unknown. [XNS5.0]. If filedes does not refer to a socket, the results are unknown. ] Is used by the network lock daemon (rpc.lockd(8)) to communicate with the NFS server kernel to handle locks on the NFS files. [Tru64 UNIX]. An unlock (F_UNLCK) request in which l_len is nonzero and the offset of the last byte of the requested segment is the maximum value for an object of type off_t, when the process has an existing lock in which l_len is 0 and which includes the last byte of the requested segment, is treated as a request to unlock from the start of the requested segment with an l_len equal to 0. Otherwise, an unlock (F_UNLCK) request attempts to unlock only the requested file.]. AdvFS-only request Parameters [Toc] [Back] [Tru64 UNIX] The following values for the request parameter are available for AdvFS only, and relate to performing direct I/O. The arguments used with these request parameters are in the <fcntl.h> file. FCACHE is defined as zero to indicate that the file's cache policy is the file system's default cache policy. FDIRECTIO is defined as one to indicate that the file's cache policy is direct I/O. Gets the cache policy for the file, which is either direct I/O or caching. [Tru64 UNIX] The following value for the request parameter is valid only when the filedes parameter describes an AdvFS or UFS file. [Tru64 UNIX] The F_GETMAP request gets the sparseness map of the file referred to by the fildes parameter. The argument parameter, taken as a pointer to type struct extentmap, is filled in with data that describes the extent map of the file. Each map entry is declared as: struct extentmapentry { unsigned long offset; unsigned long size; }; struct extentmap { unsigned long arraysize; unsigned long numextents; unsigned long offset; struct extentmapentry *extent; }; The map returned by this function can be different from the actual number of extents (or their definition) when the file is being written. It is recommended that you use this function only on files that are not being written. [Tru64 UNIX]() function. [Tru64 UNIX]. [Tru64 UNIX]. [Tru64 UNIX]. [Tru64 UNIX] The F_ADVFS_OP request is used to perform operations on AdvFS files which do not have an analog on other file systems. The argument parameter is expected to be a pointer to an advfs_opT) and fcntl(oldfiledes, F_DUPFD, newfiledes). Upon successful completion, the value returned depends on the value of the request parameter as follows: Returns a new file descriptor. Returns FD_CLOEXEC or 0 (zero). Returns a value other than -1. Returns the value of file status options and access modes. (The return value will not be negative.) Returns a value other than -1. Returns a value other than -1. Returns a value other than -1. [XNS5.0] Returns the value of the socket owner process or process group; this will not be -1. [XNS5.0] Returns a value other than -1. Returns a value other than -1. [Tru64 UNIX] Returns a value other than -1. [Tru64 UNIX] Returns a value other than -1. [Tru64 UNIX] Returns a value other than -1. [Tru64 UNIX]. [Tru64 UNIX] The request parameter is F_GETMAP and the filedes parameter does not point to an open file descriptor of an AdvFS or UFS file. The request parameter is F_SETLK or F_SETLKW, the type of lock (l_type) is a shared lock (F_RDLCK), and filedes is not a valid file descriptor open for reading. The type of lock (l_type) is an exclusive lock (F_WRLCK), and filedes is not a valid file descriptor open for writing. The request parameter is F_SETLKW, the lock is blocked by some lock from another process and putting the calling process to sleep, and waiting for that lock to become free would cause a deadlock. The argument parameter is an invalid address. The request parameter is F_DUPFD and the argument parameter is negative or greater than or equal to OPEN_MAX. [Tru64 UNIX] Either the OPEN_MAX value or the per-process soft descriptor limit is checked. An illegal value was provided for the request parameter. The request parameter is F_GETLK, F_SETLK, or F_SETLKW and the data pointed to by argument is invalid, or filedes refers to a file that does not support locking. [Tru64 UNIX] The F_ADVFS_OP request was performed and the fd referred to a socket; or the action was ADVFS_GET_INFO and the info_buf_size was zero; or the operation to be performed was undefined; or the action to be taken was undefined. The request parameter is F_DUPFD and too many or OPEN_MAX file descriptors are currently open in the calling process, or no file descriptors greater than or equal to argument are available. [Tru64 UNIX] Either the OPEN_MAX value or the per-process soft descriptor limit is checked. One of the values to be returned cannot be represented correctly. The request argument is F_BETLK, F_SETLK, or F_SETLKW and the smallest or, if l_len is nonzero, the largest offset of any byte in the requested segment cannot be represented correctly in an object of type off_t. [Tru64 UNIX] The value of the request parameter is F_SETOWN and the process ID given as argument is not in use. The request parameter is F_SETLKW and the fcntl() function was interrupted by a signal which was caught. [Tru64 UNIX] The request parameter is F_GETMAP and an I/O error occurred on the disk where the file is located. The request parameter is F_SETLK or F_SETLKW and satisfying the lock or unlock request would exceed the configurable system limit of NLOCK_RECORD. [Tru64 UNIX] The file is an NFS file, and either the client or server system is not running rpc.lockd, which is the NFS lock manager. [Tru64 UNIX] The system was unable to allocate kernel memory for the requested file descriptor. [Tru64 UNIX] The request parameter is F_SETOWN and the calling process does not have a controlling terminal, the file is not the controlling terminal, or the controlling terminal is no longer associated with the calling process' session. [Tru64 UNIX] The request parameter is F_SETOWN and the argument specified by the pgrp_id is valid, but matches a process ID or process group ID of a process in another session. [Tru64 UNIX] The request parameter is F_SETTIMES and the user does not have superuser privilege.. [Tru64 UNIX] Either the OPEN_MAX value or the per-process soft descriptor limit is checked. The dup2() function was interrupted by a signal which was caught. The number of file descriptors exceeds OPEN_MAX or the per-process limit, or there is no file descriptor above the value of the new parameter. [Tru64 UNIX] The file descriptor specified by filedes is on a remote machine and the link to that machine is no longer active. [Tru64 UNIX] The system was unable to allocate kernel memory for the requested file descriptor. Because in the future the variable errno is set to EAGAIN rather than EACCES when a section of a file is already locked by another process, portable application programs should expect and test for either value. Functions: close(2), creat(2), dup(2), exec(2), flock(2), fork(2), getdtablesize(2), open(2), pipe(2), read(2), truncate(2), write(2), lockf(3) Commands: rpc.lockd(8), rpc.statd(8) Standards: standards(5) Network Programmer's Guide fcntl(2)
http://nixdoc.net/man-pages/Tru64/man2/fcntl.2.html
CC-MAIN-2014-42
refinedweb
1,845
61.06
Questions Updated instead of making a new question… I really want to provide a few alternative languages other then English on my social network site I am building, this will be my first time doing any kind of language translation so please bear with me. I am researching so I am al ear and open to ideas and I have a lot already here is are the questions. 1) What does i18n mean, I see it often when researching language translation on SO? 2) Most people say use gettext PHP has an extension or support for it, well I have been researching it and I have a basic understanding of it, as far as I can tell it is a lot of extra work to go this route, I mean coding my site to use it’s functions ie; _(‘hello world i’m in English for now’) or else gettext(‘hello world i’m in English for now’) is no problem as any route I go will require that. But then you have to install gettext on your server and get it working, then use some special editors to create special files and compile them I think? Sounds like a pain, I understand this is supposed to be the best route to go though, well everyone seems to say it is. So can someone tell me why this is the route to go? 3) I really like the simplicity of this approach, just building a language array and calling the phrase you need in a function like the example below , you would then just include a file with the appropriate language array. What I really want to know is, would this be the less better performance method on a high traffic and fairly large site compared to using gettext and if so can you explain why please? <?PHP //Have seperate language files for each language I add, this would be english file function lang($phrase){ static $lang = array( 'NO_PHOTO' => 'No photo\'s available', 'NEW_MEMBER' => 'This user is new' ); return $lang[$phrase]; } //Then in application where there is text from the site and not from users I would do something like this echo lang('NO_PHOTO'); // No photo's available would show here ?> * some code used from brianreavis’s answer below Don’t reinvent the wheel. Use for example gettext or Zend_Translate. It’d probably be best to define a function that handles your language mapping. That way, if you do want to change how it works later, you’re not forced to scour hundreds of scripts for cases where you used $lang[...] and replace them with something else. Something like this would work and would be nice & fast: function lang($phrase){ static $lang = array( 'NO_PHOTO' => 'No photo\'s available', 'NEW_MEMBER' => 'This user is new' ); return $lang[$phrase]; } Make sure the array is declared static inside the function so it doesn’t get reallocated each time the function is called. This is especially important when $lang is really large. To use it: echo lang('NO_PHOTO'); For handling multiple languages, just have this function defined in multiple files (like en.php, fr.php, etc) and require() the appropriate one for the user. This might work better: function _L($phrase){ static $_L = array( 'NO_PHOTO' => 'No photo\'s available', 'NEW_MEMBER' => 'This user is new' ); return (!array_key_exists($phrase,$_L)) ? $phrase : $_L[$phrase]; } Thats what i use for now. If the language is not found, it will return the phrase, instead of an error. You should note that an array can contain no more than ~65500 items. Should be enough but well, just saying. Here’s some code that i use to check for the user’s language: <?php function setSessionLanguageToDefault() { $ip=$_SERVER['REMOTE_ADDR']; $url=''.$ip; $data=file_get_contents($url); $s=explode (':',$data); $s2=explode('(',$s[1]); $country=str_replace(')','',substr($s2[1], 0, 3)); if ($country=='us') { $country='en'; } $country=strtolower(ereg_replace("[^A-Za-z0-9]", "", $country )); $_SESSION["_LANGUAGE"]=$country; } if (!isset($_SESSION["_LANGUAGE"])) { setSessionLanguageToDefault(); } if (file_exists(APP_DIR.'/language/'.$_SESSION["_LANGUAGE"].'.php')) { include(APP_DIR.'/language/'.$_SESSION["_LANGUAGE"].'.php'); } else { include(APP_DIR.'/language/'.DEFAULT_LANG.'.php'); } ?> Its not done yet, but well i think this might help a lot. Don’t write your own language framework. Use gettext. PHP has standard bindings that you can install. As the other answers don’t really answer all the questions, I will go for that in my answer plus offering a sensible alternative. 1) I18n is short for Internationalization and has some similarities to I-eighteen-n. 2) In my honest opinion gettext is a waste of time. 3) Your approach looks good. What you should look for are language variables. The WoltLab Community Framework 2.0 implements a two-way language system. For once there are language variables that are saved in database and inside a template one only uses the name of the variable which will then be replaced with the content of the variable in the current language (if available). The second part of the system provides a way to save user generated content in multiple languages (input in multiple languages required). Basically you have the interface text that is defined by the developer and the content that is defined by the user. The multilingual text of the content is saved in language variables and the name of the language variable is then used as value for the text field in the specific content table (as single-language contents are also possible). The structure of the WCF is sadly in a way that reusing code outside of the framework is very difficult but you can use it as inspiration. The scope of the system depends solely on what you want to achieve with your site. If it is going to be big than you should definitely take a look at the WCF system. If it’s small a few dedicated language files (de.php, en.php, etc), from which the correct one for the current language is included, will do. Unfortunately gettext not work good and have problems in various situation like on different OS (Windows or Linux) and make it work is very difficult. In addition it require you set lot’s of environment variables and domains and this not have any sense. If a developer want simply get the translation of a text he should only set the .mo file path and get the translation with one function like translate(“hello”,”en_EN”); With gettext this is not possible. why not you just make it as multi-dimesional array…such as this <?php $lang = array( 'EN'=> array( 'NO_PHOTO'=>'No photo\'s avaiable', 'NEW_MEMBER'=>'This user is new', ), 'MY'=> array( 'NO_PHOTO'=>'Tiada gambar', 'NEW_MEMBER'=>'Ini adalah pengguna baru', ) ); ?>
https://exceptionshub.com/most-efficient-way-to-do-language-file-in-php.html
CC-MAIN-2017-51
refinedweb
1,109
60.75
resize mdiArea with Mainwindow I have a Main Window with an top dock. In design mode i added an mdiArea. on main.cpp i maximize my windown with : w.showFullScreen(); I now want the mdiArea to be also fullscreen under the top dock. I tried lots of different solutions, but i dont get the mdiArea to scale with the size of the mainwindow --sorry for my crappy english - SGaist Lifetime Qt Champion Hi and welcome to devnet, Did you set your mdiArea as central widget of QMainWindow ? Yes i set the mdiArea as centralWidget here is the full code of my main.cpp : [code] int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.showFullScreen(); QMdiArea *mdiArea =w.findChild<QMdiArea*>("mdiArea"); w.setCentralWidget(mdiArea); w.show(); return a.exec(); } [/code] Why are you setting it like this ? You should do it directly in MainWindow's constructor Because i'm new to QT and don't now how to do it proper. Could you give me an example on how to do this ? Just take a look at QMainWindow's documentation and the MainWindow Application Example I took a look on the documentation and now set everythin up correct, but i still dont get the mdiarea scaled out The program now is fullscreen. But i want it to be the same size as the Programm. Is the mdiArea empty ? If empty means, that ther is no mdi window inside, then yes. the program should start with an empty full screen mid area and then all needed windows should be chosen with the menu Can you show your MainWindow constructor ? Als elements has been created with the designer This is my Mainwindow.ccp #include "mainwindow.h" #include "ui_mainwindow.h" #include <QApplication> #include <QMdiSubWindow> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); //showMaximized(); showFullScreen(); setCentralWidget(ui->mdiArea); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_actionBeenden_triggered() { QApplication::quit(); } and this is the Mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT void createChild(); public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_actionBeenden_triggered(); void on_actionFader_triggered(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H [edit: Fixed coding tags, use three backticks SGaist] In that case, why don't you put the mdiArea directly as central widget with designer ? I have the auto created QWidget , auto named central widget. For this i have selected vertical layout. Below the QWidget i have the mdiArea. How can i change this ? Or is that correct ? Add mdiArea to the vertical layout and you should be good to go. I think that is what i done, but it still desn't work So what you want is to put all layout margins at 0 so your mdiArea widget will take the whole place I have done that, but the mdi area still does not scale out The question is going to be silly but did you just put it over the QMainWindow or did you explicitly clicked the layout vertically menu entry ? i clicked the vertical layout manualy on the central widget. Also i cant put the mdi area over it. What do you mean by you can't put the mdi area over it ? I thougt i could mabey drag'n drop it Here are all stepps i have done Create Project with Widget Created a mdiArea with designer try to resize with code QWidget or QMainWindow ? In any case, you only need to put the QMdiArea in a layout on the widget Its a QT Widged Application So i think it auto creates a MainWindow ?? I set the layout to vertical (see pictures in last postes) MainWindow can be a QMainWindow or a QWidget depending on what parameter you choose
https://forum.qt.io/topic/60264/resize-mdiarea-with-mainwindow/?page=1
CC-MAIN-2019-30
refinedweb
626
62.88
The Domain Model as REST Anti-pattern The Domain Model as REST Anti-pattern Join the DZone community and get the full member experience.Join For Free How to Transform Your Business in the Digital Age: Learn how organizations are re-architecting their integration strategy with data-driven app integration for true digital transformation. Today JavaLobby published yet anotherdomain-model-as-RESTarticle, using Spring and Jersey. As already pointed out, this really is an anti-pattern, and is not RESTful, and cannot be so either. The point that all of these types of articles miss is theHATEOASpart, the hyperlinking of resources. If you expose your domain model, basically saying "here's all I got, use as you see fit", there is no sensible way to create links between resources that expose the application state. There is no sensible way to tell the client "here's what you can do next", because the "REST" API allows anything at any time. Here's an example, from my own app, which showed me the problem with this approach. I have users in my system. I need two ways to work with their passwords: the user must be allowed to change his own password, and the administrator shall be allowed to reset any users' password. In the beginning, when I was exposing my domain model, the URL's for this were as follows: /user/<username>/changepassword/user/<username>/resetpassword I'm just doing what the article suggests, which is to expose my domain model, and all that I can do with it. What's the problem with this? The first and most obvious problem is that it's very hard to determine who is allowed to do what here. I need to have authorization checks on both "changepassword" and "resetpassword". The first needs to check if it is the same user that accesses it, and the second needs to check if the accessing user has the administrator role. Also, since the client MUST get to these resources by following links in hypermedia (that's a constraint, remember?), the most obvious thing to do is to list them when accessing /user/<username>/. But then my link lists need to do these authorization checks as well, because if the user is not an administrator, then the "resetpassword" link should not be there. I should not allow clients to see links they cannot reasonably follow! My UI will also be quite complicated, because in one screen I might do "resetpassword" and a number of other administrative tasks, each of which uses different parts of the domain model, and so its exposure to the API, and consequently, its brittleness if the API changes, is immense. It's just a very bad situation, and one which you'll get into by following the guidelines in all of these expose-your-domain-model articles. So what to do instead? The trick is to expose usecases instead. It's that simple. Now, the main problem with doing this is that you have to actually know what your usecases are! And this is probably why all of these articles do the domain-model anti-pattern: because of their simplified nature they only thought to the point of "we gotta have users in our system" and not take the next step "what can we do with them?", because then you need to decide a whole lot more about what your system does. Since articles need to be reasonably focused on one thing, they just don't go there. But for You, if you do that, you end up with the mess outlined above. What did we do in our REST API to fix the above? We simply looked at our usecases, and rearranged the REST API accordingly. For the above, they relate to two different usecases which are account handling and user administration. And so we changed the API to something like this: /account/changepassword/administration/users/<username>/resetpassword If a client goes to /account/, which it can do by first going to "/" and finding that link, it will receive a list of links with what you can do on your own account, such as "changepassword". Do a GET on that link, and the client gets a form with two fields: the old password and the new password. The client might show this as three fields though, with a duplicate new password field to ensure that the user typed it correctly. The client can then POST to "changepassword" to make the actual change. I don't have to make any authorization checks, since the client is implicitly accessing its own account, so there's no way to screw it up, even deliberately. For the admin side, the client browses to /administration/users/ (and again, that link was retrieved from "/" if the user is an administrator), lists/searches the users, gets the link to a particular user, do a GET on "resetpassword" to get the form for it, and then fills it in and POST it to make the change. The REST API has at all times told the client what it is allowed to do, by using hypertext to drive the application state. This is what HATEOAS means in practice, and it is VERY helpful if you expose your usecases, and VERY annoying if you expose your domain model (simply because you can't). This approach also removes the issue outlined in the article with circular references, simply because in usecases, there are no circular references. Another effect of this is that links in the REST API will almost always be relative, since all they do is guide the client further into a usecase, or sub-usecase. If you expose domain models you have to have absolute links, and they will be going here there and everywhere, exposing the internal associations between entities. It's stupid beyond belief, but this is what pretty much all of the current articles on "RESTful" frameworks tell you to do. And I say: DON'T! It'll only bring you misery. From a security point of view the above is also easier to work with. Now all I have to do is add a check on "/administration/" for the administrator role, and after that the user can do anything below that point. No need to duplicate that check everywhere (and no need to use aspects to get around this annoyance)! Now that you know what to do, the next question might be: how to do it? The problem here is that since all the current "REST" frameworks haven't thought HATEOAS through, they don't really allow you to make REST API's for your applications, and so, they will not be very easy to use. You have to work against them. This goes for Jersey and friends as well, as they don't allow this usecase approach to URL parsing. What we have done in my project, Streamflow, is to create our own wrapper on top ofRestlet. Restlet provides an excellent base for REST applications, but is too low-level to have to deal with in the application code. By putting a thin wrapper on top of it, which understand the notion of usecases and links, we have been able to really reduce the amount of code needed to do all of this. Here's sample code for "change password". The code uses a routing technique, so in order to get to /account/changepassword, the framework first takes "/" and finds a resource for that. This resource then knows how to get to "/account/", which in turn knows how to get to "changepassword". The code looks like this: public class RootResource extends CommandQueryResource{ @SubResource public void account() { subResource( AccountResource.class ); }...} When the client hits "/" the framework will automatically look at this class, and present hypermedia (JSON or HTML at this point, but Atom Services is also an option) for it. The client clicks "/account/", which leads to this: public class AccountResource extends CommandQueryResource{ public AccountResource( ) { super( AccountContext.class ); } @SubResource public void profile() { subResourceContexts( ProfileContext.class, ContactableContext.class ); }} To find out what the client can do on this level you look in AccountContext. If you want to continue further down into the profile handling of an account (setting email, phone, etc.) the client would follow "/account/profile/" link that is presented. In our case, let's look at AccountContext: public class AccountContext{ public void changepassword( ChangePasswordCommand newPassword ) throws WrongPasswordException { UserAuthentication user = RoleMap.role( UserAuthentication.class ); user.changePassword( newPassword.oldPassword().get(), newPassword .newPassword().get() ); }} It exposes one interaction on this level of the usecase, which is /account/changepassword. The parameter tells the framwork what it requires as input, so if the client does GET it can look at the ChangePasswordCommand value object and present it as a form. If the client does a POST the framework parses the input into the value object and invokes the method, allowing it to "do it's thing". In this case it looks up the UserAuthentication role, which is a Qi4j mixin that our user entity implements. This entity was registered automatically by the authentication filter, so I don't have to look it up. For the administration usecase the code would get access to the "<username>" part of the URL so that it can locate the user from the repository. And that's pretty much it. Not only is this easier to work with for clients (who simply follow links in hypermedia), but the code in both client and application is also absolutely trivial. I can also find out what my REST API looks like in total by starting with RootResource and explore the API by clicking on the classes it references. Since the API is so deterministic given these classes I can also generate documentation automatically that basically says, "given your user authorization level, here are all the resources you can access in the API". In particular, when your API becomes hypermedia driven like this, what you want to expose as documentation is the set of "rel" attributes that the client must know, in this case "account" and "changepassword". What the URL's look like is none of the clients business! It should just go to "/" and follow links based on the "rel" attribute of those links. Then you can say that your API is "RESTful". Until you do that, no, you may have a "web API" or a "HTTP API", but it aint REST. There are more details in how this works, and how to turn links on/off depending on internal state, but the gist of how to think is as above. From }}
https://dzone.com/articles/domain-model-rest-anti-pattern
CC-MAIN-2018-51
refinedweb
1,764
59.23
If you are a Tree Style Tab user and HATE seeing the tabs being displayed on top and left at same time: In a nutshell (on Windows) open a cmd prompt cd %APPDATA% cd Mozilla/Firefox/Profiles/ cd *** (whatever is named your profile.... no clue why they could not choose a fixed name...) mkdir chrome in this chrome folder, create a userChrome.css file with this content: @namespace url(""); /* to hide the native tabs */ #TabsToolbar { visibility: collapse; } /* to hide the sidebar header */ #sidebar-header { visibility: collapse; } and restart Firefox.... and pray that with next release they will not break everything again. For the time being I have disabled the automatic update of Firefox... In Linux, use about:config in the browser to find your Profile directory ( /home/centos/.mozilla/firefox/pmrfuuch.default in my case), then mkdir chrome etc etc. (see )
http://www.javamonamour.org/2017/11/firefox-57-and-tree-style-tabs-broken.html
CC-MAIN-2018-47
refinedweb
141
63.29
[Solved] Do I need to run Qt even loop (QApplication.exec()) to display QMessage::critical()? While this code seems to work. Is it correct? I thought that no Qt functinality would work if I didn't use a.exec(). @int main(int argc, char *argv[]) { QApplication a(argc, argv); try { MainWindow w; w.show(); return a.exec(); } catch (ExceptionInitialization& exception) { qDebug() << exception.getMessage(); QMessageBox::critical(nullptr, QObject::tr("ERROR"), exception.getMessage()); return (-1); } }@ - dheerendra Qt Champions 2017 Not required. It is dialog. Instead of passing nullptr, try passing 0. What is the issue you are facing ? It it not shown ? - JKSH Moderators Hi, [quote author="Zingam" date="1407675034"]While this code seems to work. Is it correct? I thought that no Qt functinality would work if I didn't use a.exec().[/quote]Yes, it's fine. exec() starts and event loop. Without it, you can't handle events and signals, but other things in Qt still work. (For example, even if I don't call exec() I can still use QFile to read/write files) Note that there are many ways to start an event loop: - QCoreApplication::exec() - QThread::exec() - QEventLoop::exec() - QDialog::exec() What Dheerendra meant is that QMessage::critical() calls QDialog::exec() internally, so you do get a running event loop until you close the dialog. [quote author="Dheerendra" date="1407677087"]Instead of passing nullptr, try passing 0.[/quote]Why? nullptr was invented specifically to avoid the ambiguity caused by passing 0. We should encourage each other to use C++11. - jazzycamel @ #include <QtGui/QApplication> #include <QtGui/QMessageBox> #include <exception> using namespace std; #if __cplusplus<201103L // naive C++11 support test #define nullptr 0 #endif class MyException: public exception { virtual const char *what() const throw(){ return "My Exception Happened"; } } myException; int main(int argc, char *argv[]) { QApplication a(argc, argv); try { throw myException; } catch(exception &e) { QMessageBox::critical(nullptr, "Exception!", e.what()); } } @ Works perfectly for me (Qt4.8) ;o) Thank you! I wasn't sure if the MessageBox would work without issues. I do a great deal of initialization in MainWindow like copying files, socket initialization, xml parsing, etc. And if some of this fails I need to warn the user and exit. So I assume my doubts are solved. Note: It's a C++11 app.
https://forum.qt.io/topic/44707/solved-do-i-need-to-run-qt-even-loop-qapplication-exec-40-41-to-display-qmessage-critical
CC-MAIN-2018-39
refinedweb
380
61.02
I've checked out other resources and haven't been able to find something helpful. But I'm attempting to figure out how to start loop increment at 0 instead of 1 for drawing the number inside the oval as shown below. I'd appreciate the help. My code: (Drawing Panel:) // Draws boxed ovals using a for loop. import java.awt.*; public class DrawLoopFor { public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(501, 251); panel.setBackground(Color.CYAN); Graphics g = panel.getGraphics(); int sizeX = 50; int sizeY = 25; for (int i = 0; i < 11; i++) { int cornerX = i*50; int cornerY = i*25; g.setColor(Color.WHITE); g.fillOval(cornerX + 5, cornerY + 5, sizeX-10, sizeY-10); g.setColor(Color.BLACK); g.drawString("" + i, cornerX - 28, cornerY - 8); g.setColor(Color.BLACK); g.drawRect(cornerX, cornerY, sizeX, sizeY); } } } You're drawing the text in the previous box rather than the current box. That's why the last box is empty, and the zero is drawn outside the visible screen. Most likely because you subtract 28 from cornerX when you draw. Try adding rather than subtracting. As I don't have your DrawingPanel class I can't confirm the exact offsets to cornerX and cornerY that you need, but I think you should use something like: g.drawString("" + i, cornerX + 22, cornerY + 17); (22 for the X coordinate, since you were drawing the start of the text 3 pixels before the middle of the box, and 25 - 3 = 22; 17 for the Y coordinate because the height is 25, and you were previously drawing the baseline of the text 8 higher than the end of the box, so 25 - 8 = 17)
https://codedump.io/share/hR5OkozDZPr2/1/java-loop-increment-not-starting-at-0
CC-MAIN-2017-30
refinedweb
282
63.19
1.1 anton 1: \ Etags support for GNU Forth. 2: 1.9 ! anton 3: \ Copyright (C) 1995,1998.8 pazsan 40: require search.fs 41: require extend.fs 1.7 pazsan 42: 1.1 anton 43: : tags-file-name ( -- c-addr u ) 44: \ for now I use just TAGS; this may become more flexible in the 45: \ future 46: s" TAGS" ; 47: 48: variable tags-file 0 tags-file ! 49: 50: create tags-line 128 chars allot 51: 52: : skip-tags ( file-id -- ) 53: \ reads in file until it finds the end or the loadfilename 54: drop ; 55: 56: : tags-file-id ( -- file-id ) 57: tags-file @ 0= if 58: tags-file-name w/o create-file throw 59: \ 2dup file-status 60: \ if \ the file does not exist 61: \ drop w/o create-file throw 62: \ else 63: \ drop r/w open-file throw 64: \ dup skip-tags 65: \ endif 66: tags-file ! 67: endif 68: tags-file @ ; 69: 70: 2variable last-loadfilename 0 0 last-loadfilename 2! 71: 72: : put-load-file-name ( file-id -- ) 73: >r 1.4 anton 74: sourcefilename last-loadfilename 2@ d<> 1.1 anton 75: if 76: #ff r@ emit-file throw 77: #lf r@ emit-file throw 1.4 anton 78: sourcefilename 2dup 1.1 anton 79: r@ write-file throw 80: last-loadfilename 2! 81: s" ,0" r@ write-line throw 82: endif 83: rdrop ; 84: 85: : put-tags-entry ( -- ) 86: \ write the entry for the last name to the TAGS file 87: \ if the input is from a file and it is not a local name 88: source-id dup 0<> swap -1 <> and \ input from a file 1.5 anton 89: current @ locals-list <> and \ not a local name 1.1 anton 90: last @ 0<> and \ not an anonymous (i.e. noname) header 91: if 92: tags-file-id >r 93: r@ put-load-file-name 94: source drop >in @ r@ write-file throw 95: 127 r@ emit-file throw 1.2 pazsan 96: bl r@ emit-file throw 1.1 anton 97: last @ name>string r@ write-file throw 1.2 pazsan 98: bl r@ emit-file throw 1.1 anton 99: 1 r@ emit-file throw 1.4 anton 100: base @ decimal sourceline# 0 <# #s #> r@ write-file throw base ! 1.1 anton 101: s" ,0" r@ write-line throw 102: \ the character position in the file; not strictly necessary AFAIK 103: \ instead of using 0, we could use file-position and subtract 104: \ the line length 105: rdrop 1.5 anton 106: endif ; 1.1 anton 107: 108: : (tags-header) ( -- ) 109: defers header 110: put-tags-entry ; 111: 112: ' (tags-header) IS header
http://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/etags.fs?annotate=1.9;sortby=log;f=h;only_with_tag=MAIN;ln=1
CC-MAIN-2021-17
refinedweb
447
82.04
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. get name of many2one field in sequence I have an object. I would like to define his by addind one of his many2one field name's (mission_id) and his sequence. So I write this code. but when create the objet i am getting the field (mission_id) id's numbre plus the object (mission_wave) sequence. How can i get mission_id name's instead of id? Thanks. class mission_wave(osv.osv): def create(self, vals): if vals.get('name', '/') == '/': vals['name'] = str(vals.get('mission_id') + str(self.env['ir.sequence'].get('hr.mission.wave')) return super(hr_mission_wave, self).create(vals) Hi, You can use the browse record, you can try something like: mission_name = self.pool['mission.class.name'].browse(vals.get('mission_id')).name vals['name'] = str(mission_name + str(self.env['ir.sequence'].get('hr.mission.wave')) hope this could helps Hi Ahmed, thanks for your answer. I try the code but get error. "TypeError: browse() takes at least 3 arguments (2 given)" Koffi, try self.env['mission.class.name'] instead of self.pool['mission.class.name'] Thanks it is working. About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/get-name-of-many2one-field-in-sequence-106871
CC-MAIN-2017-39
refinedweb
233
62.04
David Pratt wrote: > Hi. I am trying to get my head around using buildout with both private > and public repositories. So my questions relate to a way to organize my > svn in a better way for eggification and construction of a simple > sandbox to keep my svn checkouts together in a consistent and portable > way. The goal is to checkout sources, modifying and checking in my > changes as I go, and having the buildouts in their own folders reflect > the changing code and dependencies. > > My first couple of questions are whether buildout can use a folder as > source for a (development) egg - something that will update, Yes. (I wonder if I understand your question.) > secondly > whether an egg can be created with ssh to a private repository like: > > svn+ssh://myaccount@myrepo.example.com/usr/home/myaccount/svn/path > /to/my/project > > I have been using ssh for private code sources. Yes. You check out the projects you want to work on and then configure buildout to create develop eggs from them. The rule of thumb is, use develop eggs for checkouts. It doesn't matter if the checkouts are public or private. Note that you can also have private egg repositories using sftp. See: > In a recent buildout I have been studying, I have seen this: > > find-links = > > I am also looking at a simple sandbox structure that could also make > some sense ... > > development --+-- private-src (private checked out sources) > | > +-- public-src (external checked out sources) > | > +-- buildout (a container for my active buildouts) > > My source containers would just hold folders of checked out code I am > currently working on. I plan on checking out my buildouts from svn to a > buildout container so that I could have a few or more different > buildouts going at a time (each being an app or just testing some things > in their own environment) > > I am curious about folders as sources since sometimes I just want to try > some code without a lot of hassle or committing it to a repository right > away. I think it would be good to try it in a buildout. With the > structure of my development folder I could use a relative link from a > source folder as well. Note that I strongly prefer to keep buildouts self contained. Typically, for each package I work on, I make the svn project for that package a buildout. The buildout.cfg therefore usually has: develop = . I use eggs for everything else needed to work on the package. If, for some reason, I want to work on another package at the same time, I'll check that out into the working directory for the first project(or add an external) and add it to the list of develop eggs. > On the repository side, I have been looking at zope's repository more > critically which is structured like this: > > container-->branch-->src-->namespace-->package Right, where container == project > or when more nesting needed: > > container-->branch-->src-->namespace-->second namespace-->package > > setup.py is always at the branch with __init__ for eggs within each > namespace package. It seems a good model for eggification since many > packages are setup for eggs in a way that is fairly transparent. This of > course is a public repository with packages being registered in PyPI. The main downside of course, is all the nesting, which can get tedious. I wish I could think of a way to have namespace packages without creating all of the annoying subfolders. I may start omitting the src directory in some projects. I also think that it was a mistake to create the zc.recipe namespace packages. Rather than zc.recipe.foo, I should probably have done zc.foorecipe. I may switch to this in the future to reduce the nesting. > For a private repository, I would like to checkout the code as eggs > equally as well. Why not follow the same pattern as for public projects? I don't see why a project's structure should depend on whether it is public or private. Jim -- Jim Fulton mailto:jim at zope.com Python Powered! CTO (540) 361-1714 Zope Corporation
https://mail.python.org/pipermail/distutils-sig/2006-November/006983.html
CC-MAIN-2014-15
refinedweb
688
63.49
Asked by: Getting Report Server WMI Provider error: Invalid namespace -SharePoint integration I get the following during sharepoint reporting services configuration. noticed in denali reporting services config tool the db is in native mode and i believe this is the cause that sharepoint is throwing the WMI errror but there is no option to create a new database in "Integrated" mode in reporting services config tool. when choose a excisting db with "Integrated mode" it pops a message to select a db in native mode and doesn't let sharepoint integrated mode. any idea what i am missing? shivMonday, September 05, 2011 2:17 AM Question All replies Reporting Services in Denali is a SharePoint shared service. Do not use the old RS config tool for configuration, instead create a new SQL Reporting Services Application in SharePoint Central Administration –> Application Management –> Service Applications –> Manage Service Applications and create a new SQL Server Reporting Services Application. Please read this documentation page, specifically the section about "Create a Reporting Services Service Application" near the bottom: These blog posts may also be useful: * * HTH, Robert Robert Bruckner This posting is provided "AS IS" with no warranties, and confers no rights.Monday, September 05, 2011 5:02 AMOwner Robert, i am new to sharepoint reporting and not sure whether i am missing anything basic. yes, i had followed those articles during installation. by "do not use old RS config" tool. do you mean SQL 2008r2 config tool? no, i am not using it. i using the denali reporting config tool. also, on the sharepoint side. the central administration sql reporting integration is needed right? the SSRS service application that i created is showing a status of "stopped" and they is no way to start it? thanks s shivMonday, September 05, 2011 6:45 PM By the old tool he means the Reporting Services Configuration Manager that you find under Start Menu\Programs\Microsoft SQL Server Denali CTP3\Configuration tools, you can't use that tool to configure the Reporting Services Sharepoint Mode in Denali. To the second question , the Section SQL Server Reporting Services (2008 and 2008 R2) on Central Admin under General Application Settings (where I guess you mention the Reporting Services Integration link) is just for SQL 2008 and 2008R2 , RS Denali doesn't use that page or settings, those are just for back compatibility. As Robert mentions if you follow the steps you will see there is not mention to the RS Config Tool neither the Reporting Services Integration link in Central Admin. Regards -JaimeThursday, September 22, 2011 9:00 PM
https://social.msdn.microsoft.com/Forums/en-US/c69975a7-3c3c-4ee3-9e36-b2c9870cdf71/getting-report-server-wmi-provider-error-invalid-namespace-sharepoint-integration?forum=sqldenreportingservices
CC-MAIN-2017-09
refinedweb
430
50.16
ZerynthApp Library¶ This module provides access to the Zerynth App functionalities. The Zerynth App is an innovative mobile app designed to make interaction with Zerynth programs easy. A Zerynth App can be tought as a bidirectional communication channel between a Zerynth script running on a device and some HTML+Javascript template running on the mobile app. A program using the ZerynthApp module must provide some components: - an UI template, responsible of the Javascript part - a set of remotely callable functions representing the channel from Javascript to Python - a set of events representing the channel from Python to Javascript When the ZerynthApp class, defined in this module, is instantiated and run, it waits for messages coming from the mobile app through the Zerynth Advanced Device Manager ZerynthApp Step by Step¶ Using the “zerynthapp” module is easy. - First, a device template must be defined by creating the needed HTL and javascript files. The template must be uploaded to the ADM directly from Zerynth Studio or through the Zerynth Toolchain. - A “zerynthapp” instance must be created - The “zerynthapp” instance must be configured with credentials - The “zerynthapp” callable functions must be defined - The “zerynthapp” instance must be run HTML templates¶ HTML templates reside on the ADM servers and are transferred from it to the mobile app where they are rendered. Javascript is needed to add some logic to the template. The task is made easier by using the Zerynth ADM Javascript library. Important In each template there must be an index.html file that will be served by the ADM when the device UI is requested Templates are better explained with examples: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http- <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Zerynth</title> <!-- LOAD JQUERY AND BOOTSTRAP --> <script src=""></script> > <!-- LOAD THE ZERYNTH ADM JS LIBRARY --> <script src=""></script> </head> <body> <div style="text-align:center"> <p id="status" style="background:#ddd;font-weight:bold"></p> <h1>Hello, Zerynth!</h1> <div style="margin-left: 20px;margin-right: 20px"> <button class="btn btn-primary btn-xs" onclick="Z.call('random',[0,20],random_callback)">Random!</button> </div> <div id="number"></div> </div> <script> //callback for remote random method function random_callback(msg){ $("#number").html(msg.res) } $(document).ready(function() { // initialize the Z object Z.init({ on_connected: function(){$("#status").html("CONNECTED")}, on_error: function(){$("#status").html("ERROR")}, on_disconnected: function(){$("#status").html("DISCONNECTED"); return true}, on_online: function(evt){$("#status").html("ONLINE");}, on_offline: function(evt){$("#status").html("OFFLINE");}, on_event: function(evt){ //display received event $("#status").html("EVENT!"+JSON.stringify(evt)); } }) }); </script> </body> </html> In the body section, the html scaffolding is layed out and logic is inserted to link the template events with the functions running on the device. For example, in the onclick part of the button a RPC to the method “random” is generated by using the construct Z.call(method,parameters,callback). All the parameters are encoded, sent to the device, and used as arguments of the corresponding Python function. The Z.call function is the channel from Javascript to Python. Everytime the device will send an event, such event will be passed to the on_event callback of the Z object. Parameters can be passed to the event function and transmitted to the mobile app. The event method of the ZerynthApp instance is the channel from Python to Javascript. Zerynth App Instances¶ A template must be coupled with a Zerynth script running on a device. Here it is an example: from wireless import wifi # this example is based on Particle Photon # change the following line to use a different wifi driver from broadcom.bcm43362 import bcm43362 as wifi_driver import streams # Import the Zerynth APP library from zerynthapp import zerynthapp streams.serial() sleep(1000) print("STARTING...") # define a RPC function: generate a random number def do_random(a,b): return random(a,b) # send events on button pressed def on_btn(): zapp.event({"my_button":"pressed"}) onPinFall(BTN0,on_btn,debounce=1000) zapp = zerynthapp.ZerynthApp("DEVICE UID HERE", "DEVICE TOKEN HERE", log=True) # link "random" to do_random zapp.on("random",do_random) try: # connect to the wifi network (Set your SSID and password below) wifi_driver.auto_init() for i in range(0,5): try: wifi.link("NETWORK SSID",wifi.WIFI_WPA2,"NETWORK PASSWORD") break except Exception as e: print("Can't link",e) else: print("Impossible to link!") while True: sleep(1000) # Start the Zerynth app instance! zapp.run() # Do whatever you need here while True: print(".") sleep(5000) except Exception as e: print(e) This simple script connects to the local Wifi network, configures and runs a ZerynthApp instance. The method on is called to configure the Javascript-to-Python channel: everytime a call to “random” is remotely requested from Javascript, the function do_random is called in the Zerynth script. When the device button is pressed, the event method is called, and the event is transferred to the mobile app, where Javascript, configured in the template, updates a label. The ZerynthApp class¶ - class ZerynthApp(uid, token, ip=None, address="things.zerynth.com", log=False)¶ Creates a ZerynthApp instance or the device with uid uidand token token. If log is True, some debug messages are printed. If ip is given, it tries to connect to the ADM instance hosted at ip (default ip is 178.22.65.123). If address is given, it tries to connect to the ADM instance hosted ad address url (default address is “things.zerynth.com”). on(method, fn)¶ Associates the method name method to the callable fn. Everytime the ZerynthApp instance receives a request for method from the mobile app, the callable fn is executed (possibly with arguments).
https://docs.zerynth.com/latest/official/lib.zerynth.zerynthapp/docs/official_lib.zerynth.zerynthapp_zerynthapp.html
CC-MAIN-2019-30
refinedweb
931
55.84
byte - 8bit - signed - -128 to 127 short - 16bit - signed - -32768 to 32767 int - 32bit - signed (since Java 8 it can be used to represent unsigned) - -231 to 231-1 long - 64bit - signed (since Java 8 it can be used to represent unsigned) - -263 to 263-1 float - Single precision 32bit - End with F or f double - Double precision 64bit - End with D or d boolean - Only two values (true / false) char - Single 16bit unicode charactor (UTF 16) - '\u0000' to '\uffff' (0 to 65535) Here you can try this program to understand about java data types. public class DataTypes { public static void main(String[] args) { byte b = 10; short s = 5478; int i = 9978456; long l = 12547893533245625L; float f = 3.142f; double d = 1.0000000002125d; char c1 = 'A'; char c2 = '\u0024'; String st = "This is String"; System.out.println("byte: " + b); System.out.println("short: " + s); System.out.println("int: " + i); System.out.println("long: " + l); System.out.println("float: " + f); System.out.println("double: " + d); System.out.println("char: " + c1); System.out.println("char unicode: " + c2); System.out.println("String: " + st); } } Type casting Upward casting This method is implicit and reliable. There is the way to convert. int i = 10 ; double d = i ; public class DataTypes { public static void main(String[] args) { int i = 100; double d = i; System.out.println(d); } } Downward casting In this situating you can’t cast like upward method,If you try that way, it will give a compile time error. double d = 3.14; int I = d; So you have to cast in this way, Now output is 3. double d = 3.14; int I = (int) d; Your result is 3, double is floating point data type, but int is integer type.That is why you got the answer 3 instead of other one. Try this code, public class DataTypes { public static void main(String[] args) { int i = 128; byte b = (byte) i; System.out.println(b); } } In this program your output is -128, You may confuse from this answer. Thing is that, the range of byte is -128 to 127. When it exceeds the limit, its wraparound. Then the next value after 127 is -128. Special escape characters - \b - backspace - \n - new line - \t - tab - \f - form feed - \r - carriage return - \" - double quote - \' - single quote - \\ - backslash Underscore character - After Java SE 7, you can use underscore (_) character in numerical fields. - This can be used to separate numbers into groups to read easy. - But you can use it at the beginning or at the end of the number. - You cannot put underscore just before or after the F, D or L character. - It cannot be used before or after the decimal sign. public class DataTypes { public static void main(String[] args) { long num1 = 5642_1245_7845_5458L; float num2 = 3.14_15F; long num3 = 0xFF_AC_FA; System.out.println(num1); System.out.println(num2); System.out.println(num3); } } Default values of data types public class DataTypes { static byte b; static short s; static int i; static long l; static float f; static double d; static String str; static boolean bool; public static void main(String args[]) { System.out.println("byte : " + b); System.out.println("short : " + s); System.out.println("int : " + i); System.out.println("long : " + l); System.out.println("float : " + f); System.out.println("double : " + d); System.out.println("String :" + str); System.out.println("boolean : " + bool); } } Data types in java Reviewed by Ravi Yasas on 9:28 PM Rating: In your diagram displaying primitive data types shouldn't boolean and char be included, say under "nun numeric"?? I have corrected it bro, thankz much... It's better to have your kind comments to improve this blog, I really forgot it when I create it. anyway Thanks ..
https://www.javafoundation.xyz/2013/08/data-types-in-java.html
CC-MAIN-2021-43
refinedweb
618
67.65
- NAME - SYNOPSIS - DESCRIPTION - CONSTRUCTOR OPTIONS - METHODS - SEE ALSO_opts" in DBIx::Class::Schema::Loader. Available constructor options are: skip_relationships Skip setting up relationships. The default is to attempt the loading of relationships. debug If set to true, each constructive DBIx::Class statement the loader decides to execute will be warn-ed before execution. db_schema Set the name of the schema to load (schema in the sense that your database vendor means it). Does not currently support loading more than one single scalar table name argument and returning a scalar moniker. If the hash entry does not exist, or the function returns a false value, the code falls back to default behavior for that table name. The default behavior is: join '', map ucfirst, split /[\W_]+/, lc $table, which is to say: lowercase everything, split up the table name into chunks anywhere a non-alpha-numeric character occurs, change the case of first letter of each chunk to upper case, and put the chunks back together. Examples: Table Name | Moniker Name --------------------------- luser | Luser luser_group | LuserGroup luser-opts | LuserOpts::Number. inflect_singular As "inflect_plural" above, but for singularizing relationship names. Default behavior is to utilize "to_S" in Lingua::EN::Inflect::Number. schema_base_class Base class for your schema classes. Defaults to 'DBIx::Class::Schema'. result_base_class Base class for your table classes (aka result classes). Defaults to 'DBIx::Class'. table classes. A good example would be ResultSetManager. resultset_components List of additional ResultSet components to be loaded into your table classes. A good example would be AlwaysRS. Component ResultSetManager will be automatically added to the above components list if this option is set. use_namespaces This option is designed to be a tool to help you transition from this loader to a manually-defined schema when you decide it's time to do so. The value of this option is a perl libdir pathname. Within that directory this module will create a baseline manual DBIx::Class::Schema module set, based on what it creates at runtime in memory. THIS OR ANYTHING ABOVE!. METHODS None of these methods are intended for direct invocation by regular users of DBIx::Class::Schema::Loader. Anything you can find here can also be found via standard DBIx::Class::Schema methods somehow. new Constructor for DBIx::Class::Schema::Loader::Base, used internally by DBIx::Class::Schema::Loader. load Does the actual schema-construction work. rescan Arguments: schema Rescan the database for newly added tables. Does not process drops or changes. Returns a list of the newly added table monikers. The schema argument should be the schema class or object to be affected. It should probably be derived from the original schema_class used during "load".". SEE ALSO DBIx::Class::Schema::Loader
https://metacpan.org/pod/release/ILMARI/DBIx-Class-Schema-Loader-0.04006/lib/DBIx/Class/Schema/Loader/Base.pm
CC-MAIN-2018-34
refinedweb
445
50.43
Contents MotivationEdit You have a sequence of items and you would like to perform several sequential operations on each of the items in the sequence. MethodEdit You would like to use a single function where you pass a series of functions as parameters to that function. Background on Functional LanguagesEdit Functional languages are languages that treat functions as first-order data types. They frequently have a function that you pass a list of items and tell it what function to perform on each of those items. Just like XML transformations, functional languages are ideal when you have many small tasks to perform on a large number of items. Functional languages are excellent for these tasks since the actual order that the functions get executed on items does not have to be guaranteed. The developer does not have to be concerned about waiting for a transformation on item 1 to finish before the system starts on item 2. The Google MapReduce algorithm is an example of functional systems. MapReduce allows a data set such as "all web sites" to be treated as a sequence of items. MapReduce then has different processors each receive small items of work that can be processes independently. For more on functional languages see Functional programming on Wikipedia and Functional Programming on Wikibooks. Because XQuery is also a functional language, you can also have the confidence that a large list of items passed off to an XQuery function can run independently on many processors without the concern of incorrect results if the items are processed out of order. Simple exampleEdit In the following example we will declare two functions. We will then process a list of words by applying these functions to each of the items in the sequence. We will do this by passing the function name as an argument to another function. NOTE: This only appears to work in eXist 1.3. eXist versions 1.2.X have the wrong data type associated with the QName() function. The eXist system needs to turn each function into a function identifier. To do this it needs to call util:function(). util:function takes two arguments, the qualified name of the function (the prefix and the function name) as well as the arity of the function. In this case the arity of a function is the number of arguments that the function takes. The data type of the first argument must be of type QName. The data type of the arity, the second parameter, is an integer. util:function($function as xs:QName, $arity as xs:integer) as function declare namespace fw = ""; declare function fw:apply($words as xs:string*, $my-function as function) { for $word in $words return util:call($my-function,$word) }; declare function fw:f1($string) { string-length($string) }; declare function fw:f2($string) { substring($string,1,1) }; let $f1 := util:function(QName("","fw:f1"),1) let $mywords := ("red","green","purple") return <hofs> <data>{$mywords}</data> <hof> <task>length of each string</task> <result>{fw:apply($mywords,$f1)}</result> </hof> <hof> <task>Initial letter of each string</task> <result>{ fw:apply($mywords, util:function(QName("","fw:f2"),1) ) }</result> </hof> </hofs> ReferencesEdit - Jim Fuller Article on IBM DeveloperWorks - this has an excellent example of how to use Higher Order Functions using Saxon.
https://en.m.wikibooks.org/wiki/XQuery/Higher_Order_Functions
CC-MAIN-2017-43
refinedweb
547
51.38
Would you mind posting the code for Prompt used by import Prompt I tried using Prompt.lhs from your first post but it appears to be incompatible with the guessing game program when I got tired of reading the code and actually tried running it. best, thomas. 2007/12/4, Ryan Ingram <ryani.spam at gmail.com>: > Ask and ye shall receive. A simple guess-a-number game in MonadPrompt > follows. > > But before I get to that, I have some comments: > > > Serializing the state at arbitrary places is hard; the Prompt contains a > continuation function so unless you have a way to serialize closures it > seems like you lose. But if you have "safe points" during the execution at > which you know all relevant state is inside your "game state", you can save > there by serializing the state and providing a way to restart the > computation at those safe points. > > I haven't looked at MACID at all; what's that? > > > {-# LANGUAGE GADTs, RankNTypes #-} > > module Main where > > import Prompt > > import Control.Monad.State > > import System.Random (randomRIO) > > import System.IO > > import Control.Exception (assert) > > Minimalist "functional references" implementation. > In particular, for this example, we skip the really interesting thing: > composability. > > See for a real > implementation. > > > data FRef s a = FRef > > { frGet :: s -> a > > , frSet :: a -> s -> s > > } > > > fetch :: MonadState s m => FRef s a -> m a > > fetch ref = get >>= return . frGet ref > > > infix 1 =: > > infix 1 =<<: > > (=:) :: MonadState s m => FRef s a -> a -> m () > > ref =: val = modify $ frSet ref val > > (=<<:) :: MonadState s m => FRef s a -> m a -> m () > > ref =<<: act = act >>= modify . frSet ref > > update :: MonadState s m => FRef s a -> (a -> a) -> m () > > update ref f = fetch ref >>= \a -> ref =: f a > > Interactions that a user can have with the game: > > > data GuessP a where > > GetNumber :: GuessP Int > > Guess :: GuessP Int > > Print :: String -> GuessP () > > Game state. > > We could do this with a lot less state, but I'm trying to show what's > possible here. In fact, for this example it's probably easier to just > thread the state through the program directly, but bigger games want real > state, so I'm showing how to do that. > > > data GuessS = GuessS > > { gsNumGuesses_ :: Int > > , gsTargetNumber_ :: Int > > } > > > -- a real implementation wouldn't do it this way :) > > initialGameState :: GuessS > > initialGameState = GuessS undefined undefined > > > gsNumGuesses, gsTargetNumber :: FRef GuessS Int > > gsNumGuesses = FRef gsNumGuesses_ $ \a s -> s { gsNumGuesses_ = a } > > gsTargetNumber = FRef gsTargetNumber_ $ \a s -> s { gsTargetNumber_ = a } > > Game monad with some useful helper functions > > > type Game = StateT GuessS (Prompt GuessP) > > > gPrint :: String -> Game () > > gPrint = prompt . Print > > > gPrintLn :: String -> Game () > > gPrintLn s = gPrint (s ++ "\n") > > Implementation of the game: > > > gameLoop :: Game Int > > gameLoop = do > > update gsNumGuesses (+1) > > guessNum <- fetch gsNumGuesses > > gPrint ("Guess #" ++ show guessNum ++ ":") > > guess <- prompt Guess > > answer <- fetch gsTargetNumber > > > > if guess == answer > > then do > > gPrintLn "Right!" > > return guessNum > > else do > > gPrintLn $ concat > > [ "You guessed too " > > , if guess < answer then "low" else "high" > > , "! Try again." > > ] > > gameLoop > > > game :: Game () > > game = do > > gsNumGuesses =: 0 > > gsTargetNumber =<<: prompt GetNumber > > gPrintLn "I'm thinking of a number. Try to guess it!" > > numGuesses <- gameLoop > > gPrintLn ("It took you " ++ show numGuesses ++ " guesses!") > > Simple unwrapper for StateT that launches the game. > > > runGame :: Monad m => (forall a. GuessP a -> m a) -> m () > > runGame f = runPromptM f (evalStateT game initialGameState) > > Here is the magic function for interacting with the player in IO. Exercise > for the reader: make this more robust. > > > gameIOPrompt :: GuessP a -> IO a > > gameIOPrompt GetNumber = randomRIO (1, 100) > > gameIOPrompt (Print s) = putStr s > > gameIOPrompt Guess = fmap read getLine > > If you wanted to add undo, all you have to do is save off the current Prompt > in the middle of runPromptM; you can return to the old state at any time. > > > gameIO :: IO () > > gameIO = do > > hSetBuffering stdout NoBuffering > > runGame gameIOPrompt > > Here's a scripted version. > > > type GameScript = State [Int] > > > > scriptPrompt :: Int -> GuessP a -> GameScript a > > scriptPrompt n GetNumber = return n > > scriptPrompt _ (Print _) = return () > > scriptPrompt _ Guess = do > > (x:xs) <- get -- fails if script runs out of answers > > put xs > > return x > > > > scriptTarget :: Int > > scriptTarget = 23 > > scriptGuesses :: [Int] > > scriptGuesses = [50, 25, 12, 19, 22, 24, 23] > > gameScript is True if the game ran to completion successfully, and False or > bottom otherwise. > Try adding or removing numbers from scriptGuesses above and re-running the > program. > > > gameScript :: Bool > > gameScript = null $ execState (runGame (scriptPrompt scriptTarget)) > scriptGuesses > > > main = do > > assert gameScript $ return () > > gameIO > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe at haskell.org > > >
http://www.haskell.org/pipermail/haskell-cafe/2007-December/037137.html
CC-MAIN-2014-41
refinedweb
725
60.24
Telerik Reporting supplies report item components that are placed in the report designer to build report content: The Report Definition item is created during the first stage of the Report Life Cycle. This is the actual .NET class that represents the report. It is always a subclass Telerik.Reporting.Report and contains information about report items and their properties. Report items are represented by the private fields of the report class. Let’s illustrate this with an example. While in design-time, if you add a TextBox to the Detail Section of the report that you are designing, a private field of type TextBox will be added to the code-behind file and some basic initialization code will be generated within the InitalizeComponent method of the report class. The InitializeComponent method initializes (creates) a Report and its child items.It is a special method recognized and parsed by the Report Designer in order to display the report in design-time. This object will later serve as the definition for creating a concrete instance of the TextBox for each row form the data source. These definition objects are of the types that reside in the Telerik.Reporting namespace, for example Telerik.Reporting.TextBox. The second stage of the Report Life Cycle involves combining the report definition with the data source. The processing engine performs all grouping, sorting and filtering calculations and iterates over all rows from the data source and creates the appropriate processing items based on the item definitions created earlier and the actual data. Based on the original item definition (Telerik.Reporting.TextBox for example) and the actual data in the current data row a new item is created. This item is known as a processing item (Telerik.Reporting.Processing.TextBox for example) and bears all characteristics of its definition item, but it is bound to the respective data field from the current data row. While the definition TextBox’s Value property may contain something like “=Fields.FirstName”, the processing item’s Value property will be equal to “John”. The Processing Engine provides the developer with a way to intervene in this process. Just before the processing item is bound to data, the ItemDataBinding event of its definition item is raised. After the processing item has been data bound the ItemDataBound event is raised. By subscribing a listener for those events, the developer can modify the default behavior at run-time. The sender parameter of the event handler methods is in fact the processing report item.
http://www.telerik.com/help/reporting/report-items-intro.html
CC-MAIN-2015-35
refinedweb
417
55.95
28.14. site — Site-specific configuration hook¶ Code source : Lib/site.py This module is automatically imported during initialization. The automatic import can be suppressed using the interpreter’s -S option. Importing this module will append site-specific paths to the module search path and add a few builtins.. Modifié dans la version 2.6: A space or tab is now required after the import keyword... Nouveau dans la version 2.6.. Nouveau dans la version 2.6.. Nouveau dans la version 2.6. (and possibly site-python). Nouveau dans la version 2.7. site. getuserbase()¶ Return the path of the user base directory, USER_BASE. If it is not initialized yet, this function will also set it, respecting PYTHONUSERBASE. Nouveau dans la version 2.7. site. getusersitepackages()¶ Return the path of the user-specific site-packages directory, USER_SITE. If it is not initialized yet, this function will also set it, respecting PYTHONNOUSERSITEand USER_BASE. Nouveau dans la.
https://docs.python.org/fr/2/library/site.html
CC-MAIN-2017-47
refinedweb
156
63.05
Let’s look at an inheritance example with members. The class LibraryBook is a child class of a super class Book. Here, we say LibraryBook inherits states and behaviors of objects of Book class such as isbn, author, title and many others. Apart from deriving from Base class, LibraryBook can have its own data members such as number of copies and member functions representing states and behaviors of objects. package javaapplication31; public class BookClass { static class Book { int isbn; String author; String title; public void init(int isbn, String author, String title) { this.isbn = isbn; // this.isbn refers to instance variable, // isbn refers to local variable this.author = author; this.title = title; } } static public class LibraryBook extends Book { int nCopies = 10; // number of copies of the book public void show() { System.out.println("isbn = " + isbn + "\nauthor = " + author + "\ntitle = " + title + "\ncopies = " + nCopies); } } public static void main(String[] args) { LibraryBook lb = new LibraryBook(); lb.init(4321, "Jeniffer", "Data Structures"); lb.show(); } }
https://codecrawl.com/tag/inheritance/page/2/
CC-MAIN-2018-47
refinedweb
159
57.98
MZ·IE02 SHARP SERVICE MANUAL CODE: 00 ZMZl EO 2 / /-E GP I/O INTERFASE MODEL ~---------------------------- MZ-1 E02 CONTENTS ----------------------------~ 1. WHAT IS A GP I/O INTER FACE? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. SPECIFICATIONS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 DATA INPUT/OUTPUT FORMAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 INPUT/OUTPUT PINS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 SIGNAL TIMING IN AUTOMATIC HANDSHAKING MODE ..... " . . . . . . . . . . . . . . 2 CONNECTION OF PERIPHERAL DEVICES . . . . . . . . . . . . . . , . . . . . . . . . . . . . . . . 3 PROGRAMMING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 ERROR CODE TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 INPUT CODE TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 MZ-1E02 CONTACT SIGNAL TABLE _ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 SETUP OF THE DIP SWITCH _ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 MZ-1E02IGPI0) TEST PROCEDURE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 MZ-l E02 SCHEMATIC DIAGRAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 MZ-1E02 COMPONENT LOCATION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 PARTS LIST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 SHARP CORPORATION MZ·IE02 1. WHAT IS A GP 110 INTERFACE? 3. DATA INPUT/OUTPUT FORMAT The General Purpose Input/Output Interface (GP liD) is designed for connecting general low-speed peripheral units (e.g. The input/output format for data and control signals including positive/negative logic, code length (8-bit/7-bit code), and parity mode (even parity/odd parity/no parity) shOUld be set up in accordance with the input/output format of the peripheral unit to be connected. The method of setting the format will be described in Part VII, Programming, p. 1 6. measuring instruments, printers, X-V plotters, etc.) and providing information exchange between the main computer unit and peripheral devices in a parallel 1/0 mode. However, there are many different standards and features in parallel interfaces, and they do not always provide satisfactory information exchange for units having parallel interfaces. It is reauested that the user fully understand this instruction manual 'and sp8cifications of the peripheral units before using this I/O interface. Sharp cannot provide either hardware or software support for special customer applications. Moreover, Sharp cannot in any way be responsible for damages that arise as a result of customer misuse. However, this instruction manual describes information necessary for exchanging information between the main computer unit and peripheral units in so far as is possible. 1. B-BIT CODE AND 7·BIT CODE 8-bit code uses eight bits (eight pins) to express data and the 7-bit code uses seven bits (seven pins) to express data. Either 8-bit or 7-bit code can be set for this I/O interface. This interface unit has eight pins for each data input and output, and setup of the 7-bit code permits the use of the remaining bit (one pin) as a parity bit, as will be described below. 2. PARITY CHECK A parity bit can be added to 7-bit data so as to provide a parity check of the data. An even parity check verifies that the total number of 1 (logical "1") bits of data and the parity bit is an even number, and an odd parity check verifies that the total number of 1 bits is an odd number. This I/O interface can be set to either an even parity check, odd parity check or no parity check when the 7-bit code is used. 2. SPECIFICATIONS Model: Input/output mode: MZ-1E02 Parallel input/output mode (byte serial) 1 channel Number of channels: 12 pins (8 data input pins and 4 conInput ports: trol signal input pins) 12 pins (8 data output pins and 4 conOutput ports: trol signal output pins) B-bit ASC II or 7-bit ASC II code Data code: Approximately 5 K bytes/sec. max. Data rate: Automatic handshaking or manual Transmission mode: mode Even parity, odd parity, or no parity Parity format: bit GMOOE, GSET, GIN, GOUT, and Command words: GBIT Electronic components: Integrated circuits and discrete components Operating temperature: 10 to 35'C 140 (W) x 142 (0) x 15 (H) mm Outer dimensions: 160g Weight: Instruction manual (this manual), Accessories: F DOS Master Note: One main computer unit can accomodate up to two interface units (i.e. two channels). The interface unit is mounted in slot 1, 2, 3 or 4 of MZlU02 Option Expansion Unit taht mounted in the Model-3500 Series Business Computer Main Unit (for two units combinations of slots 1 and 3 or slots 2 and 4 are not allowed). The channel number is determined by the slot number of the interface unit: Slot 1 or 3 ................ Channel number: 0 Slot 2 or 4 ................ Channel number: 1 Two interface units may be mounted in any of four combinations: Combination Slot 1 1 Channel 0 2 Channel 0 X 3 X Channel 1 4 X X Slot 2 Slot 3 SIot4 Channel 1 X X ... _-- 3. AUTOMATIC HANDSHAKING MODE Automatic handshaking is one of the data transmission modes, and it generally transfers data automatically in the following procedures. Although automatic handshaking is a basic feature of this I/O interface, manual mode can also be selected. Data transmission in the automatic handshaking mode (data output). Input control signals ,ACKNOWLEDGE, READY, etc.)0..!N",O,---! reset? YES Data output Set output control signal {STROBE). Input control signals ,--"N",O«ACKNDWLEDGE, READY, etc.) set? YES Reset input control signals (ACKNOWLEDGE, More output ">2Y-"E"S_ __ data? i i Channel 0 X ----1----- - - J X Channel 1 Channel 0 Channel 1 Data input is handled similarly.' 1 MZ-1E02 4. POSITIVE LOGIC AND NEGATIVE LOmC This I/O interlace "can be set for positive logic or negative "logic, independently f~r input data, output data, input can... ~r<?' ~ig!lal~, and output c9ntro] signals. The logical mode ,ot;QJltput,R()ntrol sigrais js set by,the DIP swjt~h on the int~rfac~ PC bo~rd and the logical mode of other signais is ,~et l!sing a command_word (GSET commanc;lJ. For further . details,' see Pllrt VU,. Prograrnmin~I'rp., 1-5 and Appendix 4~ Setup of the DIP switch; p. A-5. 4;' iNP " 5. SIGNAL TIMING IN AUTOMATIC HANDSHAKING MODE 1. SIGNAL TIMING FOR DATA INPUT For data input in the automatic handshaking mode, signal lines 11 to 18 are used 'for input data, 1.10 is used: f'or th~ ~.TRO_~E signal in data input and 01_0. is -u~ed for the. ACKNOWLEDGE signal which indiCates thatt'he interlace unit (MZ-1 E02) has received data. J~~.!~!!oyvin !1,I_u~t'~~~es t~~_t! J, 9 s.iQ.Qal.s _9_S~"rIJing that PUTPrNS signals' on liries 110 and 010 are in Data signa!s 11 to 18 1. ' INpurPiNS'" Th.is','jjo' j'nteriace ;has\(] 2 inpu"t pins, eight for data and four for control .signals. 'th'e 12 iripu"t pins correspond to signals 11 through 112. Signals 11 to 18 are data signals and 19 to 112 are control signals. These signals have the follQvying magnitudes , (weighrs),: . 1i l1i',' I!~ , ... :. . . .. 2° ,J,I~J10 2' .3.13,111 ....... 2' 4: 14,112," ...... 2' 5., 15 ........... 24 ~-+I\+,,---_:;_'-T"-4J\.,--~ at T must be feast 78-.0.uS in dUration. signal 110 ACKNOWLEDGE signal 01 0 --~=-=:::f~- 95.0 ,uS to 170.0j,lS The ACKNOWLEDGE signal on signal line 010 can be replaced with the READY, REQUEST TO SEND (trans, mission request) or the BUSY signal. 2. SIGNAL TIMING FOR DATA OUTPUT For data output in the automatic handshaking mode, signal lines 01 to 08 are used for output data, 09 is used for the 8. 18 ........... 27 or used as a parity bit or not used. STROBE signal and 19 is used for the ACKNOWLEDGE signal which indicates that the peripheral unit has received data. The following Hlustrates the timing of signals, assuming that signals on lines 09 and 19 are in a negative logrc system. 2. OUTPUT PI NS This)/O iriterface has 12 output pins, eight for data and fbL\r f~r'i:::0l1trol signals. 'The- 12_ ou'tput pins correspond to signals 01 through 012. These signals have the following magnitudes (weights): 1. 01,09 ....... 2' 2. 02,010 ...... 2' 3. 03,011 ...... 2' 4. 04,012 ...... 2' 5. 05 .......... 24 Data signals 01 to 08 ___~=t=+~~17~,O~"~S~'~5~%~,,______ STROBE signal 09 If T1 is less than 3.5 Tl + T2 must be at least 3.5 .uS; if T1 is equal to or more than 3.5 .uS, T2 must be at least 78.0 p.S. tLS, ACKNOWLEDGE signal 19 6. 06 .......... 2' 7. 07 .......... 2' 8. 08 .......... 27 or used as a parity bit or not used. After power has been switched on, signals 01 to 08 are ON The ACKNOWLEDGE signal on line 19 can be replaced with the READY, REQUEST TO SEND (transmission request) or the BUSY signal. As described above in aautomatic handshaking, signal lines 11 to 18 are used for data input and 110 and 010 are used for control signals during data input. Signal lines 01 'to 08 are used for data output and 09 and 19 are used for control signals. Input lines 111 and 112 and output lines 011 and 012 are not used in the automatic handshaking mode and these lines can be used arbitrarily. The following shows some examples of signals to be transmitted on these four lines. Also refer to the GBIT command, p.30. (high level) and signals 09 to 012 may be ON (high level) or OFF (Iow level) as set by the DIP switch on the interface PC board. For further details, see Appendix 4, Setup of the DIP switch, p. A-5. ELECTRICAL CHARACTERISTICS OF INPUT/OUTPUT PINS 1) Output signals ON (high) : > 2.4 V OFF (Iow) : <0.5 V ---y-------,r--- STROBE 6. 16 ........... 2' 7. i7 ........... 2' 3. a positive logic s'istem~ 0.25 mA 48 mA Signal line 2) Input signals ON (high) : 2.0 - 5.25 V OFF (Iow) : -0.5 - 0.5 V Maximum input voltage: 5.25 V 11T,''i'l2' ERROR Signal, WARNING si'grial, PAPER END signal, ALARM signal, FAU LT signal, WAIT signal, etc. 011, 012 MACHINE SELECT Signal, REMOTE POW, ER-ON signal, INITIAL. RESET signal, FAULT RESET signal, etc. Note: 2 ExamplE!,of signal If data input or output does not operate satisfactorily in the automatic handshaking mode and the system hangs up in the wait stat~ (e.g., the system waits for the STROBE signal in data input or the ACKNOWLEDGE signal in data output), the system can be released from this state by pressing the HALT button. MZ-IE02 6. CONNECTION OF PERIPHERAL DEVICES 1. PERIPHERAL DEVICES THAT CAN BE CONNECTED. General low-speed peripheral devices (e.g., measuring instruments, printers, X-V plotters, etc.) having parallel interfaces can be connected. The Model-3500 Series Business Computer Main Unit can also be connected to another computer having a parallel interface. Processing of control signals and operation (timing) of the automatic handshaking modes differ for each device and the specifications of each device must be satisfied. For further details, see the following paragraph. 2. PRECAUTIONS FOR CONNECTION The user should first carefully check the specifiecations of each peripheral device before connection is made. This paragraph describes general precautions. 1) Electrical characteristics of the input/output pins Confirm that the peripheral device to be connected satisfies the characteristics shown in Part IV, 3, Electrical characteristics of input/output pins, p. O. In particular, make sure to check that the output voltage of the peripheral device does not exceed the maximum input voltage of the MZ-1 E02 interface. Excessive signal voltage can cause damage to the interface unit. 2) Automatic handshaking mode Confirm that data is transmitted to the peripheral device in accordance with the flow chart for data transmission, as described in Part Ill, 3, Automatic handshaking mode, p. 8. The timing of the signal on line 010 at data input and the signal on line 09 at data output must satisfy the specifications of the peripheral device. The setup time for the signal on line 110 at data input and the signal on line 19 at data output must be long enough, as specified, to ach ieve satisfactory data transmission. 3) Manual mode If data transmission does not operate satisfactorily in the automatic handshaking mode, carry out data transmission in the manual mode where control signals are input and output by the program (GB IT command). Data transmission in the manual mode takes 10 seconds or more, and the timing of each control signal must be considered carefully. 4) Other When a printer is connected as a peripheral device, set the eR code of the printer to the carriage return (without line feed) function, i.e., turn off the automatic line feed. A CR code and an LF code are output automatically following data output. Slot number 1 2 3 4 Channel 0 1 0 1 number 2) Wiring Solder the each loose wire of optional GP I/O interface cable [MZ-1C19] with a proper connector of peripheral device according to Appendix 3. MZ-1 E02 Contact signal table. Connect all GND lines (24 wires) of the cable to the GNO pins of the peripheral device. Extension of the cable must be within 2 meters and sufficient precautions must be taken for noise protection to ensure reliability. 3) Attaching the connector Connect the interface MZ-' E02 and the peripheral device with the cable [MZ·l C19]. And then fasten it with two screws on the both end sides of the connector. 4) Power·ON Set the GP I/O interface controlling FOOS Master disk (accessories) in the Mini-Floppy Disk Drive unit (channel-drive number AO) that located on the right hand side of the Model-3500 Series Business Computer Main Unit. Turn power on the peripheral device (CRT display, etc.), then the Model-3500 Series Business Computer Main Unit. (The FDOS Master attached with Model-3500 Series Business Computer Main Unit and that of version No. V2.0 are not applicable.) 7. PROGRAMMING For ease of understanding of the syntax and rules of command words, the syntax notation is defined as follows. This notation is effective only in describing the syntax and rules, and should not be used in actual programs. Symbol Meaning I [ J I I ( ) " S, T A AS 3. CONNECTING PROCEDURE N Note) Switch off the power supplies to the Model-3500 Series Business Computer Main Unit and peripheral devices before making connection. X, Y, Z C, D, E --- 1) I nstalling the MZ·1 E02 Install the MZ-1 E02 in one of slots 1, 2, 3 or 4 of MZ1 U02 Expansion Unit that mounted in the Model-3500 Series Business Computer Main Unit. After installation, secure the MZ-1 E02 with screws that closed the slot cover. The interface unit is assigned channel 0 when it is mounted in slot 1 or 3, or the unit is assigned channel 2 when it is mounted in slot 2 or 4. (See the following table.) 3 Indicates the separation for selection. The part enclosed in brackets [ ] can be omitted. When this is omitted, the funcI tion is merely invalidated or a different function is validated. . The part enclosed in braches { ) can be written repeatedly using a comma ( , ). The aprt enclosed in angles ( ) can be written repeatedly using a semicolon ( ;). Indicates an iteger, (Example: 10) Indicates a character constant. (Example: "NAME") Indicates a numeric variable (including a numeric array variable), (Example: NO) Indicates a S- or @-type character variable (including character array variable). (Example: DAS) Indicates a variable (numeric or character variable) (including an array variable). Indicates a numeric expression. Indicates a character string. Indicates a flow of syntax. ~ Indicates selection. ...c'l. Indicates repetition. ~ Indicates omission. MZ-lE02 In actual operatio'n, -I ENTER I key must be pressed at the enci.---or-~ach- _pro-gram step. (For' m~ltiple statement :.en_try, statements must' be separated Note 1) 2. GSET This command specifies the logical polarity of Input/ _ output ~ata signals and input control signals. using a colon ( : ).} Note 2) th~ ,Enter the program with MZ-1E02 installed. This command is effective only-for channels and ports in the automatic handsha"king mode. 1. GMODE' Fqrmat) GS~T Thi~! com~and ,~ets up the inp~t/output channel modes. . . ',:, , ' , ' Channel number (0, 1) X -------'-~----'---"'-'~~~~=~~---"-~~-~~------'e 'i'ypi;-"fsig,",ls"'-~----'~=--~~----'~-- Th~ set'~p' ~~de~ include the automatic :nandshaking mo'de or manual mode for input/output ports, S-bit or 7-bit cOde for the automatic handshaking, ~ode, and 'tne- parity check mo'de. ID ........ Input data signals OD .. . . . .. Output data signals le ........ Input contr'ol'signaj~ Positive logic/Negative logic 0: F?rmat) GMODE C, (X,) 0 (,El [x.) C, D I (SYNTAX) X: Channel number (0, 1) C : Port L-_rr<ID-r-0-rl________ 1'1' ,L ... ;; .... Inp~t port .. 0 ........... Output port D ; !Mode' E A ..... ',._ .. AutOinatic handshaking mode B ........ Manual mode Data format This command specifies the logical polarity of signals on a channel, as indicated respectively by the character strings D and C, ahd the expression X. The logical polar~ty of signals can be specified in two ways: S ......... S-bit code i) 7E ....... 7-bit code with even parity bit 70 ....... 7·bit code with odd parity bit 7 ......... 7-bit code without parity bit Specifi,cation for a group of signals (8 data bits or 4 bits) as designate~ by string C: Character string D: Positive logic ........... "1" Negative logic ........... "0" ii) Specification of individual signals as designated by character string C: Character string D: Example for input control signals: "0101" 1]1'. Numeric expressjon X selects the channel with character ~tring C selecting which port and character string D .selecting the mode (automatic handshakin9.' mode/manual mode). When the automatic handshaking mode is specified by D, data format can be specified by the character string E. If (X,] is omitted, channel 0 is set automatically. If E is omitted in the specification of the automatic handshaking mode, 8-bit data code is set automatically. After power has been switched on, the input and output ports of each channel are set to the automatic handshaking mode with 8-bit data code. If Addendum) 10 GMOOE "O","A",'"7E" This program specifies the automatic handshaking mode for 7-bit code with even paritY' check for the output port of channel O. ,," .".",--" ., .. :.. ._ ... __ ~ __ ; The 7·bit ASCII cdde system has the SIISO state for handling as much data as .an 8~bit The logical polarity of the output control signals is set by the DIP switch on the interface PC board. (This command cannot be used for that purpose.) For details, see Appendix 4, Setup of the DIP switch, p. A-5. , Addendum) SIISO (shift-in/shift·out) •• ' 10 GSET "00", "0" This program specifies negative logic for all output data signals (8 bits) on channel O. / SO (shift-in/shift-out) state is automatically set to SI by execution of this command. ;_,J~ is omitted, the logical polarity for channel 0 Example) ~l --"~; Negative logic for signal 110 Positive logic for signal 111 Negative logic for signal 112 is set. After power has been switched on, positive logic is set for all input/output data signals and input control signals for each channel. Note) For data 1/0 in the 7-bit ASCII code system, the Example) ex,) Positive logic for signal 19 code system does. The SO code (CH R$ &OE) switches the SI state to the SO state, and the SI cdde (CH R$ &OF) switches the SO state to the SI state. Accordingly, data iri the 7-bit ASCII code system includes SI codes and SO codes. These codes must be taken into considerati'on in programming when the amount of data is significant. The SI and SO states are independent for the input and output ports and for each channel. After power has been switches on, the SI state is automatically set. 4 MZ-lE02 Format 2) GIN 3. GIN This command enters data. manual mode input command. I I X, N, CC, DJ - D - . - GIN-.-~ch".r.c'.r ~ l...cD-J-=-~~ (SYNTAX) f,\ _ I Channel number (0, 1) Variable for inputting data End code 1 End code 2 X N C 11 E : Type of signals D ........ Data signals C ........ Control signals A: Numeric variable for inputting data The syntax differs in the automatic handshaking mode and manual mode. Format 1 applies to the automatic handshaking mode input command, and Format 2 applies to the Format1)GIN X, E, A Channel number (0, X 1 _ _ _ -, I .~ Format2 of the GIN command is used in manual mode. The GIN command inputs the logical level (ON or high, and OFF or low) of a signal as designated by the character string E to the numeric variable A as binary data for the channel as designated by the numeric expression X. Binary data produced by this command will have the magnitude of 1,2,4,8, 16, 32, 64 or 128, or any sum of these values depending on the bit position in the ON state (high level), irrespective of the logical polarity specified by the GSET command. Bit positions in the OFF state (Iow level) give a value of O. This command (Format 1) is used in the automatic handshaking mode. The GIN command inputs data to variable N unitl end codes are read (will be described shortly) as designated by the character strings C and D for a channel as designated by the o Magnitude of bit positions in the ON state (high level): 11,19.................. 1 12,110 ................. 2 13,111 ................. 4 14,112 .................. 8 15 ...................... 16 16 '" ................... 32 17 ...................... 64 18 ...................... 128 numeric expression X. The end codes are not input to the variable N. If the area for variable N overflows, ERR 0 R 205 occurs. The NULL code has no effect and is not input to the variable. For character strings C and D, only the first character is valid as an end code. o End code When one end code is specified (,D is omitted), data is input until the end code as designated by the character string C is met. Whe two end codes are specified, data is input until one of the end codes as designated by character strings Cor D is met. In this case, if the end code as designated by character string C is met, the succeeding statement will be executed next. If the end code as designated by character string D is met, the statement in the subsequent program step will be executed next. Example) 10 GIN O,A$,CHR$ &7F ,CHR$ 8.00:GO TO The range of magnitude of data signals is 0 to 255, and that of control signals is 0 to 15. 4. GOUT This command output data. Syntax 1 and 2 apply"to operation in automatic handshaking mode, and Format 3 applies to operation in manual mode. 10 Format 1) GOUT 20 DISP "A$=";A$ This program inputs data to the character variable A$ until the DEL (delete) code (Le. CHR$ & 7F) or CR (carriage return) code (Le. CHR$ & OD) is met. Upon input of the DEL code the statement 'GO TO 10' will be executed next, or upon input of the CR code, the statement 'DISP "A$=" ;A$' in the subseqQent program step will be executed next. Note 2) Note 3) Note 4) Null code is invalid to input even in @-type character variables. For input data in negative logic as specified by the GSET command, complementary data (having an inverted polarity) will be input. The data of 253 bytes or less is available to input at a tirm, more bytes of data input invite error (y C X Channel number (0, 1) Y C Numeric data to be output Character data to be output > C; ) 1 (SYNTAX) , GOUT ,-dD-.,c,-~ ' - . 1_ Note 1 J X, _ _ _ Format 1 of the GOUT command is used in automatic handshaking mode. The GOUT command outputs numeric data designated by the numeric expression, or literal data designated by the character string C to a channel designated by the numeric expression X. With a semicolon attached at the end of the last numeric expression or literal string, no CR code (CHR$ (ERROR 125). If CHR$ &01 through &1F and CHR$ &81 &OD) nor LF code (CHR$ &OA) is output following the output of data. Conversely, if a semicolon is omitted at the end of the last numeric expression or literal string, a CR code and an LF code are output automatically follow· ing the output of data. through &9F is specified as the end code in the 7-bit code system, the end code is detected using 7·bit data irrespective of the SI/SO state. If CHR$ &20 through &7F and CHR$ &AO through &F F is specified as the end code, the end code is detected using the SI/SO state and 7-bit data. 5 MZ·IE02 Example) 10 GOUT 0, "ABC" :\ Format3) GOUT This program outputs literal s1:i-iri~j' (lifer'aT constanW" ASC" data followed by a CR code and LF code forchanriel O. Note) For output data in .rieQCitive logic as specified by the GSET comman~.~:· ·'~oinpl~~entarY. :d~tCl.: (having inverted poia'rity) will be outP~l"t.· (This r'ule also applies to Format 2.) Format2)·G.OUT " x·., USING ri'l· S I'(Y) I A$ I IMAGE X.,h"Gha~reL"~mb~\(q,J). ':'-'f;i.; .,;, L,if)~ mJwb~rva~ye_.of IMAGE st~~ern,en~ ;-~ ~-,;~.;.~ '," :') Lj~e !a.bel.-~~ITI~ eJ ,lMA~.E 5~,a~e.m~t1t . ,);'";( J.: ,L,in e , ,~1:ll}lb~;r ,(numer,ic expressio~) of IMAGE _~at,eITIIi!n1; ; "ji _. ..,' . : .~A$,,: , Character ,- 'variable_ - for. -specified. format (!~~_ge Cl; r'_: ,~Y_!l1b'pl); ',", ;:. , -~- - -', -~ -: -~ :- - ---, ~ --- ----T· .:". Character cQnstan~ indicating im.age symbol J ~J" ~~meri'c.~at~;,~~ ~~ 9utPU.~' , - ~ !:i':'~i: ::;;Gh~.~~~tf1r dat~:.~,?.b.elp.lJ~'pyt -j - . Channel number (0, 1) Type of signals o ...' .. ~ .. Data signals C". '.':...:'... Control signals NUmeric. data ·to be OUtput :, A}: I(SYNTAX) C{Z I CLC-:.-J-JJ-____~--I .- - - T Z : X E X, E, Y I . . .- I - GOUT~ .Ch.n~ • . . '."m.o,.;." . . . . . ~-'----r' _ I _ • ',---.'~. ---l. - , ,.. ,,' .J Format 3 of the GOUT command is used in :tpe m~nua! mode. The GOUT comm~nd Qutputs numeric data designated by the numeric expression Y in binary format with' the logical -polaritY-oaf "the signafs-'designated_b-v the--charactei' string ~ to a channel designated by the numeric expression ~. this command outputs an ON state. (high level) for. a-O bit; irrespective of the' iogiccH "Polaiity' ~pecified by the GSET command. The logical polarity of output 'cbntrol sig'nals' is determined by the DI P switch o.n the inierf~de PC , board {See·p. A-5 0 } 'Wh'en'the character string E iS'set to data . signals, tile' niagn'itude of the riu"n1eric expreSsion Y must b~ within' the' ra~ge from 0 to 1.5 If this range is exceeded, ERROR 127 occurs. NoCR cdde (CHR$&OD) ;,or LF code (CHR$ &OA) is output a't th~ 'end bf the 'output data. '--.c' _ _ Note} Use this command for data. in. the a-bit code system. Format 2 'of the GOUT command is used in the automatic hJ~"d~ha.king.. . , '. Th"Et GOUT command outputs,;numeric data designated by the numeric expression Z 'or literal data designated by the character string C in a format designated by the IMAGE statement. This syntax conforms to Function 2 of the PR INT state· ment.described in the MZ-3500 BASIC LANGUAGE .. MA,NY/',!I,'.rc<"lso !~'er. t? the IMAGE .statement. It a s.~micolon is attached .to the end of the last numeric ~xpr~ssiori'or 'Iiter~I' string, no CR code (CHR$ &00) nor LF code (CHR$ &OA) is output following the,output of data. Conversely, if a semicolon is omitted, an LF code is output automatically at end of the. dat;;! (,No CR code is output). If {Z I C f e;) is omitted, neither CR code nor LF code is output. The eR code and LF code C(in be set using the IMAGE statement. Example 1) 10 GOUT 1,USING 500,X$,Y$ ThJs pr.Qgr~1l] outputs character"strings X$.. and Y$ in the format specified by the IMI:\G.E :..sta,t~!11~nt .for channel 1. . : :. ;. i: : , . ::, :;, ~ : .. ; j': .• , i :,: , . ,'; . ) . ,; j ; . , Example 2) 10 H$="TRANSISTORS":K=1320 ':,.' i:.~~g,.:~~~T;i-O~·~~~NP) lPR!.~.~~~~! . °ioo: IMA·GE.,,~'llA 5X":·,"PRI.CE'" "') ,... ,:,1 . ;: ',') ,. ;;;. . . "TR''';;'N<sr STOR s'Sp '.1 '. "" ., ',,' .'" I SpSpSpSp$ 1 , 3 2 0 CRLF SpSp Sp Sp PR IC E The NULL code can be output. 10 GOUT 0, "0",0% This program outputs a NULL code for channel. O. 5. GBIT This command verifies and sets the logical level· of signals. This command is effective for ports in both automatic handshaking and manual ·modes. .The. commahd has no relation to the logical polarity specified by the GSET command. The logical polarity of the· output control signals is determined by the DIP switch on the interface PC ~oard. See. Appendix 4, Setup of the DIP switch, .p. A-;. Formatr) GBIT . eX, ) c, Y, A X Channel number (0, 1) C : Txpe ofsi9n81s . ID ........ Input dClta s.ignals le ........ Input contro'l signals Y Pin number 0 ......... 1),19 1 ......... 12, 110 2 ; .. : ';i . " . .13, III 3.. ....... '1(112 4 ......... 15 4X $#.,### C· j,: . • Example) ,'1!" I.'; ,).i, . 'Th!~' p~9~r~~ 9':u1r,~:s., c,la~~ .i:n. the .follo~ing .format, ~lJY~ere Sp,CR, and LF signify a space code, CR code and LF code, respectively.. . . . . . . .. .-. . ! '.' Addendum) 5 ......... : 16 6 ......... 17 7 ......... 18 ,f!\: .~umeril? variabl~.~9r inputting data MZ·lE02 6. A SIMPLE PROGRAMMING EXAMPLE The GBIT command verifies the logical level of a pin designated by the numeric expression Y for an input signal designated by the character string C for a channel designated by the numeric expression X, and assigns "1" to numeric variable A if the state is ON (high level) or assigns "0" to numeric variable A if the state is OFF (Iow level). If (X, J is omitted, a signal on channel 0 is verified. Example) Sample program describing data transfer with automatic handshaking mode using two sets of main unit Model 3500 series. 10 GBIT "IC",2.A 20 IF A=l THEN "ERR" 10 GMOOE u, "0", "Pt", "8 ' ................ Sets the mode (Output port). 20 A$:='· SHARP J 30 L level). X [X, 1 C, Y, Z Channel number (0, GOUT O,A$I ............ ·······Output character date "SHARP". GOUT 0, CHR$ &FF; . ···············Output ending code "CHR$ &FF". GMOOE 0," 1··, "A", "8"· . ······Sets the mode (Input port). "'() r, 1NO. B$. CHR$ &FF ............•.•.•. 'Input character data. \40 50 This program checks signal 111 on channel 0, and branches the program to line iabel "ERR" if the signal is ON (high Forma(2) GBIT 11 Example 11 C : Type of signals OD ....... Output data signals OC ....... Output control signals Y Pin number 0 ......... 01,09 1 ......... 02,010 2 ......... 03, 011 3 ......... 04,012 4 ......... 05 5 ......... 06 6 ......... 07 7 ......... 08 Z Set of signals ~g ~~6P A$;8$ 10 (i,IOOE 0,"1··,",,"","8"··· . ···Setsthe mode (Jnputport). 2u GIN U,A$,(.Hf($ 8.FF···· ········lnput character data. 38 GMOOE 0, "0", "A··, "8 '·················Sets the mode (Output portl. 40 i3$",··tlode 1-350L)·· j50 GOUT 0,13$1 .....•...• 160 GOUT 0, (;Hf($ &FF 1" ··············Output character data "Modal-3500". ···················Output ending code "CHR$ &FF". 70 01SI-' A$;8$ 80 END Execution results "SHARP Model-3500" is displayed onto the both of CRT A side and B side. Cable connecting table When executing program, use the cable corresponded as follows. 0 ......... OFF (Iow level) 1 ......... ON (high level) Side A Signal name When the character string C indicates that the signal is an output data signal, this command sets a pin designated by the numeric expression Y to ON (high level) if the magnitude of the numeric expression Z is "1", or sets the pin to When the character string C indicates that the signal is an output control signal, setup of the DIP switch on the interface board functions inversely. If (X,) is omitted, a signal on channel 0 is set. Example) No. No. 1 25 11 3 5 27 12 29 13 04 05 06 7 31 9 33 OlD I J. : : .. level). 35 37 17 _~ 39 18 19 __ 41 43 1 110 01 _-'-'-- >< 11 2~ __ ?~_ --- 31 15 ~3 16 35 17 37 _.~8 39 19 41 110 43 --.~ __ ~-- - - _.9 05 06 11 ... ~ ...><--. 19 02 03 04 17 07 08 09 19 010 13 - 16 3 5 7 15 o All GND (ground) contacts must be connected with those of partner. o Unused contacts are open. 7 14 15 11 12 __ 14 , 13 ~-----,--?9_ _ This program sets signal 09 on channel 0 to ON (high level) if DIP switch 1 on the interface PC board is set to OFF. If the DIP switch 1 is set to ON, the pin is set to OFF (Iow Signal name 02 03 _08 09 10 GBIT "OC",O,l Contact 01 07 OFF (Iow level) if Z is "0". Side 8 Contact ~xample Example 2 ) " 3) SampJI:! pr.ogram de~c;ribing. cfClt~_ transfer, with .00Cinual mode· l,Isjng.·a_. mail"") ljnit _MpQe_I-3500 seri.es and' printer [MZ'1 P02]" Sample program describing data transfer with manual mode using two sets of main unit Model~350n ~eries. 10 G81T-'o:;;aC",,3-.-0-:;.;, ... ;. _____ ..-_~._ Output controf_~ig;'-al"~12 OFF. ~g '~~~~i),:;~~i:-;:~ ,- GMOOE 0, "0". "8" ....... -----.---.----- Sets the .mQge ,(OjjtP~t portJ. GOUT O. "O".A .-.~---- ••.•• -._------ ____ Output numeric data A. G8IT 0, "OC", 3.1 .---.---- ..••• -------- Output control signal 012 ON. la Gt:loDE' 9:,"~:> "8' ',",''''''''''- ---,---",Sets themdde- (Ou-tpuipon). G8lT 0." le" .2. x ........ ---- ..... ----- Verify input control signal 111. ?O ~I3IT O. "Ot;" ,I, 1. __ .. __ .... __ . _____ ...... Output control signal 010 ON. IF x-a THEN 70 3,° B""ATO 0A' DC ,O,t. _____ .. ____ ~ " ONPU r;PR1ME s.."nal·, " ; j' 'i6 :G06"t'-:·6;·;··b;";iV-:--·~-~;---.-- .. -----.----- Outilut numeric da'i:~ B. 500 IF .'1=0 THEN END ·----·---··.Output control srgnal 09 ON. 100 G8IT. O. "DC" ,~,O j-.; •••••. ---n--n----Output control signal 012 OFF. 60 GOUT 0, "IJ" ,A " __ n.n_.n._., {DATA SI RO~e signal at printer}. 1-10 GBH 0, '.'IC." ,2, X ., .. -------.•. --.----- Verify inp~t control signal 111. 70 GBIT 0 "~C" 0 ···--------··Output numenc data. IZ,j If7.·X=I·THEN 110 ' _ _ _ _ _ _--"~-' ,.,. n'" ,""I'Q" 1-3e.:-G-1'18eE-:-e'..,.....r! '8 1 Se~the-mod.e-{·I:np,!:.it'-portr. 80--Gs:J:.~Q-,-!!0'Gll-rs-i+ nnn.-----.. --- •. -'.'crrtput.coh.t~o -sigRa":' 9-QFF;-e~ 140 GIN' 0" ;"0"'; t '.. ,.. ~'-': -----.. -----...... Input numerrc data. 90 GBIT _0, "I.Co";O, 8 '--·--·-··--···----:--~:-·Verif.y ,input contrpl'signal' 19; 150 OlSP A:"+":8:"=":C i~g ~6 ~DI4~HEN 90 IBUSYsignal at printer):._ 40 50 60 70 80 "i";"". 01 o· 160 END . .2QO OATA:·i":,83.72,Q5.82,8Ij.10 210 [lATA :31:,83, 72, 05.82.80,10 220 DATA :30:,83, 72 .65,82~80, 10 ~~g g~~~ i~I'~h:;::;~~;~~~~:::'1.0 ,: "i fa GBH' '0 ,':'QC" .2;0 .-.- ..•. ---------------- Output control singal 011 OFF. 20" GEtl TO., "le:' • .3, x •••_--------•• ---------- Verify inpUt contml signal 112• .. J'--30_ IF ')::1' -THEN' 20 1' ' , 4d ~MODE '-d', "1", '~B" -.. -------------------- Sets the mode (Input port). so GBI T 0," LC" ,3, X ----- __ ••••• ___________ Verify input control signal 112 60 IF X=O THEN 50 70 GIN 0, "0" ,A ---------- ______________ .•.. Input numeric data, 80 G81T 0, "OC" ,2 ,1 ---------------- ...... Output control signal 011 ON. 90 G81T O,"IC",3,X ----·····-------------Verify input control signal 112. . 100 IF )(=1 THEN 90 1,10 '120 130 14';" ISO 160 170 LF ,code Function code designating character pitch and double width. GIN 0, :'.0" .8_.--------~,_--------- •••.•• _._ Inp!JJ numeric-data. '01'31" '''A=''':A:OISf'_ "B=":S ,--, C=A+8 ('-MO[lE C)! Execution results Executing this program gets the following kinds of character on printer. "0", "S" ------ ---------- •• ---- Sets the mode '{Output portl. GOUT 0, "0". C -------('-S11 0,"OC",2,(1 ---------··Output numeric data C. ----·--------Outputcontrolsignal 011 OFF. ENO SHARP ·----------------··---Character pitch to 16.5CPI. SHARP --------··-----Character pitch to l6.5CPI, double width mode. SHARP ----------···----Character pitch to 10CP!. S H A R P -'---Character pitch to 10CPI, double width mode. Execution results Result is displayed at A side after calculating at B side the total of two numeric datas which is input through Aside. Cable connecting table When executing program, use the cable corresponded as follows. Side A Signal name Contact 01 02 03 1 3 5 7 0' 05 06 07 08 012 11 No. Cable connecting table When executing program, use the cable corresponded as follows. Side B Contact Signal No. Name ~ain Signal name 11 25 unit side Contact N,. Printer side Contact No. , Signal name 27 12 01 1 29 13 02 3 , 31 33 14 5 15 03 04 .3 4 7 5 DATA B.IT4 11 35 16 05 13 9 6 DATA BIT5 37 17 15 39 '8 112 01 02 03 0' 05 06 07 0' . 011 23 47 25 1 " 27 13 29 14 15 31 33 3 5 7 , 16 35 17 37 11 13 IS 39 15 111 45 21 . 11 7 DATA BIT6 07 13 B DATA Bin b'B 15 9, DATA B1TB 0" 010 17 1 DATA STROBE 19 41 31 INPUT_PRIME 11 BUSY 43 10 ~ LEDGE 45 47 12 PAPER END 13 SELECT 111 112 o All GND (ground) contacts must be connected with those of partner, o Unused contacts are open, 8 DATA EHT3 06 '9 110 o All GND (ground) contacts must be connected with those of partner. o Unused contacts are open. DA1'.A BIT1. DATA BIT2 MZ-lE02 2. 7·BIT ASCII CODE TABLE 8. ERROR CODE TABLE Error code number Meaning lE R NI (odd number) PariW error in data entry. 121 123 Improper input data in automatic handshaking mode. 125 The data entry variable overflows in automatic 127 handshaking mode. Improper output data in manual mode. Note) An erroneous program step indicated by an odd number error code (ERN) can be skipped using the ON ER ROR statement. Error code number Meaning lE R NI (even number) Hardware error. 120 122 124 Improper operand in the command word. Improper setting of the logical polarity, improper setting of the pin number, or improper setting of the end code, Note 2) For error codes other than those listed above, refer to VI. "Error code list" of the MZ·3500 BASIC LANGUAGE MANUAL Appendix. Note 2) 9. INPUT CODE TABLE Input data is processed as the following characters or functions in the Model·3500 Business Computer Main Unit. 10. MZ-1E02 CONTACT SIGNAL TABLE 1. 8·BIT ASCII CODE TABLE ~ 0 1 e-'c-'- 2 1 0 • ISP ~ @ P A Q • 2 B R • 3 C S , , , • D T d , 5 E U , & 6 F V f - 7 G W 9 + -=-itI D -"- Note 1) Note 2) 7 6 0 ( B 5 1 1% --;- • ! $ 7 3 - 8 H X D , Cl _e y • " • y w I Y i y , J Z j ,I... K [ k I < L ¥ I : M ) > N 11 0 - /? 0 _ " " D E F , , Following table shows the contact and input/output signal of the interface [MZ~1 E02] coordinated with the each loose wire of optional GP I/O interface cable [MZ·1C19]. (The cable consists of 50 pes. of loose wire and they are distincted from each other, with 5 kinds of calor and number of colored 2 kinds.) I- " f11 h ["I11III Con .. cl + ",, , ,• ,• • • " " - e :::L , p ("" a """1 \.. ..J I m C • ,1+ , ~ B 1: 9 ~ 9 q b h 8 L ~ LF Carriage Return Line Feed SO Shift Out SI Shift In SP Space Character codes which are left blank in the above table are used for Japanese characters, except for the character code 00 on the SI side. " " " " "" , r '" '"" " " " " " 10 J LF: Carnage Return Line Feed SP: Space Character codes which are left blank in the above table are used for Japanese characters, except for the character code 00. 9 Signal ".me Wit! calor " '" " '" " Oronge OrB"ge Gr.v GraV Wi11" Mork calar ." ." BI.c~ Whl" Yellow Block Yellaw Block " '" " '" " '" '" '" '" '" '" '" '" '" " Pink DO DO flnk Black O""IIe O""Il e Black GroV Gr.v Whit. Wi11" Yellow Yellow Pink Pink Orange Orango G"v G"y Whi\. Cont ... ,,- Si91'111 , ,, "'" '"'" '" " '" , , .,' , , .,' , ." ,, ." I ,, ." ,, •• ,, •• I ,, •• ,I ,, ." ,, ." ,, , "'" Block '" '" 0" Number of mark. Black Black Black Black BI.c~ BI.c' " " " " ,."" "'" '" " " " " " " " "'" '" '" nOm' " '" " '" " '" '" '" " '" '" '" '" '" '" '" Wire eclor color White Block Yellow Yollow Pink Pink 0,""11" O,.nEPl' Grav Grav White ." Block ." ." Block Block .,' .,' Block White Block Yellow y.llaw Block Pink ." ." ." ." .'" Number ofmork. ,, , , , • • • • • • • • • Blotk • Orange BI.. k M.ny Groy Groy BI.ck Many M.ny ,,~ Orange Wwito '" '" '" Yellow Natul.d Pink '" '" Mark White Yellow Pink Block '" ". Block Bl.ock Many M.ny M.ny M,ny Many Many M.ny 'MZ-IE02 11_ SETUP OF THEiDIP'-SWITCHi' ., 5. The message as sti9YY~rf~~:~Frg. 7"a'~pJiih~~)wt)e'n3:tj'~ t~;i normally. __ _----------_. . _.,---The DIP switc~(t'h the interface PC boar'dls\ised to estaolish th~si~t~ ,of thErQutput -co'nir-QI~5igr::!al.s Jmmej:fiately after powe~ - ... · ! Fig. 2,-----------,::-.-,-,--,-:-:-:--, ~1{S-~Efef~~'-S~itc~-e-d dn.;:thlltlg!c~1 pol~rj~y "2f ,t~e;9~tPjjt;'cohtr6~ ~rgn~ls, ~tc. - ---_. - -- -"~i - ,, i -, L~.1tcf:t-:~ . I , ' Switch position ~ig!1al "I :-~; · ii I OFF . -I 3 - - I:' • -" OF.F Positive ,'/ OFF (IoW lavel) ON°, dN 912_ (hiah i'evert (high IEllieD- off 011 I"~c I, - qN j Of-F (high le~el! OFF'- ON (high le~el) (Iow le~el) ON - DIP '-'- I OFF (high [aveil ON OFF (low!evei) (high Lev,ell OFF ON logic (Iow level) Jhigh level) Negative logic' Positive logic ON OFF Negative logic Positive , logic - (hign levell-- (low'l~vell OFF --"-Oi\J (high leve;r) how le~en ON _ (high le'!ell_ OFF (Iow level) Negathre ON ":Iogi(; , (high levell OFF (Iow level) >11 (high I~vel) --i'OFF (Iow level) ,I If there is any failure, the bit in failure will be shown on the display. Example: The m~ssage-,!as-sho~m 'i:Mlow-'app~ear's \..vhen bits 1 and 2 of the I/O port is in failure. 'i'_)' -I' .' ," P).M.~:"lE02JR.S2~2C_IIE ~WB) .', ' . C ' , . . . ' c(:!)" i:Jia~n6~Hc' iii6gr~mdisketie (UK9G-".oH3 CSZZ) (4) C.ble(UKO-GG0078CSZZ) • '.', (;1- MZ-3500 GPl!O CHECK OK 1\·'1 '.I ~99Js:r,~h'ir~vd, :f; -~:. 'n .); ,:,' (1) MZ-3500 Personal Computer ') ..- READY - ON 12_ MZ-1E02 (GPIO}'TE$TPROCED-' ;~J~,!EJ' ' ")\.1 Space Key)' 'Tuin'.1! dip switch"" Off;:bUhe .~dal'd:ta;be:tested when the above message is displayed, then push:We SPACEBAR. The test is satisfactory when the following message appears . -- after-depressronoftheSPACEBAR. I .. ";..;, - (Push ON (Iow ievell ~ The: teve-I of each -bit 'in' accoraance with Syntax :3 o.f the G'OUT -c~mrhand, Cir the value of.the numeric expression Z in accordanc~; ~i~~_I,~XPH;tln,;4,-f?f.thJ!:~~,IT ?omman~,. ,.::));)';'1::':;;; '~ __ j SWaN ,- _:Qutput level in manual mod.a Positive logic Negatiye logic _ [evel) ,(jowON, 010- : po~arjtv ON. 6N •• : Logical (loiN rev'el) _ 09 __ (- Initial state OFF OFF C' 1 .~ I '! -- ends '. • •• ii~ I. , READY. >11 '11 1 MZ-35.oO GP I/O CHECK ERROR I Testproce"diire! .' •!, !.J' j i I .~ • i '-, J,.Fi,~jt,h.~j9Btiqoal,slqtJ 2. 2 bit······ERROR Insert the board to be tested in the slot number 3 or 1 of ,Cha,ll,{lel 0.,. And, inse.rt the, testing board in the slot number 2 or 4 of Chan·nel 1. Keep;~he-'board t~ be tested in Ch-ar:mel--O- at all times and . change the_'testing boar_q in CJ;.annel' 1 after each test. Fig .. 1 ~ '.'. ,SlOt.·· ,3 _ 1·. 4 2. ~~--~- Channel.o Channel 1 NOT~': : B~.tore -lfjsertir;i.g the ,bo~rd ,in the:,slot;-_make ,sur:e that all dip s~itches are in OFF:'position. Any dip-'switch turned ON must_be set OFF. ,3.'- Connect . :~edicijted 4. 1 bit······ERROR p.n.! pn,the.baqk of the,MZ-3500. b~ards' using' the cable' (UKOGGOO.78CSZZ) fq'r this service. , Error may also be iniJicated when the SPACEB~R is pushed after turning all'dip switches ON. (Error message) _tbit .... 2 bit ......... 3 bit ......... 4 b-i t ......... ,5 bj t .. : ...... 16 bit ....... -7,bit ......... 8 bit. ......... 9b It lOb i t n-br t 12b It· Insert the diagnostic program diskette (UKOG-0143CSZZ) in the MZ-3500 floppy disk drive and turn power on. The test starts automatically after power on. SIgnal line 01 or 11 in failure • 02 or -12 in failure • 03 or 13 in failure 1- 04 or 14 in failure • i 05 or 15 in failure • 06 or ,16 in failure • 07 or 17 in failure 1- 08 or 18 in failure Dip switch • 09 or 19 in failure rem~iils'ON. • 010 or \lO in failure • • , 011 or III in -f~ilure ';' 612'~r:112 i~fai1ur'~ • ERROR ERROR ERROR ERROR ERRPR ERROR ERROR ERROR ERROR ERROR E,RROR ; I , . ,I; ERROR ;) , .. " ~ '-, . , , I.. ' I, ,- , : , , NOTE: Be· sure to turn power off before accessing of the board. 10 ~ ~ ."v IREQ 0 R' )~1I-4 '" 2BB o ;oV ,co '"'''eo -15 , le i17 J :.tLsoo LS27 B ,,'" 1 _ 2'(12 lOOP 1R: ~ 3 LSIO .e ~6 ,- '" se WR , a ~'" m ~ e ~ LS3Z ~ LS3Z ~4B V '00 , D1 30 U4 D3 ~l 00 ~21l' l::::::J. 00 "--" '" PI I---l!' 'IJ [)7 •M -i" ~:i "wo '''' 100 cs ,\9 \10 B AO '00 ~IWE 100 ~O CS 20 OF. .....:=:J:S ~A9 q, R1~ BA6 P'AZ ~AI ~A3 P A4 ~AS 2\I1'E 100 20 DE I" 16 ,J1;= R ~ ~ .~B F;A~ \'«121 2,\ ·5 8Z55 V"" " ~ 110Vce ""~ 9 , " e Al , '" 4A 58nS G:>:~ rlr Voo Vc<,~ 12 07i DSp.t:: DS~ DIm:=D21W-1J3m-D4Hi-- D01~ f);~ D4~ g~lW-- ~A U3Ht-D~m::= Dll-lJ.-- 9 "",~3821658725 1__,' ," ""Ii¥== 4D 13 L500 " cC 7 G:\D , 1, 14 IS PC2 17 'PCl'6 " " ~2~ reo ~~~ 1'!\.5 38 37 n4~ m T'A2 '" ," 4 ..~ , ,'eo , ""'b I IL '""'~ f,~lt~ "". :: ~ ': '00" ;; """" ,c. eo, :. wo ' " 0 ; / ; ' . w" ,,'''' " 4 ~ 6 3 '" cooo 2 '1"\' 5 " '''' , 11 r; '" , 12 Vcc ~ ,rCC, 10 'lee ~ ~ "" " " " '';;' 2 T 58 ~--' 3C " rfiC\ ~ 12 "m ,co'" • AO " "" -+ 01 ~RO~rl-4 10 5 CKCL "" 41P ~: 'w ;J;'"W ""'" ~ ~ ~o AI210 "R ,.c 2 All 9 2L~ ~ ""," mu ,,,'" ,0 , I.S27 ,., V" 10 DP~9 ~:;[c:~3~12 I 5]26 4 ,"" ~_ j ,~6 1 .'15 A7 "0 ,"0"' "." o '" , '0"''''' V" 0 0" .- ;;~ co m 'H ,; •• """"''' >V"",," c I. IL :=;l f ~ 5 I.SM 6 - , =-~ 7L-2 :< -" .1t.1C 3 '" ~llm """' ~ <f.1!1 ;/; !o lA \>' ;; "' \~;;I; ~-(,]...9 ;; IS 1.0><6'In !.i.. ~ ~ ~ ~ lKX4 ~p~ 1 3 (291 0 1B ~!l "" 14 ClII "" "" --., --{Q) 0 --@ ~8 ~51 ~l 1 12 ~11 111 110 "" "" -@J -@ -@ 0 0 ~h o\2('l;l: -@ I 9 -@c ~ ~ ," " " s:: > ~ :xJ c ~ s:: :::r: m (J) (') (') III 21' ( ~ N '" Thc C'-cn numbers nre GXD'" G:>:D-'----"--_ 0.1,,' 12\' <15 ycc--t----r---- ..... ", 17, " " " o~nn~NOr oc o '1~ -(9)C -@~ {Q)C -<0" -<wo C 0" rC- ~ ~ 00 --{Q) 0 Vcc '"..r:::: • ><0-' '" :\ia.~ 1Q,..,~11~ ,~~ 6 , :r.f'---- '" , 10 LSHX2 41Px12 3 ::tFc' " P!I 'S- ~ 5 lKX ~U38 ~ ~ e 10 le .E~ I~a="':: 1::8~ ~.u=:= ~~ , ~ a="':: ~ ",,; ~ llt?~ .. ~1D ~e ~1S,~ v" ----1.J..1. 2C lOKX4: IKXB Vo, Cable side " "c::"':: 7438X2 NI s:: ~ ..... 0 N trl - ~ t:< MZ·1E0;2 14. MZ-1E02 COMPONENT LOCATION CPU Side B GNO Vcc RO DO 02 04 06 AD A2 A4 A6 No Cable Side A 1 2 3 GNO 4 Vcc 5 6 SYSRES 7 ijiffi 8I 01 03 9 05 10 07 11 A1 12 A3 13 A5 14 15 A7 A8 A10 A12 16 A9 17 An 18 19 20 TORQ 21 Ml 22 MREQ 23 24 2& 26 27. RoM x 28 29 GNO 30 SLOT GNO (PARTS SIDE) 12 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 0 0 0 o. 1 2 3 4 5 6 7 8 9 10 0 0 0 0 0 0 0 11 0 12 i 1 i .2 i 3 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 32 34 36 38 40 42 44 46 48 GNO 50 i i i i i i i i i 4 5 .6 7 8 9 10 11 12 31 33 35 37 39 41 43 45 47 49 ---- (PARTS SIDE) MZ·IE02 15. PARTS LIST [I] Electronic parts NO.. PARTS caDE 1 2 3 4 5 LANGTI013ACZZ QSOCZ6424ACZZ QSOCZ6440ACZZ QSW Z9660KCZZ XBPSM30P06KSO 6 RMPTC4 10 2QCKB 7 RMPTC~ lO3QCKB 8 RMPTC8102QCKB 9 VCCCPA1HH101J 10 VCCSPU1HL470J 11 VCEAAA lCW3 3 6M 12 VCKYPA1HB102K 13 VCTYPA lNX 1 04M 14 VHiM58725P 15 15 VHiM74LSOO/ 1 16 VHiM74LS04/ 1 17 VHiM74LSIO/ 1 18 VHiM74LS126 1 19 VHiM74LS14/ 1 20 VHiM74LS27/ 1 21 VHiM74LS32/ 1 22 VHiM74LS74/ 1 23 VHiM74LS86/ 1 24 VHiM7438/// 1 25 VHiUPD8255/ 1 26 VRD RV2EYIOOJ 27 VRD RV2EYIOIJ IlJ PRICE RANK NEW MARK AH AE AG AR AA AC AC AD AA AA AB AA AB AZ AE AE AE AH AM A F AF AG AF AE AV AA AA PART RANK C C C B C B C C C C C C C B B B B B B B B B B B B C C DESCRIPTlaN Angle for connector le socket 24pin) le socket 40pin Dip SW. Screw Block resistor l.OK,nX4 1/8W +10 0 Block resistor lOKOX4 1/8W +1O%) _ Block resistor (l,OKnXB 1/8W +10%) Capacitor 50WV lOOpF Capacitor 50V 47pF Capacitor 16WV 33"F) Capacitor 50WV 1000pF Capacitor 12V O.l"F IC IC IC IC IC IC IC IC IC IC IC IC Resistor lOOJ O.5W Resistor 1/4W lOOn. +5%) Accessary NO. 1 2 3 4 5 6 7 PARTS CaDE SPAKA1087ACZZ SPAKA 114 OACZZ SPAKA 1141 ACZZ SPAKCl 0 8 6ACZZ SPAKC12 4 2ACZZ TiNSEI068ACZZ RMEMRIOQ6AC19 PRICE RANK AC AH AA AF AP BB BF NEW MARK PART RANK D 0 N N D D D D DESCRIPTlaN Packing Packing Packing Pack in cushion for master cushion for 1 E03 cushion for 1E03 case for master Packinll case Instruction book Master media W MZl C19(MZl E02) NO.. PARTS CaDE 1 SPAKAll05ACZZ 2 SPAKC1206ACZZ 4 TSELF1002ACZZ PRICE RANK AD AU AA NEW MARK PRICE RANK BK BN NEW MARK N N N PART RANK D D D Packing- cushion Packing case Sealing label PART RANK E E Diag media Cable unit DESCRIPTlaN [I] Taals NO.. PARTS CaDE 1 UKOG O143CSZZ 2 UKOGG0078CSZZ DESCRIPTlaN 13 ,I"~ , SHARP SHARP CORPORATION Industrial Instruments Group Reliability & Quality Control Department Yamatokoriyama, Nara 639-11, Japan Y.F Jun. 1983 Printed in Japan
http://manualzz.com/doc/1943415/sharp-mz-1pol-service-manual
CC-MAIN-2017-13
refinedweb
8,632
74.79
It’s time to practice working with APIs. We can work with APIs on the frontend or backend, so we will practice both! Let’s show off our github account to people! We will add a list of our github repositories to our personal site so that people know how good at coding we are. We will be using the List User Repos endpoint of the github api Take a few minutes to see if you can get the API to work for you in Postman. You should be able to make a GET request, inputing your own github username, and see a list of your repos. For me, the request looks like this: GET Let’s look at the response. We get an array with objects inside. Each object represents one of our repos. You can look through the attributes to see all of the information that is available to you regarding that repo. Github even gives you other urls you can request to see expanded information. Let’s add this to our mobile site. To do so, we will need to use javascript. So, let’s create another file called main.js in the root directory of our project. touch main.js This is where we will put the javascript we are using. To make things more fun, let’s require people to press a button in order to see our repositories (instead of just displaying them) This means, that we will need to add a few things to our html file: In our JS file, we will need the following: Take a few minutes to try to do this on your own. It’s ok if you get stumped for a little while (Even I did for a bit creating this demo). Here is how I would approach it: index.html: Abe's site Hello everyone! main.js: jQuery(document).ready(function($) { function getRepos() { $.get(" .then(function(data) { var repoContainer = $('#repoContainer') displayRepos(repoContainer, data) }) } function displayRepos(container, repos) { $.each(repos, function(index, repo){ container.append(' ' + repo.name + '') }) } var button = $('#showRepos') button.on( 'click', getRepos) }); A few notes: jQuery(document).ready(function($) { ... }). This makes sure that your javascript doesn’t run until the browser has finished rendering the DOM. If you don’t do this, you’ll notice some very annoying and hard to debug errors idso that I can find them easily in my javascript getReposI use the javascript promise that jquery $.get()returns to wait to display the repos until after they have returned from the API call If you are feeling excited by this activity, try adding some of these: .catchfunction that will show an error on the screen when the API request fails. CORS (Cross Origin Resource Sharing) is a security measure that servers use. You can read up on it, but the details are a little hard to swallow at first. What you need to know is that often API requests will fail if you are serving your file directly from the file system. That is what we were doing in the example above. And example of this can be seen if you open your index.html from above and reveal the developer console ( <COMMAND> <OPTION> i). We are going to make a call to another API that enforces this standard. Paste this code into your web console (To get an inspirational quote from this API: $.get(' You should see an error come back that looks like this: XMLHttpRequest cannot load The 'Access-Control-Allow-Origin' header has a value ' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access. This error cost me nearly 15hrs at the first hackathon I attended. One common reason for this error is that you are not serving your content from a web server, you are just opening the file directly from your computer. You can tell this because if you look in your URL bar, you will see something like this: /Desktop/test/index.html When you serve files using a web server, it will look more like this: localhost:8000 But, we really want to include and be able to test this API. How can we? Well, we need to server our files on a server. Luckily there is a simple way to do this using a built-in python function. In your terminal, navigate into the base directory for your site (where you have index.html). Then run this function: python -m SimpleHTTPServer You will see something like this: Serving HTTP on 0.0.0.0 port 8000 ... That means that your site is being served on a simple web server on port 8000. To see your site, visit Now, let’s try the API command from before: $.get(' It should work! If you change the code like this, you should see the response printed: $.get(' console.log(data)}) You may sometimes see this error for other reasons (such as leaving out an API key), but this is always a good thing to check first! If we can access APIs on the frontend, why would we want to do it on the backend. There are a few reasons, but one of the most important is when you are required to use secret keys to access the API. If we include the keys on the front end, they will be accessible to anyone. This is a problem. Let’s say you are using an API that costs you $0.01/request. If someone gets ahold of your key, they could make unlimited requests on your account and rack up quite a bill! Let’s practice this. We’ll modify our service so that people can text the joke to a friend! Here is an overview of how we’ll do this: Viewin Django) that will accept the phone number and call the Twilio API to send a text Let’s add another url and controller to the app. We’ll send the phone number and the text of the joke to this endpoint. Then, this endpoint will trigger the Twilio API to send a text message. Then it will let our frontend know that everything worked (Or send back error text if it didn’t). Create a new controller inside your views.py file. You can add it underneath your Home class. You will also need to import HttpResponse: from django.http import HttpResponse from django.views import View from django.shortcuts import render from django.http import HttpResponse import pyjokes class Home(View): ... Your Home Code here ... class TextJoke(View): def post(self, request): print(request.POST) return HttpResponse("Success") Then we need to add this to our urls.py file. Add the import and a line to the urlpatterns. from django.conf.urls import url from django.contrib import admin from jokes.views import Home, TextJoke urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', Home.as_view()), url(r'^send-text', TextJoke.as_view()), ] Great! Let’s visit our new endpoint to check it out. Run your server and visit Interesting…I saw the same exact page as our based route. There was a funny joke, but not what I was hoping to see. Why isn’t it working correctly? Well, it has to do with the order that our urls are listed in. Since the urls use regex, Django starts testing the requested url from the top down in the url list. In our case, it looks at r'^' first (which corresponds to nothing after the base url). The problem with this is that EVERY url will match this pattern, because there isn’t really any pattern to match. The way around this is the change the order of our urls. Bump the home page url down to the bottom of the list: from django.conf.urls import url from django.contrib import admin from jokes.views import Home, TextJoke urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^send-text', TextJoke.as_view()), url(r'^', Home.as_view()), ] Now if you refresh the page, what happens? I got a white screen. What were you expecting? I was expecting the text “Success”. Hmmm… Why isn’t it working? Go back to your views.py file and compare the code for the Home view with the code for the TextJoke view. One important difference is the name of the function inside the class. In the Home view, the function name is get, but in the TextJoke view, the function name is post. You probably guessed, this determines how you are able to access the endpoint. If we want to get the response we are looking for, we need to send a post request to that endpoint. By default the web browser performs a get request when you type in a url. To do a post request, let’s use Postman. Do a POST request to You likely got another error (Do you hate me yet???). Mine has a lot of text output, but this is the main part: CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. Feel free to research about CSRF verification. In short, it is a security measure to make sure that it is the frontend of your site talking to the backend and not someone trying to pretend they are your frontend. This is important if you are serving your html from you backend (That’s what we are doing in this example). What’s the solution? Well, Let’s move on to the next part of our current project, and we’ll see how it is handled. Let’s edit our template to add a form that will call our API endpoint. Text yourself this joke: Take a look at the code above: inputs are wrapped in a formelement. This automatically sends the data to the url in the actionattribute actionattribute is directed to the endpoint we created and then methodmakes sure it is a POST request {% csrf_token %}takes care of the security issue we ran into earlier (Django makes this easy) labeland inputfor the phone number make it clear to the user where to type their number inputfor the joke is hidden, and the value is set to {{ joke }}. This means that the current joke will be sent to our endpoint as well submit. This means it is will be a button that submits the form and calls the actionmethod Refresh your browser on the home page. you should see the form. Give it a try! You will be taken to the new page at /send-text/ that shows success! Next, sign up on Twilio for an account. Each account comes with test account credentials, so you shouldn’t have to pay any money up front. Go to Phone Numbers > Tools > Test Credentials (Direct Link) and take note of these two test keys; You will need them to access the API: Install the twilio python sdk pip install twilio Then, add code to send a text message to your views.py. I broke it out into a helper method called sendTextMessage. from django.http import HttpResponse from django.views import View from django.shortcuts import render from django.http import HttpResponse import pyjokes from twilio.rest import Client # Your Account SID account_sid = "AC23ca8d59856f5a920b63242af3b8b9e2" # Your Test Auth Token auth_token = "ce26ed0fb2dc5513e85d6c3ba716c1d9" # Instantiate the twilio SDK with your values client = Client(account_sid, auth_token) # Helper method for sending text messages def sendTextMessage(phone_number, body): return client.messages.create( to=phone_number, from_='+15005550006', body=body) class Home(View): def get(self, request): context = { 'joke': pyjokes.get_joke() } return render(request, "home.html", context) class TextJoke(View): def post(self, request): print(request.POST) phone_number = request.POST.get('phone-number') joke = request.POST.get('joke') try: sendTextMessage(phone_number, joke) except: return HttpResponse("There was an error sending the message") return HttpResponse("Success") Above, you will also noticed that I wrapped the sendTextMessage helper method in a Try/Except block. A Try Except block is a common pattern found in programming languages. You use it when you have a part of your code that may throw an error if something goes wrong. In this case, we wrap the sendTextMessage helper method in a Try block because if there is an error, we want to display a different message to the user. The except block determines what happens if the try block finds an error. In this case, we want to return the text “There was an error sending the message” if there is an error calling twilio, but return “Success” if not. A great place for a Try/Except block. Now, if you run this code and submit a valid phone number, you should see “Success” on the new screen. If you input an invalid phone number, you should see the error message. One thing you probably noticed is that in either case, you don’t actually get the text message. This is OK! Unfortunately, Twilio actually doesn’t let you send a real text message with test credentials. For that you need to sign up for a real account and pay a little money. Your choice if you would like to! But, we can still practice as if the text message is being sent, because if the twilio code doesn’t return an error, we know it worked! Congrats! You’ve got a form that calls an API.
https://www.codecrashcourse.com/integrating-with-apis/
CC-MAIN-2022-21
refinedweb
2,246
74.79
Index Copyright 1996-1998 by James Mohr. All rights reserved. Used by permission of the author. Be sure to visit Jim's great Linux Tutorial web site at Any time you access an SCO system, whether locally, across a network or through any other means both files and filesystems are involved. Every program that you run starts out as a file. Most of the time you are also reading or writing a file.. You can also use this understanding to evaluate both the system and application behavior to determine if it is proper. In order to be able to access data on your hard disk, there has to be some pre-defined structure. Without structure, it ends up looking like my desk where there are several piles of papers and I have to look though every pile in order, including. On an SCO system this is an area called boot0. Although there is only 512 bytes of data in boot0, there is 1024 bytes reserved for it. The code within boot0 is sufficient to execute the code in the next block, boot1. Here, 20Kb are reserved, although the actually code is slightly less. The code within boot1 is what reads the /boot program, which will eventually load the kernel. Immediately after boot1 is the division table. Under SCO, a division is a unit of the hard disk contained within a partition. A division can be any size, including the entire partition. Often, special control structures are created at the beginning of the division that impose an additional structure on that division. This structure makes the division a filesystem. In order to keep track of where each division starts and how big it is, the system uses the division table. The division table has functionality similar to that of a partition table, although there is no such thing as an "active" division. There can be up to seven divisions (and therefore 7 filesystems) per division, but the size of the division table is fixed at 130 bytes although 1024 bytes are reserved for the table. Just after the division table is the bad track table. A bad track is a portion of the hard disk that has become unusable. Immediately following the bad track table is an area that is used for alias tracks. These are the tracks that are used when one of the other tracks goes bad. If that occurs, the operating system marks the bad track as such in the bad track table and indicates which of the alias tracks will be used. The size of the area taken up by the alias tracks is determined by how many entries are in the bad track table. (There is one alias track per table entry) You can see the contents of your bad track table by using the badtrk utility. Once the table and alias tracks have been defined, you cannot increase the number without re-installing. Just after the bad track table are the divisions. If you have one of the older SCO UNIX filesystems (AFS, EAFS), there are two control structures at the beginning of the filesystem: the superblock and the inode table. The superblock contains information about the type of filesystem, it's size, how many data blocks there are, the number of free inodes, free space available and where the inode table is. Many users at not aware of the fact that different filesystems reside on different parts of the hard disk and in many cases on different physical disks. From the user's perspective the entire directory structure is one unit from the top (/) down to the deepest sub-directory. In order to carry out this deception, the system administrator needs to mount filesystems. This is done by mounting the device node associated with the filesystem (e.g. /dev/u ) onto a mountpoint (e.g. /u). This can either be done by hand, with the mount command line or by having the system do it for you when booting. This is done with entries in /etc/default/filesys. See the mount(ADM) and the filesys(F) man-pages for more details. Conceptually, the mountpoint serves as a detour sign for the system. If there is no filesystem mounted on the mountpoint. The system can just drive through and access what's there. If a filesystem is mounted, when the system get to the mountpoint is sees the detour sign and is immediately divert in another directions. Just as the road, treess and houses still exist on the other side of the detour sign, any file or directory that exists underneath the mountpoint is still there. You just can't get to it. Let's look at an example. We have the /dev/u filesystem which we are mounting on /u. Let's say tha when we first installed the system and before we first mount the /dev/u filesystem, we created some users with their home directories in /u. For example, /u/jimmo. When we do finally mount the /dev/u fileystem onto the /u directory, we no longer see /u/jimmo. It is still there, however, once the system reaches the /u directory it is redirected somewhere else. This brings up an interesting phenomena. When you use find to locate a file, it will reach the mount point and get redirected. However, nheck is not file and directory oriented, but rather filesystem oriented. If you used find you would not see /u/jimmo. However, you would if you used ncheck! When a filesystem is mounted, the kernel reads the filesystem's superblock into an internal copy of the superblock. This way, the kernel doesn't have to keep going back to the hard disk for this information. Figure 0-1 Boot Hard Disk Layout The inode is (perhaps) the most important structure. It contains all the information about a file including, owner and group, permissions, creation time, and most importantly: where the data blocks are on the hard disk. The only thing it's missing is the name of the file. That's stored in the directory and not in the inode. If you have an Desktop Filesystem (DTFS), then there is no inode table. Rather the inodes are scattered across the disk. How they are accessed, we'll get into later when we talk about the different filesystems. After the superblock (and inode table, if there is one) you get to the actual data. Data is stored in a system of files within each filesystem (hence the name). As we talked about before in the section on SCO basics, files are grouped together into directories. This grouping is completely theoretical in the sense that there is nothing physically associating the files. Not only can files in the same directory be spread out across the disk, it is possible that the individual data blocks of a file are scattered as well. Figure 0-1 shows you where all the structures are on the hard disk. In most systems, there will be at least two divisions on your root hard disk. On ODT 3.0 systems these divisions will contain your root filesystem and your swap space. Although it takes up a division, just like the root filesystem, your swap space is not a filesystem. This is because it has none of the control structures(superblock, inode table) that make it a filesystem. Despite this, there must still be an entry in the division table for it. In OpenServer, there is a new filesystem at the beginning of the partition and the root filesystem is moved to place after the swap space. We'll go into more details later. (NOTE: That whether you have a the extra division will depend on what kind of installation you did. We'll cover this in more detail in chapter 13. Up to this point we've talked a great deal about both files and directories, where they reside and what their attributes (characteristics) are. Now it's time to talk about the concepts of files and directories. We need to talked about how the operating system sees files and directories and how they system manages them. From our discussion of how a hard disk is divided, we know that files reside within filesystems. Each filesystem has special structures that allow the system to manage the files. These are the superblock and inodes. The actual data is stored somewhere in the filesystem in datablocks. Most SCO UNIX filesystems use a block size of 1024 bytes. If you have OpenServer, the new DTFS has a variable block size. Every SCO UNIX filesystem uses inodes, which, as I mentioned earlier, contain the important information about a file. (In some books, inode is short for information node and in others it is short for index node.) Although the structure of the inodes is different for each filesystem, they hold the same kinds of information. What each contains can be found in <sys/ino.h>, <sys/inode.h> and <sys/fs/*>. Each inode has pointers which tell it where the actual data is located. How this is done is dependent on the filesystem type and we'll get to that in a moment. One piece of information that the inode does not contain is the file name. This is contained only within the directory. If you are running OpenServer, then there are at least three divisions used. The first one (slot 0 in the division table) is used for the /dev/boot filesystem. This contains the file that are necessary to load and start the operating system. Although this is what is used to start the system, this is not root filesystem. The root filesystem has be move to the third division. Once the system has been loaded, the /dev/boot filesystem is mounted onto the /stand directory and is accessible like any other mounted filesystem, except for the fact that it is normally mounted as read-only. In both ODT 3.0 and OpenServer, the root filesystem normally contains most of the files your operating system uses. Depending on the size of your primary hard disk and the configuration options you chose during installation, you may have more than just these default filesystems. Common configurations included having separate filesystems for users' home directories or data. Table 0.1 Filesystems Supported by ODT 3.0 Table 0.2 Filesystem Supported by OpenServer Although all of these filesystem are supported, not all are configured into your kernel by default. If you have ODT 3.0, you automatically have support for the three standard UNIX filesystem (EAFS, AFS and S51K) as well as the XENIX filesystem. In OpenServer, the three UNIX filesystems supported in ODT are includes, as well as the XENIX filesystems, and the two new ones: HTFS and DTFS. In order to be recognized they must be first configured in the kernel. How this is accomplished, depends on what product you are running and what filesystem. Table 0.1 and Table 0.2 show what filesystems are supported. If you want to use one of the network filesystem such as NFS, SCO Gateway for NetWare, and Lan Manager Client Filesystem, you need to add that product through the Software Manager. This will automatically add support into the kernel for the appropriate filesystem. If you have ODT 3.0, then you can use sysadmsh to add the driver for each of the other filesystems. On OpenServer, you use the Hardware/Kernel Manager. In both cases, there are mkdev scripts that will do this. In fact, these scripts are called by sysadmsh and the Hardware/Kernel Manager. Table 0.3 shows you which script is run for each filesystem. Table 0.3 mkdev script associate with each filesystem From the filesystem's standpoint, there is no difference between a directory and a file. Both take up an inode, use data blocks and have certain attributes. It is the commands and programs that we use that impose structure on the directory. For example, /bin/ls imposes structure when we do listings of directories. Keep in mind that it is the ls command that puts the file names "in order." Within the directory, the file names do not appear in any order. Initially, files appear in the directory in chronological order. As files are created and removed, the slots taken up by older files are replaced by newer ones and even this order disappears. Other commands, such as /bin/cat or /bin/hd, allow us to seeing the directories as files, without any structure. Note that in OpenServer these commands don't let you see the structure, which I see as a lost in functionality. When you do a long listing of a file, (ls -l or l) you can learn a lot about the characteristics of a file and directory. For example, if we do a long listing of /bin/date, we see: -rwx--x--x 1 bin bin 17236 Dec 14 1991 /bin/date We can see the type of file we have: the '-' in the first position says its a regular file, the access permissions (rwx--x--x), how many links it has (1 - we'll talk more about these in a moment), the owner and group (bin/bin), the size(17236), the date it was last written to (Dec 14, 1991. Maybe the time, as well, if it is a newer file), and the name of the file (/bin/date). For additional details on this, see the ls(C) man-page. Unlike operating systems like DOS, most of this information is not stored in the directory. In fact, the only information that we see here, which is actually stored in the directory is the file's name. If not in the directory, where is this this other information kept and how do you figure out where on the hard disk the data is? As I mentioned before, this is all stored in the inode. All the inodes on each file system are stored at the beginning of that filesystem in the inode table. The inode table is simply an set of these inode structures. If you want, you can see what the structure looks like, by taking a peek at <sys/ino.h>. To access the information in the inode, you need the inode number. Each directory entry consists of an inode number and file name pair. On ODT 3.0 and earlier, the first two bytes of each entry were the inode number. Since a byte can hold 256 values, the maximum possible inode was 256*256, or 65535 inodes per filesystem. The inode simply points to a particular entry in the inode table. This is the only connection there is between a filename and its inode, therefore the only connection between the filename and the data on the hard disk. Because this is only a pointer and there is no physical connection, there is nothing preventing you from having multiple entries in a directory pointing to the same file. These would have different names, but have the same inode number and therefore point to the same physical data on the hard disk. Having multiple file names on your system point to the same data on the hard disk, is not a sign of filesystem corruption! This is actually something that is done on purpose. For example, if do a long listing of /bin/ls (l /bin/ls) you see: -r-xr-xr-t 6 bin bin 23672 Dec 14 1991 /bin/ls Here the number of links (Column 2) is 6. That means there are five other files on the system with the same inode number as /bin/ls. In fact that's all a link is: a file with the same inode on the same filesystem. (More on that later)To find out what inode that is, let's add the -i option to give us: 167 -r-xr-xr-t 6 bin bin 23672 Dec 14 1991 /bin/ls From this we see that /bin/ls occupies entry 167 in the inode table. There are three ways of finding out what other files have this inode number: find / -inum 167 -print ncheck -i 167 /dev/root — we're assuming /bin/ls is on the root filesystem l -iR / | grep '167' Since I know they are all in the /bin directory, I'll try the last one. This gives me: 167 -r-xr-xr-t 6 bin bin 23672 Dec 14 1991 l 167 -r-xr-xr-t 6 bin bin 23672 Dec 14 1991 lc 167 -r-xr-xr-t 6 bin bin 23672 Dec 14 1991 lf 167 -r-xr-xr-t 6 bin bin 23672 Dec 14 1991 lr 167 -r-xr-xr-t 6 bin bin 23672 Dec 14 1991 ls 167 -r-xr-xr-t 6 bin bin 23672 Dec 14 1991 lx Interesting. This is the entire family of ls commands. All of these lines look identical, with the exception of the file name. There are six lines, which matches the number of links. Each has a inode of 167, so we know that all six names have the same inode and therefore point the same location on the hard disk. That means that whenever you execute any one of these commands, the same program is started. The only difference is the behavior and that is based on what program you actual start on the command line. Since the program knows what name is was started with, the program can change it's behavior accordingly. There is nothing special about the fact that these are all in the same directory. A name must only be unique within a single directory. You can therefore have two files with the same basename in two separate directories. For example, /bin/mail and /usr/bin/mail. If you take a look, these not only have the same inode number (and are therefore the same file), there are actually three links. The third link being /usr/bin/mailx. So, here we have two files in the same directory (/usr/bin/mailx and /usr/bin/mail) as well as two files with the same basename (/bin/mail and /usr/bin/mail). All of which have the same inode and are, therefore, all the same file. The key issue here is that all three of these files exists on the same filesystem, /dev/root. As I mentioned before, there may be files on other filesystem that have the same inode. This is the reason why you cannot create a link between files on two different filesystems. With a little manipulation, you might be able to force two files with identical content to have the same inode on two filesystems. However, these are not links (just two files with the same name and same content). The problem is that it may be necessary to create links across filesystems. One reason is that you might want to create a path with a much shorter name that easier to remember. Or perhaps you have several remote filesystems, accessed through NFS and you want to create a common structure on multiple machines all of which point to the same file. Therefore you need a mechanism that allows links across filesystems (even remote filesystems). This is the concept of a soft or symbolic link. Symbolic links were first introduced to SCO UNIX in release 3.2.4.0. In SCO OpenServer they are (perhaps) the primary means of referring to installed files. For more information on referencing installed files, see the section on Software Storage Objects. Unlike hard links, symbolic links take up data blocks on the hard disk and therefore have a unique inode number. However, they only need one data block as the contents of that block is the path to the file you are referring to. Note that If the name is short enough the symbolic link may be stored directly in the inode. See Table 0.4 for details on filesystem characteristics. Figure 0-2 Symbolic link For example, if I had a file on a /u filesystem named /u/data/albert.letter. I could create a symbolic link to it as /usr/jimmo/letters/albert.letter (no, it doesn't have to have the same name). The one data block assigned to the symbolic link /usr/jimmo/letters/albert.letter contains /u/data/albert.letter. Whenever I access the file /usr/jimmo/letters/albert.letter, the system (the file system driver) knows that this is a symbolic link. The system then reads the full path out of the data block and accesses the "real" file. Since the data file contains only a path, you could have filesystem mounted via NFS where the data is stored on a remote machine. Whatever you are using to access that file (e.g. an application, a system utility) cannot tell the difference. For example, I might have a file in my own bin directory that points to a nifty utility on my friend's machine. I have a filesystem from my friend's machine mounted to my /usr/data directory. I could create a symbolic like this: ls -s /usr/data/nifty /usr/jimmo/bin/nifty I would therefore have a symbolic link, /usr/jimmo/bin/nifty that looked like this: lrwxrwxrwx 1 root other 15 May 03 00:12 /usr/jimmo/bin/nifty -> /usr/data/nifty We see two ways that this is a symbolic link. First, the first character of the permissions field is an 'l'. Next, the name of the file itself is different than we are used to. Next, we see that the name of the file that we use (/usr/jimmo/bin/nifty) and a (sort-of) arrow that points to the "real" file (/usr/data/nifty). Note that there is nothing here that tells us that a remote filesystem is mounted onto /usr/data. The conversion is accomplished by the filesystem driver when the actual file is accessed. If you were to use just the ls command, then you would not see either the type of file (l) or the ->, so there is no way to know that this is a symbolic link. If you use lf, then the file is followed by an at-sign (@), which tells you that the files is a symbolic link. Keep in mind that when the system determines that you are trying to access a symbolic link, the system then goes out and tries to access the "real" file and behaves accordingly. Therefore, symbolic links can also point to directories, or any other kinds of files, including other symbolic links. Be careful when making a symbolic link. When you do, the system does not check to see that the source file exists. It is therefore possible to have a symbolic link point back to itself or to point to nothing. Although most system utilities and commands can catch things like this, do not rely on it. Besides, what's the point of having a dog chasing its own tail. It is also advisable not to use any relative paths when using symbolic links. This may have unexpected results when accessing the links from elsewhere on your system. Let's go back to the actual structure of the directory entries for a minute. Remember that directories are simply files that have a structure imposed on them by something. If the command or utility imposes the (correct) structure, then each directory entry takes the form of 2 bytes for the inode and 14 bytes for the file name itself. Another change to the system that came in SCO UNIX 3.2.4.0 was the introduction of long filenames. Up to this point, file names were limited to 14 characters. With two bytes for the inode, 64 of these 16 bytes structures fit exactly into a disk block. However, with only 14 bytes for the name. This often made giving files meaningful names difficult. I don't know how many times I personally spent time trying to remove vowels and otherwise squish the name together so that it fit in 14 characters. The default filesystem on SCO UNIX 3.2.4.0 changed all that. One thing I liked about having 16 bytes was that a directory entry fit nicely into the default output of hd. That way you could easily see the internal structure of the directory. I don't know how many times I used hd when talking with customers with filesystem problems. However, the hd included in the initial release of Open Server won't let you do this. In my opinion, removing that very useful functionality broke hd. Up to 3.2.4.0, SCO UNIX used the Acer File System (AFS), which had some advantages over the standard UNIX (S51K) filesystem. However, neither can handle symbolic links and long file names. The Extended Acer File System (EAFS) changed that. Since the directory entries of the AFS were 16 bytes long, long file names have to "'spill over" into subsequent entries in the directory. Since a file only has one inode, extended file names beyond 14 characters need to extend into consecutive entries in the directory. Since they are taking up multiple slots, all but the last inode entry has the inode number of '0xffff'. This indicates the file name continues on in the next slot. Even with long file names, files names on an EAFS limited to 255 characters When files are removed, the inode entry in the directory is changed to 0. Do an hd of the directory (if you're running ODT) and you still see the file name, but the inode is 0.. When a new file is created, the file name takes up a slot used by an older, previously removed file if the name can fit. Otherwise it must take a new slot. Since long names need to be in consecutive slots, they may not be able to take up empty slots. If so, new entries may need to be created for longer file names. When you create a file, the system looks in the directory for the first available slot. If this is an EAFS, then it is possible that the file you want to create might not fit in the first slot. Remember that each slot is 16 bytes long. Two for the inode number and 14 for the file name. If, for example, slots 16 and 18 are filled, and slot 17 is free, a file name that is longer than 14 characters cannot fit there. This is because the directory entries must be contiguous. The system must therefore, either find a slot large enough or create new slots at the end of the directory. For example, if slots 14 and 18 were taken, but slots 15-17 were free, any file less than 42 characters (14*3) would fit. Anything larger would need to go somewhere else. If you were to count up all the bytes in the inode structure in ino.h, you'd find that each inode is 64 bytes. This means that there are 16 per disk block (16*64=512). In order to keep from wasting space, the system will always create filesystems with the number of inodes being a multiple of 16. Inode 1 is always at the start of the 3rd block of the filesystem (bytes 2048- 2111) and is reserved (not used). Inode 2 is always the inode of the root directory of any filesystem. You can see for the root filesystem this by doing ls -id /. (The -d is necessary so you only see the directory and not the contents) ` The total number of inodes on an AFS or EAFS is defined when filesystem is created by mkfs(ADM). Normally, you use the divvy command (by hand or through SCOAdmin in OpenServer to create filesystems. The divvy command will then call mkfs to create the filesystem for you. The number of inodes created is based on an average file size of 4K. If you have a system that has many smaller files, such as a mail or news server, you could run out of inodes and still have lots of room on your system. Therefore, if you have a news or mail server, it is a good idea to use mkfs by hand to create the filesystem before you add any files. Remember that the inode table is at the beginning of the filesystem and takes up as much room as it needs for a given number of inodes. If you want to have more inodes, you must have a larger inode table. The only place for the inode table to grow is into your data. Therefore, you would end up overwriting data. Besides, running mkfs 'zeroes' out your inode table so the pointers to the data is lost anyway. Among other things that the inode keeps track of are file types and permissions, number of links, owner and group, size of the file and when it was last modified. In the inode is where you will find thirteen pointers (or triplets) to the actual data on the hard disk. Note that these triplets pointers to the data and not the data itself. Each one of the thirteen pointers to the data is a block address on the hard disk. For the following discussion, please refer to Figure 0-3. Each of these blocks is 1024 bytes (1k), therefore the maximum file size on an SCO UNIX system is 13Kb. Wait a minute! That doesn't sound right, does it? In fact it isn't. If (and that's a big if) all of the triplets pointed to data blocks, then you could only have a file up to 13Kb. However, there are dozens of files in the /bin directory alone that are larger than 13Kb. How's that? The answer is that only the first ten of these triplets point to actual data. These are referred to as direct data blocks. The 11th triplet, points to a block on the hard disk which actually contains the real pointers to the data. These are the indirect data blocks and contain 4-byte values, so there are 256 of them in each block. In Figure 0-3, the 11th triplet contains a pointer to block 567. Block 567 contains 256 pointers to indirect data blocks. One of these pointers points to block 33453, which contains the actual data. Block 33453 is an indirect data block. Since the data blocks pointed to by the 256 pointers in block 567 each contain 1K of data, there is an additional 256K of data. So, with the 10K for the direct data blocks and the 256K for the indirect data blocks, we now have a maximum file size of 266K. Hmmm. Still not good. Although there aren't that many, there are files on your system larger than 266K. A good example is /unix. So, that brings us to triplet 12. This points not to data blocks, not to a block of pointers to data blocks, but to blocks that point to blocks that point to data blocks. These are the doubly-indirect data blocks. In Figure 0-3 the 12th triplet contains a pointer to block 5601. Block 5601 contains pointers to other blocks. One of which is block 5151. However, block 5151 does not contain data, but more pointers. One of these points to block 56732. It is block 56732 that finally contains the data. We have a block of 256 entries that each point to a block which each contain 256 pointers to 1024 byte data blocks. This gives us 64Mb, just for the doubly-indirect data blocks. At this point, the additional size gained by the single-indirect and direct data blocks is negligible. Therefore, let's just say we can access over 64Mb. Now, that's much better. You would be hard pressed to find a system with files larger than 64Mb. (Unless we are talking about large database applications) However, we're not through, yet. We have one triplet left. So, as not to bore too many of you, let's do the math quickly. The last triplet points to a block containing 256 pointers to other blocks, each of which point to 256 other blocks. At this point, we already have 65536 blocks. Each of these 65536 blocks contain 256 pointers to the actual data blocks. Here we have 16777216 pointers to data blocks, which gives us a grand total of 17179869184 or 16Gb of data (plus the insignificant 64MB we get from the doubly indirect data blocks). Oh, as you might have guesses, these are the triply indirect data blocks. Figure 0-3 Inodes Pointing to Disk blocks In Figure 0-3 triplet 13 contains a pointer to block 43. Block 42 contains 256 pointers, one of which points to block 1979. Block 1979 also contains 256 pointers, one of which points to block 988. Block 988 also contains 256 points. However, these pointers point to the actual data. For example, block 911. If you are running an ODT 3.0 (or earlier) system, 16Gb is not your actually size limit. This is the theoretical limit place on you by the number of triply indirect data blocks. Since you need to keep track of the size of the file and this is stored in the inode table as a signed long integer (31 bits) the actual limit is 2Gb. As I mentioned a moment ago, when a file is removed all that is done is the inode is set to 0. However, the slot remains. In most cases this is not a problem. However, when mail gets backed up, for example, there can be thousands of files in the mail spool directories. Each one of these requires a slot within the directory. As a result, the directory files can grow to amazing sizes. I have seen directories where the size of the directory file was over 300,000 bytes. This equates to about 20,000 files. This brings up a couple of interesting issues. Remember that there are 10 direct data blocks for 10Kb, then 1 singly-indirect for 256K for a total of 266Kb for both single and doubly indirect data blocks. If you have a case where the directory file is exceptionally large, and the file you are looking for happens to be at the very end of the directory file, the system must first read all 10 direct data blocks, then read the 11th block that points to the single-indirect data blocks, then read all 64 of those data blocks, then it reads the 12th block in the inode to find where the data blocks are for the pointers are, then reads the blocks containing the pointers, then reads the actual data blocks for the remainder of the directory file. Since a copy of the inode is read into memory, there is no need to go back out to the disk. On the other hand, remember there are 64 blocks containing the singly-indirect pointers. Each one of them has to be read, then each of the blocks they point to has to be read to check to see if your file is there. Then you need to read the data blocks that point to the data blocks that point to where your directory is. Only then do you find out that you mis-typed your file name and you have to do it all over again. Since the system can usually get them all in one read, it is best to keep the number of files in a directory at 638 or less. 638? Sure. Each block can hold 64 entries. There are 10 data blocks, so the 10 direct data blocks can hold 640 entries. Each directory always contains the entries . and .., therefore you can only have 638 addition entries. The next interesting thing is what happens when you run fsck on your system. If the filesystem is clean, there won't be a problem. What happens if you have a system crash and your filesystem becomes corrupted? If during the check, fsck finds files that are pointed to by inodes, but does not find any reference to them in a directory, it will place them in the /lost+found directory. When each file system is created, the system automagically creates 62 files in there and then removes them. This leaves 62 empty directory slots. 62 files plus . and .., which gives you 64 total entries times 16bytes =1024 bytes or one data block. The reason for the lost+found directory is that you don't want the system to be writing anything to a filesystem that you are trying to clean. It is safe enough to be filling in directory entries, but you don't want the system to be creating any new files while trying to clean the filesystem. This is what would happen if you had more than 62 "lost" files. If you have a trashed filesystem and there are more than 62 lost files, they really become lost. The system cannot handle the additional files and has to remove them. Therefore, I think it is a good idea to create additional entries and then remove them whenever creating a new file system. This way you are prepared for the worse. A script to do this would be: cd /lost+found for i in a b c d e f g h i j do for j in a b c d e f g h i j do for k in a b c d e f g h i j do touch $i$j$k done done done rm * This scripts creates 1000 files and then removes them. This takes up about 16K for the directory file, however it allows 1000 files to become "lost”, which may be a job-saver in the future. Make sure that the rm is done after all the files are created, otherwise you end up creating a file, removing it, then filling the slot with some other file. The result is that you have fewer files than you expected. If you look in /usr/lib/mkdev/fs, (what is actually run when you run mkdev fs) you see that the system does something like this for your every time you add a filessystem. Just after you see the message: Reserving slots in lost+found directory ... the mkdev fs script does something very similar. The key difference is that mkdev fs only creates 62 entries. If you wanted to create 1000 entries every time you ran mkdev fs, you could change that part of mkdev fs to look the above script. Something that I always found interesting was that /bin/cp, /bin/ln and /bin/mv are all the same binary. That is, they are all links to each other. When you link a file, all that needs to get done is to create a new directory entry, fill it in with the correct inode and then increase the link count in the inode table. Copying a file also creates a new directory entry, but it must also write the new data blocks to the disk. When you move a file, something interesting happens. First, the system creates a link to the original file. It then removes the old file name by unlinking it. This simply clears the directory entry by setting the inode to 0. However, once the system creates the link, for a brief instant there are two files on your system. When you remove a file, things get a little more complicated. We need to not only remove the directory entry referencing the file name, but we also need to decrease the link count in the inode table. If the link count at this point is greater than 0, then the system knows that there is another file on the system pointing to the same data blocks. However, if the link count reaches 0, we then know that there are no more directory entries pointing to that same file. The system must then free those data blocks and make then available for other files. Some of you might have realized that special device files (device nodes) do not take up any space on the hard disk. The only place they "exist" is in the directory entry and inode table. You may also have noticed that in the inode structure there is no entry for the major and minor number. However, if you do a long listing of device node, you will see the major and minor number. Where is this kept? Well, since you don't have any data blocks to point to, then the 39 bytes used for the data block pointers are unused. This is exactly where the major and minor number are stored. The first byte of the array is the major number and the second byte is the minor number. This is one reason why major and minor numbers cannot be larger than 255. As with many aspects of the system, the kernel's role in administering and managing filesystem is wide reaching and varied. Among its tasks is the organization of disk space within the filesystem. This function is different, depending on what type of filesystem you are trying to access. For example, if you are copying files to a DOS FAT filesystem, then kernel has to be aware that there are different cluster sizes depending on the size of the partition. (A cluster is a physical grouping of data blocks). If you have an AFS (Acer Fast file System) or EAFS (Extended AFS), then the kernel attempts to keep data in logically contiguous blocks called clusters (on most modern hard disks, this also means physically contiguous). By default, a cluster is 16kb, but can be changed when the filesystem is created by using mkfs. When reading data off the disk, the system can read clusters rather than single blocks. Since files are normally read sequentially, the efficiency of each read is increased. This is because the system can read larger chunks of data and doesn't have to go looking for them. Therefore, the kernel can issue fewer (but larger) disk requests. If you have a hard disk controller that does "track caching" (storing previously read tracks), you improve your read efficiency even more. However, the number of files may eventually grow to the point where storing data in 16K chunks is no longer practical. If there are no more free areas that are at least 16Kb, the system would have to being moving things around to make a 16Kb block available. This would waste more time than would be gained by maintaining the 16Kb cluster. Therefore, these chunks will need to be split up. As the file system gets fuller, the amount the chunks are split up (called fragmentation) increases. Therefore, the system ends up having to move to different places on the disk to find the data. Because of this the kernel ends up sending multiple requests, slowing down the disk reads even further. (It's always possible since you can move data blocks from other files. However, this takes time and is therefore not practical.) Figure 0-4 Disk fragmentation The kernel is also responsible for the security of the files themselves. Because SCO UNIX is a multi-user system, it is important to ensure that users only have access to the files that they should have access to. This access is on a per file basis in the form of the permissions set on each file. Based on several discussions we've had so far, we know that these permissions tell us who can read, write or execute our files. It is the kernel, that makes this determination. The kernel also imposes the rule that only the owner or the all-powerful root may change the permissions or ownership of a file. Allocation of disk blocks is dependent upon organization of what is called the freelist. When a file is opened for the first time, its inode is read into the kernel generic inode table. This is a "generic” table as it is valid for all filesystems. Therefore, on subsequent reads and writes this information is already available and the kernel does not have to make an additional disk read to get the inode information. Remember, it is the inode that contains the pointers to the actual data blocks. If this information were not kept in the kernel, every time the file was accessed this information would need to be read from the hard disk. Keep in mind that if you have a process that is reading or writing to the disk, it is the kernel that does the actual disk access. This is done through the filesystem and hard disk drivers. Every time the kernel does a read of a block device, the kernel first checks the buffer cache to see if the data already exists there. If so, then the kernel has saved itself a disk read. Obviously if it's not there, the kernel must read it from the hard disk. At first this seems liked a waste of time. I mean, checking one place and then checking another. Every single read checks the buffer cache first. So, in many cases, this is wasted time. True. However, the buffer cache is in RAM. This can be several hundred times faster than accessing the hard disk. As a result of the principle of locality, your process (and the kernel as well) will probably be accessing the same data over and over again. Therefore, the existence of the buffer cache is actually a great time saver, since the number of times it finds something in the cache (the hit ratio) is so high. When writing a file (or parts of a file), the data is first written to the buffer cache. If it remains unchanged for a specific period of time (defined by the BDFLUSHR kernel parameter), the data is then written to the disk. This also saves times because if data is written to the disk, then changed before it is read again, you've wasted a disk write. However, if it stays in the buffer cache forever (or until the file is closed, the process terminates, etc) then you run the risk of loosing data is the system crashes. Therefore, BDFLUSHR is set to a reasonable default of 30 seconds. As I mentioned a moment ago, when a file is first opened, its inode is read into the kernel's generic inode table. (Assuming it is not already there) This table is the same no matter what kind of file system you have (S51K, AFS, etc). The structure of this table is defined in <sys/inode.h>. The size of this is configurable in ODT 3.0 with the kernel parameter NINODE. The entries in the generic inode table are linked into hash queues. A hash queue is basically a set of linked lists. Which list a particular inode will go into dependents on it's value. This speeds things up, since the kernel does not have to search the entire inode table, but can immediately jump to the relatively smaller hash queue. The more hash queues there are (defined by the NHINODE kernel parameter) the faster things are read since each queue has fewer entries. However, the more queues there are, the more space in memory is required and less room for other things. Therefore, you need to weigh one against the other. Since there is normally no pattern as to which files a removed from the inode table and when, the free slots in the table are spread throughout the table randomly. Free entries in the generic table are linked onto the freelist so new inodes may be allocated quickly. One advantage that SCO UNIX provides is the ability to access different kinds of filesystems. Because of this, the kernel must also keep track of filesystem specific information, such as that contained in the inode table. This information is also kept in a kernel internal table, based on the filesystem. The System V dependent inode data structure is defined in <sys/fs/s5inode.h>, and is used by S15K, AFS and EAFS. Other inode tables exist for High-Sierra and DOS. Each time a file is opened an entry is allocated in both the generic and the System V dependent inode table (unless already in memory). The information contained in these inode table is going to be different, depending on what kind of filesystem you are dealing with. When a process wants to access a file, it does so using a system call such as open() or write(). When first writing the code for a program, the system calls that programmers normally use are the same no matter what the file system type. When the process is running and makes one of theses system calls, the kernel maps that system call to operations appropriate for that type of FS. This is necessary since the way a file is accessed under DOS, for example, is different than under EAFS. The mapping information is maintained in a table, one per file system and is constructed during a relink from information in /etc/conf/mfsys.d and /etc/conf/sfsys.d. The kernel then accesses the correct entry in the table by using the FS type as an index into the fstypesw[ ] array Another table used by the kernel to keep track of open files is the file table. This allows many processes to share the same inode information, and is defined in <sys/file.h>. Because it is often the case that multiple process have the same file open, this saves the kernel time, by not having to look up inode information for each process individually. Once a file is open and is in the file table, the kernel does not have to re-read the inode table Figure 0-5 Translation from file descriptions to data By the time the kernel actually has the inode number of a file that you are working with, it has gone through three different reference points. First, there is the uarea of your process that has the translation from your personal file descriptors to the entry in the file table. Next, the file table has the references that point the kernel to the appropriate slot in it's generic inode table. Last, the generic inode table has the pointers to the file system specific inode table. At first, this may seem like a lot of work. However, keep in mind that this is all in RAM. Without this mechanism, the kernel would have to go back and forth to the disk all the time. The open() system call is implemented internally as a call to the namei() function. This is the name-to-inode conversions. Namei() sets up both the generic inode table entry and filesystem dependent inode table entry. It returns a pointer to the generic table entry. Namei() then calls another function, the routine falloc(), which sets up an entry in the file table to point to the inode in the generic table. The kernel then calls the ufalloc() routine, which sets up a file pointer in the process's uarea to point to the file table entry set up by falloc(). Finally the return value to open() is index into the file pointer array, known as the file descriptor. The function of namei() is a bit more complicated than just converting a filename to an inode number. This seems like a simple thing to say, but in practice, there is a lot more to it. Namei() converts the filenames to inodes (not to inode numbers). Obviously it must first get the inode number, but that is a relatively easy chore, since that is the contained within the directory entry of the file. In order to find out what inode table to read, namei() needs to know on which filesystem a file resides. Simply reading the inode from the directory entry is not enough. As we talked about before, two completely different files can have the same inode provided they are on different file systems. Therefore, even though namei() has the inode number, it still does not know which inode table to read. In order to find the filesystem, namei() needs to have a complete pathname to the file. A UNIX pathname consists of zero or more directories, separated with '/' terminated by the filename. The total path length cannot be more than 1024 characters. Assuming there is no directory name mentioned when the file is opened, (or only a relative path) namei has to back track a little to get back up to the top of the directory tree. If not already in memory, the inode corresponding to the first directory in the pathname is read into memory. The directory file is read into memory and the inode/filename pairs are searched for the next directory component. The next directory is read in and the process continues until the actual file is reached. We now have the inode of the file. With relative paths or no paths at all, we have to back track. That is, in order to find the root directory of the filesystem we are on, we have to find the parent directory of our file, then it's parent and so on until we reach the root. Looking at this, we see the pathname to inode conversion is time consuming. Each time a new directory is read, there must be a read of the hard disk. In order to speed up things, SCO UNIX caches the directories. The size of the cache is set by the s5cachent kernel tunable parameter and the entries defined in <sys/fs/s5inode.h>. Whenever the kernel searches for a component of the file name, it checks the correct hash queue. In ODT 3.0 the s5cachent structures can't hold more than 14 characters. Therefore, for the long file names possible with EAFS, the kernel must go directly to the disk. Cache hits and misses are recorded and can be retrieved with sar and can monitored. In a S51K (Traditional UNIX) filesystem, the superblock contains a list of both free blocks and free inodes. There is room for 50 blocks in the free block list and 100 inodes in the free inode list. The structure of the superblock is found in <sys/fs/s5filsys.h>. When creating a new file, the system examines the array of free inode numbers in the superblock and the next free inode number assigned. Since this list only has 100 entries, they will all eventually get used up. If total number of free inodes drops to zero, the list is filled in with another 100 from the disk. If there ever less than 100 free inodes, then the unused entries are set to 0. In S51K filesystems, the list of free data blocks, the freelist, is ordered randomly. As disk blocks are freed, they are just appended to end of freelist. During allocation of data blocks, no account is made for physical location of the data blocks. This means that there is no pattern to where the files reside on the disk, and can quickly lead to fragmentation. That is, data blocks from one file can be scattered all over the disk. In AFS and EAFS the freelist is held as a bitmap, where adjacent bits in the map correspond to logically contiguous blocks. Therefore the system can quickly search for sets of bits representing free blocks and then allocate files in contiguous blocks. Logically contiguous blocks (usually physically contiguous blocks) are known as a cluster. When the filesystem is first created, the bitmap is created by mkfs. There is 1 bit for every data block on the filesystem, so the bitmap is a linear array which says whether a particular block contains valid data or not. Note that this bitmap also occupies disk blocks itself. Actually there is more than one bitmap. There are several which are spaced at intervals of approximately 8192 blocks throughout the filesystem. Since a block contains 1024 bytes, it contains 8192 bits and can therefore map 8192 blocks. There is also an indirect freelist block, which holds a list of the disk block numbers which actually contain the bitmaps. When a file is created, the entire cluster is reserved for the file. Although this does tend to waste a little space, it reduces fragmentation and therefore increases speed. When kernel reads a block, it reads the whole cluster the file belongs to as well as the next. This is called read ahead. When a disk block is needed for a new file, the system searches the bitmap for the first free block. If we later need more data blocks for an existing file, the system begins it search starting from the block number that was last allocated for that file. This helps to ensure new blocks are close to existing ones. Note that when a cluster is allocated, not all of the disk blocks may be free (maybe it is already allocated to another file). The bitmapped freelist of the AFS and EAFS has some performance advantages. First, files are typically located in contiguous disk blocks. These can be allocated quickly from the free list. using i80386 bit manipulation instructions. This means that free areas of the disk can be found in just a few instruction cycles and therefore access speeds up. Figure 0-6 The AFS freelist In addition, the freelist is held in memory. The advantage is that this keeps the system from having to make an additional disk access every time the system wants to write new blocks to the hard disk. When kernel issues an I/O request to read from a single disk block, the AFS maps the request so that the entire cluster contain the disk block and following cluster are read from disk. At the beginning of each filesystem is filesystem specific structure called the superblock. You can find out about the structure of the superblock by looking in <sys/fs/*>. The Sys V superblock is located in 2nd half of first block of filesystems (bytes 512-1023). Since the structure is less than 512 bytes, it contains padding to fill out to 512 bytes. When a filesystem is first mounted, its superblock is read into memory so updates to the superblock don't have to constantly write to the disk. In order for the structures on the disk to remain compatible with the copies in memory, superblocks and inodes are updated by sync which is started at regular intervals by init. The frequency of the sync is defined by SLEEPTIME in /etc/default/boot, with a default of 60 seconds. There are several concepts new to Open Server. The first is intent logging. When this functionality is enabled, filesystem transactions are recorded in a log and then committed to disk. If the system goes down before the transaction is completed, the log is replayed to complete pending transactions. This scheme increases reliability and recover speed since the system need only read the log to be able to bring the system to the correct state. By using this scheme, the time spent checking the filesystem (and repairing it if necessary) can be reduced to just a few seconds, not the several minutes that was required previously, regardless of the filesystem size. There is, however, a small performance penalty since the system has to spend some time writing to the logs. As changes are being made to any of the control structures (inodes, superblock), the changes are written to a log. Once complete, the transactions is marked as complete. However, if the system should go down before the log is written, it is as if the transaction was never started. If the log is complete, but the transaction hasn't finished, the transaction can either be completed or ignored, depending what fsck considers possible. Obviously if the system goes down after the transaction is complete, then nothing needs to be done. The location of the log file is stored in the superblock. As a real file it does reside somewhere on the file system, however it is invisible to normal user-level utilities and only becomes visible when logging is disabled. Intent logging does bring up one misconception in that it does not increase the reliability of the system. Only changes to the control structures are logged. Data is not. The purpose here is to reduce the time it takes to make the system operational again should it go down. Another new the concept is checkpointing. When enabled the filesystem is marked as "clean" at regular intervals. That is, the pending writes are completed, inodes are updated and, if necessary, the in-core copy of the superblock is written to disk. At this point the filesystem is considered clean. Should the system go down improperly at this point, there is no need to clean the filesystem (using fsck) as it is already clean. However, the data is still cached in the buffer cache, so if it is needed again soon, it is available. If the system goes down, the contents of the buffer cache are lost, but since they were already written to disk, no data is actually lost. Obviously, anything not written between the last checkpoint and the time the system goes down is lost, but checkpointing does decrease the amount lost as well as speed up the recovery process when the system is rebooted. Again, there is no such thing as a free lunch and checkpointing does mean a small performance loss. Checkpointing is turned on by default on High Throughput Filesystem (HTFS) , EAFS, AFS, and S51K filesystems. For the best reliability and speed of recovery, it's a good idea to have both logging and checkpointing enabled. Although they both cause slight performance degradation, the benefits outweigh the performance hit. In most cases, the performance loss is not noticed, only the time required to bring the system back up is a lot quicker. The idea of sync-on-close for the Desktop Filesystem (DTFS) is another way of increasing reliability. Whenever a file is closed, it is immediately written to disk, rather than waiting for the system to write it as it normally would (potentially 30 seconds later). If the system should do down improperly, you have a better chance of not loosing data. Because you are not writing data to the hard disk in large chunks, sync-on-close also degrades performance. Because I regularly suffer from digitalus enormus (fat fingers), I am often typing in things that I later regret. On a few occasions, I have entered rm commands with wild cards (*, for example) only to find that I had a extra space before the asterisk. As a result, I end up with a nice clean directory. Since I am not that stupid, I built an alias so that every time I used rm it would prompt me to confirm the removal (rm -i). My brother, on the other hand, created an alias where rm copies the files into a TRASH directory, which he needs to clean out regularly. Both of these solutions can help you recover from accidentally erasing files. OpenServer has adding something, whereby you no longer have to create aliases or other things necessary to keep you from erasing things you shouldn't. This is the idea of file versioning. Not only does file versioning protect you from digitalus enormus, but will also make automatic copies of files for you. In order for versioning to be used, it must be first configured in the kernel. There are several kernel tunable parameters that are involved. So to change them you either run the program /etc/conf/cf.d/configure or click on the "Tune Parameters..." button in the Hardware/Kernel Manager. (The Hardware/Kernel Manager calls configure). Next select option 10 (Filesystem configuration). Here you will need to set the MAXVDEPTH parameter, which set the maximum number of versions maintained and the MINVTIME parameter which set the minimum time (in seconds) between changes before a file is versioned. Setting MAXVDEPTH to 0 disables versioning. If MINVTIME is set to 0, and MAXVDEPTH to a non-zero value, then versioning will happen no matter how short the time between versions. Versioning is only available for the DTFS and HTFS. You can also set versioning for a filesystem by using the maxvdepth and minvtime options when mounting. These can be included in /etc/default/filesys (which defines the default behavior when mounting filesystems), or you can specify them on the command line when mounting the filesystem by hand. In addition to that, versioning can be set on a per-directory basis. This is done by using the undelete command. For example, undelete -s /usr/jimmo/letters This command line turns on versioning for all the files in the directory /usr/jimmo/letters as well as any child directories. This includes existing files and directories and well as ones created later. Note that even though the filesystem was not mounted with either the minvtime or maxvdepth options, you can still turn on versioning for individual directories, as long as it is configured in the kernel. Also, using the -v option to undelete you can turn on versioning for single files. When enabled, versioning is performed without the interaction of the users. If you delete or overwrite a file, you usually don't see anything. You can make the existing versions visible to you by setting the SHOWVERSIONS environment variable to 1, and then exporting it. The means of storing versions is quite simple. The names are appended with a semi-colon followed by the version of the file as in: letter;12 This would be the 12th version of the file letter since versioning was enabled on the filesystem. Keep in mind that this does not mean that there are 12 versions. The number of available versions is defined by the MAXVDEPTH kernel parameter or mount option. If higher than 12, there just might be 12 versions. However, if set to a lower value you will see at most MAXVDEPTH versions. Also keep in mind that you are are not just mainting a list of changes, but rather complete copies of each file. For example, let's assume I mounted a filesystem with the option -o maxvdepth=10. The system will then save, at most, 10 versions. After I edit and save a file for a while, the version number might be up to 12. However, I will not be able to see or have access to versions lower than 3, since there are removed from the system. Different file versions can not only be accessed when making copies or changes to existing file, but also when you remove them. Assume you have the three latest versions of a letter (letter;10, letter;11 and letter;12) as well as the current version letter. If you remove letter, the three previous versions still exist. These can be seen by using the -l (list) option to undelete, either by specifying the file explicitly as in: undelete -l letter or if you leave off the file name, you will see all versions of all files. To undelete a versioned file or make the previous version the current one, simply leave off the options. If you repeated use undelete with just the file name, you can backup and make ever older versions the current one. Or, to make things easier, simply copy the older version to the current one, as in: cp letter\;8 letter This will make version 8 the current one. (NOTE: The \ is necessary to remove the special meaning of the semi-colon.) With the first shipping version of OpenServer, there are some "issues" with versioning in that it does not behave as expected. One of the first things I noticed was that changing the kernel parameters MAXVDEPTH and MINVTIME do not turn on versioning. Instead, they allow versioning to be turned on. Without them, you can't get versioning to work at all. When version is enabled, you still need to use undelete -s on the directory. There is more to it than that. However, I don't want to repeat too much information that's in the manuals. Therefore, take a look at the undelete(C) man-page. There are other changes that have been made to the system. There is the introduction of a couple new filesystem types as well as adding new features to the old filesystems. Table 0.4 contains an overview of some of the more significant aspects of the filesystems. Table 0.4 Filesystem Characteristics New to OpenServer is the introduction of a new filesystem device driver: ht. This new driver can handle filesystems with 16-bit inodes like S51K, AFS and EAFS, but also the new HTFS which can handle 32-bit inodes. Although (as of this writing) you cannot boot from an HTFS, it does provide some important performance and functionality gains. One area that was changed is the total amount of information that can be stored on a single HTFS as the total number of inodes that can be used. Table 0.4 contains a comparison of the various filesystem types and just how much data they can access. Another new feature of the ht driver is lazy block evaluation. Previously, when a process was started with the exec() system call, the system would build a full list of the blocks that made up that program. This delayed the actual start-up of the process, but save time as the program ran. Since a program spends most of it's time executing the same instructions, much of the program is not used. That is, many of the blocks end up never being referenced. What lazy block evaluation does is to build this list of blocks only as they are needed. This speeds up the start-up of the process and causes small delays when a previously unreferenced block is first access. Another gain is through "transaction based" processing of the filesystem. As activity occurs on the system, they are gathered together in what is called an intent log, which we talked about earlier. If the system stops improperly, the system can use the intent log to make a determination of how to proceed. Since you only need to check the log in order to clean the filesystem, it is quicker and also more reliable. Another mechanisms used to increase throughput is to disable checkpointing. This way, the filesystem will spent all of it's time processing requests rather than updating the filesystem structures. Although this increases throughput, you obviously have the disadvantage of potentially loosing data. When dealing with aspects of the system like the print spooler or the mail system when jobs are batched processed, at any given moment it is less likely that data is being processed. Therefore you do not need the extra overhead of checkpointing. This is done by treating the filesystem as "temporary". Such filesystems are mounted with the -o tmp option. Although checkpointing is new to OpenServer, you can configure both AFS and EAFS filesystems as temporary. Keep in mind that certain applications like vi' provide their own recovery mechanism by saving the data at regular intervals. If the files are written by vi, but not written to disk, a system crash could loose the last update. When I described the directory structure I mentioned that each inode was represented by two bytes. This allows only for 64K worth of inodes. Since the HTFS can access 227 inodes and the DTFS can access 231, there needs to be some other format used in the directories. With the two new filesystems, the key word is "extensible." This mean that the structure can be extended as the requirement changes. This allows much more efficient handling of long files names, as compared to the EAFS. In most cases, the filesystem driver is capable of making the translation for applications that don't understand the new concepts. However, if the applications reads or write the directory directly, you may need a newer version of the application. The two new filesystems, HTFS and DTFS, can save space by storing symbolic links in the inode. If the path of the symbolic link is 108 characters or less, the DTFS will store the path within the inode and not in a disk block on the disk. For the HTFS, this limit is 52 characters. First this saves space as not data blocks are needed, but it also saves times since once you read the inode from the inode table, you have the path and do not need to access the disk. There are two issue to keep in mind. If you use relative paths instead of absolute paths, then you may end up with a shorter path that fits into the inode. This saves time when accessing the link. On the other hand, think back to our discussion on symbolic links. The behavior of each shell when crossing the links is different. If you fail to take this into account, you may end up somewhere other than you expect. One of the problems that the advances that SCO OpenServer brought with it is the increased amount of hard disk space required to install it. On large servers with several gigabytes of space, this is less of an issue. However, on smaller desktop workstations this can become a significant problem. Operating systems have been dealing with this issue for years. MS-DOS provides a potential solution in the form of it's DoubleSpace disk compression program. Realizing the need for such space savings, SCO Open Server provides a solution in the form of the new DTFS. Among the issues that need to be addressed is not only the saving of space, but also the reliability of the data and avoiding any performance degradation that occurs when compressed files need to be uncompressed. On fast CPUs with fast hard disks, the preformance hit because of the compression is noticeable. The first issue (saving space) is addressed by the DTFS in a couple of ways. The first is that files are compressed before they are written to the hard disk. This can save anywhere from just a few percent in the case of binary programs to over 50% for text files. What you get will depend on the data you are storing. The second method space is saved is the way inodes are store on the disk. With "traditional" filesystems such as S51K or EAFS, inodes are pre-allocated. That is, when the filesystem is first created, a table for the inodes allocated at the beginning of the filesystem. This is a consistent size no matter how many or how few inodes are actually used. Inodes on a DTFS are allocated as needed. Therefore, there are only as many inodes as there are files. As a result you never have any empty slots in the inode table. (Actually there is no inode table in the form we discussed for other filesystems. We'll get to this in a moment.) In order to distinguish these inodes from others, inodes on the DTFS are referred to as dtnodes. Figure 0-7 The DTNODE map The DTFS has many of the same features as the EAFS filesystem, such as file length up to 255 characters and symbolic links. In addition, the DTFS also has multiple compression algorithms, greater reliability (through the integrated kernel update daemon, which attempts to keep the file system in a stable state), and dynamic block allocation algorithm that can automatically switch between best-fit and first fit. Best-fit is where the system looks for an appropriately size spot on the hard disk for the file and first-fit is where the system looks for the first one that is large enough (even if it is much larger than necessary). As one might expect, the disk layout is different from other filesystems. The first block (block 0) was historically the "boot block" and has been retained for compatibility purposes. The second block (block 1) is the super block and like other filesystems it contains global information about the filesystem. Following the superblock is the block bit-map. There is one block for each 512-byte data block in the filesystem, so the size of the bitmap will vary depending on the size of the filesystem. If the bit is on (1), the block is free, otherwise the block is allocated. The block bitmap is followed by the dtnode bitmap. It's size is the same as the block bitmap since there is also one bit for each block. The difference is that these bits determine if the corresponding block contains data or dtnodes. A 1 indicates the block contains dtnodes and a 0 indicates data. Following these two bitmaps are the actual data and dtnode blocks. Since the dtnodes are scattered throughout the filesystem, there is no inode table. Unlike the inodes of other filesystems, dtnodes are not pre-allocated when the filesystem is created. Instead, they are allocated at the same time as the corresponding file. This has the potential for saving a great deal of space since every dtnode points to data in contrast to other filesystems where inodes may go unused and therefore the space they occupy is wasted. The translation from dtnode number is straight forward. The dtnode number has the same number as the block number that it resides on. For example, if block 1256 was a dtnode, then that dtnode number would be 1256. This means that since not all blocks contain dtnodes, not all dtnode numbers are used. The one exception to this is that the dtnode number of the root of the filesystem is stored in the superblock. Each dtnode is accessed through the dtnode map. The contents of the superblock are found in the files location in <sys/fs/ >. If you take a quick look at it you see several important pieces of information. One of the most important ones is the size of the filesystem. Many of the other parameters included in this structure can be calculated from this value. These include the root dtnode number, start of the bitmaps, the start of the data blocks, as well as the number of free blocks. Although the values can be calculated, it saves time by also storing these values in the superblock. As I mentioned earlier, the block size of the DTFS varies in increments of 512 bytes between 512 and 4096. The reason for the range is that empirical studies have shown that filesystem throughput increases as the block size increases. However, in an effort to save space (a primary consideration in the DTFS), smaller block sizes were also allowed. Before being written to the disk, regular files are compressed using one of two algorithms (one being "no compression"). Because of this compression, it is no longer possible to directly calculate a physical block on the hard disk based on the offset in the file. For example, let's assume a file that begins at block 142 of the filesystem. On a non-compressed filesystem, we could easily find byte 712 since block 0 of the file contains bytes 0-511, and block 1 contains bytes 512-1023. Therefore, byte 712 is in block 101 of the filesystem. However, if we have a compressed filesystem, there is no immediate way of knowing if the compression is sufficient to place byte 712 into block 142, or it is still in block 143. We could start at the beginning of the file and calculate how much uncompressed data is in each block. Although this would eventually give us the correct block, the amount of time spent doing the calculations more than eliminates advantages gained by the compression. In order to solve this problem, the structure on the hard disk is maintained in a structure called a B-tree. Without turning this book into a discussion on programming techniques, it is sufficient to say that the basic principle of a B-tree forces it to be balanced, therefore the depth of one leaf node is at most one level away from the depth of any other leaf node. Conceptually the B-tree works like this: Let's assume a block ‘a', is the root node. The block offset of every data block that is on the left hand branch of a is smaller than the block offset in a. Also, the block offset of every data block that is on the right hand branch of ‘a' is larger than the block offset in ‘a'. This then applies to all subsequent blocks, where the left hand branch is smaller and the right hand branch is larger. In order to find a particular offset in the file you start at the top of the tree and work down. If the block offset is less than the root, you go down the left hand branch. Likewise, if the block offset is greater you go down the right hand branch. Although you still have to traverse the tree, the amount you have to search is far less than a pure linear search. Each node has a pointer to both the previous and the next nodes. This allows traversal of the tree in both directions. Regular files are the only ones that are compressed. Although supported, symbolic links and device nodes are left as they are, since you don't save any space. If a symbolic link is smaller than 192 bytes, the name is actually stored within the dtnode. The size of blocks containing directories is fixed at 512 since directories are typically small. Long names are allowed on the DTFS up to a maximum of 255 characters (plus the terminating NULL). One interesting aspect is the layout of the directory structure. This is substantially different than on the (E)AFS. Among other things there are entries for the size of the filename and size of the directory entry itself. The DTFS has several built in features that provide certain protections. The first is a technique called "shadow paging." When a data is about to be modified, extras blocks are allocated that "shadow" the blocks that are going to be changed. The changes are then made to this shadow. Once the change is complete, the changed blocks "replace" the previous blocks in the tree and the old blocks are then freed up. This is also how the dtnode blocks are modified except that the shadow is contained within the same physical block. If something should happen before the new, changed block replaces the old one, then it is as if the change was never started. This is because the file has no knowledge of anything ever happening to it. Unlike changes on an EAFS, AFS and other "traditional” UNIX filesystems, where changes are made to blocks that are already a part of the file. If the system should go down in the middle of writing, then the data is, at best inconsistent, or at worst, trashed. Obviously, in both cases, once the changes are complete and something happens, the file remains unaffected. Figure 0-8 Updating blocks on a DTFS Also unique to the DTFS is the way the dtnodes are updated. If you look at the structure and count up the number of bytes, you find that the amount of data that each block takes up is less than half the size of the block (512 bytes). The other half is used as the shadow for that dtnode. When it gets updated, the other half is written to first, only after the information is safely written does the new half become "active". Here again, if the system crashed before the transaction was complete, then it would appear as if nothing was ever started. By comparing the timestamp we can tell which half is active. Other than saving space, there is another logic to splitting the block in half. Remember that the dtnode points to the nodes that are both above it and below it in the tree. Assume we didn't shadow the dtnode. When one dtnode gets updated, it would get replaced by a new node. Now the nodes above it and below it need to be modified to point to this new node. In order to update them, we have to copy them to new blocks as well. Now, the nodes pointing to these blocks need to get updated. This "ripples" in both directions until the entire tree is update. Quite a waste of time. Another technique used to increase the reliability is the update daemon (htepi_daemon). Once per second the update daemon checks every writeable filesystem. If the update daemon writes out all the data to that filesystem before another process writes to that filesystem, the update daemon can write out the superblock as well and can then mark the filesystem as clean. If the system were to crash before another process made a write to that filesystem, then it would still be clean and therefore no fsck would be necessary. Built into the dtnode is also a pointer to the parent directory of that dtnode. This has a very significant advantage when the system crash and the directory entry for a particular file gets trashed. In traditional SCO filesystems, if this happened, there would be files without names and when fsck ran, they would be placed in lost+found. Now, since each file knows who its parent is, the directory structure can easily be rebuilt. That's why there is no more lost+found directory.: ls -l | more As I mentioned, there are actually data blocks taken up on the hard disk to store the data as the system is waiting for the receiving side to read it. For all intents and purposes this is a real file. It contains data (usually) and it has an inode. The only difference is that, unless it is a named pipe, it has no entry in any directory and therefore no file name. When then system goes down by accident and cannot close the pipes, fsck will report them as unreferenced files. This is very disconcerting to many users as they see a long list of unreferenced files when fsck runs after a crash. This represents only one of the problems existing with traditional pipes. The other is the fact that these pipes exist on the hard disk. When the first process writes to the disk, there is a disk access. When the second process reads the disk, there is a disk access. Since disk access a bottleneck on most systems, this can be a problem. (NOTE: This ignores the existence of the buffer cache. However, if sufficient time passes between the write and subsequent read, then the buffer cache will no longer contain the data and two disk accesses are necessary) SCO OpenServer has done something to correct that. This is the High Performance Pipe System (HPPS). The primary difference between the HPPS and conventional pipes is that the HPPS pipes no longer exist on the hard disk. Instead, they are maintain solely within the kernel as buffers. This corrects the two previously discussed disadvantages of conventional pipes. First, when the system goes down, the pipes simply disappear. Second, since there is no disk interaction, there is never any performance slow-down as a result. Like traditional pipes, when HPPS pipes are created an inode is created with it. This inode contains the necessary information to administer that pipe. One of the major additions to OpenServer is the idea of "virtual disks". These can come in many forms and sizes, each providing its own special benefits and advantages. To the running program (whether it is an application or system command), these disks appear like any other. As a user, the only difference you see is perhaps in the performance improvements that some of these virtual disks can yield. There are several different kinds of virtual disks which can be used depending on your needs. For example, you may be running a database that requires more contiguous space than you have on any one drive. Pieces of different drives can be configured to a single, larger drive. If you need a quicker way of recovering from a hard disk crash, you can mirror your disks, where one disk is an exact copy of the other. This also increases performance since you can read from either disk. Performance can also be increased by striping your disks. This is where portions of the logical disk are spread across multiple physical disks. Data can be written to and read to the disks in parallel, thereby increasing performance. Some of these can even be combined. Underlying many of the virtual disks type is the concept of RAID. RAID. In some cases, drives can be replaced even while the system is running. This is the concept of a hot spare. This is done from the Virtual Disk Manager. Some hardware vendors even provide the ability to physically remove the drive from the system without having to shut the system down. This is called a hot swap All the control for the hard disks is done by the hard disk controller and the operating system sees only a single hard disk. In either case, data is recreated on the spare as the system is running. Keep in mind that SCO does not directly support hot swapping. This must be supported by the hardware in order to ensure the integrity and safety of your data. SCO's implementation of RAID is purely software. Makes sense since SCO is a software company. Other companies provide hardware solutions. In many cases, hardware implementations of RAID present a single. logical drive to the operating system. In other words, the operating system is not even aware of the RAIDness of the drives it is running on. In Figure 0-9 we see how the different layers of a virtual drive are related. When an application (vi, a shell, cpio) accesses a file, it makes as system call. Depending on whether you are accessing a file through a raw device or the the filesystem code, the application uses the block or character code within the device driver. The device driver it accesses at this point is for the virtual disk. the virtual disk then access the device driver for the physical hard disk.. The simplest virtual disk is called (what else) a simple disk. With this, you can define all your non-root filesystem space as a single virtual disk. This can be done to existing filesystems and not only provides more efficient storage, but using virtual disks instead of conventional filesystems makes it easier to change to the more complex virtual disks. This is because you cannot add existing filesystem to virtual disks. They must be first converted to simple disks. A concatenated disk is created when two or more disk pieces are combined. In this way, you can create logical disks that are larger than any single disk. Disks that are concatenated together do not need to be the same size. The total available space is simply the sum of call concatenated disks. New peices cannot be added to concatenated disks once the filesystem is created. Remember that the filesystem sees this as a logical drive. Division and inode tables are based on the size of the drive when it is added to the system. Adding a new piece would require you to recreate the filesystem.. Figure 0-9 Virtual Disk Layers Figure 0-10 Striped Array With No Parity (RAID 0) and availability of the data (transaction speed and reliability) is more important than storage efficiency. Another consideration is the speed of the system. Since it takes longer than normal to write data, mirrored systems are bettered suited to database applications where queries are more common than updates. As of this writing, OpenServer does not provides for mirror of the /dev/stand filesystem. Therefore, you will need to copy this information somewhere else. One solution would be for you to create a copy of the /dev/stand filesystem on the mirror driver yourself. I have been told by people at SCO that an Extended Funtionality Supplement (EFS) is planned to allow you to mirror /dev/stand and boot from it, as well.. Figure 0-11 Striped Array with Undistributed Parity (RAID 4) drive go out, the missing data can be recreated. Here again, you can recreated the data while the system is running, if a hot spare is used. Figure 0-12 Striped Array With Distributed Parity (RAID 5) As I mentioned before, some of the characteristics can be combined. For example, it is not uncommon to have to have stripped arrays mirrored as well. This provides the speed of a striped array with redundancy of a mirrored array, without the expense necessary to implement RAID 5. Such a system would probably be referred to as RAID 10 (RAID 1 plus RAID 0). All of these are configured and administered using the Virtual Disk Manager, which then calls the dkconfig utility. It is advised that, at first, you use the Virtual Disk Manager since it is easier to use. However, once you get the hang of things, there is nothing wrong with using dkconfig directly. The information for each virtual disk is kept in the /etc/dktab file and is used by dkconfig to administer virtual disks. Each entry is made up of two lines. The first is the virtual disk declaration line. This is followed by one or more virtual piece definition lines. Here we have an example of an entry in a dktab file that would be used to create a 1 GB array. (This is RAID 5) /dev/dsk/vdisk1 array 5 16 /dev/dsk/1s1 100 492000 /dev/dsk/2s1 100 492000 /dev/dsk/3s1 100 492000 /dev/dsk/4s1 100 492000 /dev/dsk/5s1 100 492000 The first line is virtual disk declaration line and varies in the number of fields depending on what type it is. In each case, the first entry is the device name for the virtual device followed by what type it is. For example, if you have a simple virtual disk, there is only the device name followed by the type (simple). Here, we are creating a disk array, so we have array in the type field. A simple disk consists of just a single piece. The other types, such as mirror, concatenated, etc, require a third field to indicate how many pieces (simple disks) go into making up the virtual disk. Since we are creating a disk our of five pieces, this value is 5. If you use striped disks or disk arrays, then the fourth field defines the size of the cluster in 512-byte blocks. We are using a value of 16, therefore we have an 8K cluster size. If you have mirrored disks, then the fourth field is the "catch up" block size and is used when the system is being restored. The virtual piece definition line describes a piece of the virtual disk. (In this case we have five pieces) It consists of three fields. The first is the device node of the physical device. Note that in our case, each of the physical drives is a separate physical drive. (We know this because of the device names 1s1-5s1). The second field is the offset from the beginning of the physical device of where to start the disk piece. Be sure you leave enough room so you start beyond the division and bad track tables. Here we are using a value of 100 and since the units are disks blocks (512 bytes), we are starting 50K from the beginning of the partitions, which is plenty of room. The third field is the length of the disk piece, Here you need to be sure that you do not go beyond the end of the disk piece. In our case we are specifying 492000. This is also in disk blocks. Therefore, each of the physical pieces is just under 250Mb. Since the actual amount of storage we get is the sum of all the pieces, we have just under 1000Mb or 1Gb. To change this array to RAID 4, where there is a single drive that is used solely for parity, we could add a fourth field to one of the virtual piece description lines. For example, If we wanted to turn drive three into the parity drive, we would change it to look like this: /dev/dsk/3s1 100 492000 parity Okay, so you've decided that you need to increase performance or reliability (or both) and have decided to implement a virtual disk scheme. Well, which one? Before you decide, there are several things you need to consider. The System Administrators Guide contains a checklist of things to consider when deciding which is best for you. If you create an emergency boot/root floppy on a system with virtual disks, there are a couple of things to remember. First, once you create a virtual disk, you should create a new boot/root floppy set. This is especially important if the virtual disk you are adding is a mirror of the root disk. If you do not and later need to boot from the floppy, then any changes made to the root filesystem will not be made to the mirror. The drives will then be inconsistant. In order to boot correctly, you need to change the default boot string. Normally, the default boot string points to hd(40) for the root filesystem. Instead, you need to change it to reflect the fact that the root filesystem is mirror. For example, you could use the string: fd(60)unix.z root=vdisk(1) swap=none dump=none This tells the system to use virtual disk 1 as the root filesystem. Note also that the device names are probably different from one machine to another. Therefore, it may not be possible to use the boot/root floppy set from one machine on another. Its also possible to "nest" virtual drives. For example, you could have several drives that you make into to a striped array. This striped array is seen as a single drive, which you can then include in another virtual disks. For example, you could mirror that striped array. Be careful with this, however. It is not recommend that you nest virtual drivers with redundant (mirrored, RAID 5) inside of other virtual disks. This can cause the virtual disk driver to hang, preventing access to all virtual drives. Even on a standard SCO UNIX system, without all the bells and whistles of TCP/IP, X-Windows, and SCO Merge, there are several tools that you can use to access DOS filesystems. These can be found on the doscmd (C) man-page. Although these tools have some obvious limitations due to the differences in the two operating systems, they provide the mechanism to exchange data between the two systems. Copying files between DOS and UNIX systems presents a unique set of problems. One of the most commonly misunderstood aspects of this is using wildcards to copy files from DOS to UNIX. This we can do using the doscp command,.for example: doscp a:* . One might think that this command copies all the files from the a: drive (which is assumed to be DOS formatted) into the current directory. The first problem is the way that DOS interprets wildcards. Using a single asterisk would only match files without an extension. For example, it would match LETTER, but not LETTER.TXT. So, if we exand the wildcard to include the possibility of the extensions, we get: doscp a:*.* . Which should copy everything from the floppy into the current directory. Unfortunately, that's not the way it works either. Instead of the message: doscp: /dev/install:* not found You get the slight variation: doscp: /dev/install:*.* not found Remember from our discussion of shell basics. It is the shell that is doing the expansion. Since nothing matches, we get this error. The solution to the problem was a little shell script that does a listing of the DOS device. Before we go on, we need to side-step a little. There are two ways to get a directory listing off a DOS disk. The first is with the dosdir command. This gives you output that appears just like you if you had run the dir command under native DOS. In order to use this output, we would have to parse each line to get the file name. Not an easy thing. The other is dosls, which gives a listing that looks like the UNIX ls command. Here you have a single column of files names with nothing else. Much easier to parse. The problem is that the file names come off in capital letters. Although this is not a major problem, I like to keep my file names as consistant as possible. Therefore, I want to convert them to lower case. Skipping the normal things I put into scripts like usage messages and argument checking, the script could look like this: DIR=$1 dosls $DIR | while read file do echo "$file" doscp "$dosdir/$file" `echo $file | tr "[A-Z]" "[a-z]"` Ü Note the back-ticks done The script takes a single argument which is assigned to the DIR variable. We then do a dosls of that directory which is piped to the read. If we think back to the section on shell programming, we know that this construct reads input from the previous command (in this case dosls) until the output ends. Next, we have a do-done loop that is done once for each line. In the loop, we echo the name of the file (I like to seeing what's going on) and then make the doscp. The doscp line is a little complex. The first part ($dosdir/$file) is the source file. The second part, as you would guess, is the destination file. However, the syntax here gets a little bit. Remember that the back-ticks mean "the output of the command". Here, that command is echo | tr. Note that we are echoing the file name through tr and not the contents. It is then translated in such a way that all capital letters are converted to lower case. See the tr(C) man-page for more details. To go the other way (UNIX to DOS), we don't have that problem. Wild cards are expanded correctly, so we end up with the right files. In addition, we don't need to worry about the names, since they are converted for us. The problem lies in names that do not fit into the DOS 8.3 standard. If a name is longer that eight characters or the extension is longer than three characters it is simply truncated. For example, the name letter_to_jim.txt ends up as letter_t.txt, or letter.to.jim becomes letter.to. One thing to keep in mind here is that copying files like this is only really useful for text files and data files. You could use it to copy executables to your SCO system if you were running SCO Merge, for example. However, this process does not convert a DOS executable into a form that native SCO can understand, nor vis-versa. Be careful when copying files because of conversions that are made. With UNIX text files, each line is ended with a carriage return (CR) character. The system converts this to a carriage return-new line (NL) pair when outputting the line. You can ensure that when copying files from DOS to UNIX that the CR-NL is converted to simply a CR by using the -m option to doscp. This also ensures that the CR is converted to a CD-NL when copying the other way. If you want to ensure that no conversion is made, use the -r option. You can also make the conversion using either the xtod or dtox commands. The xtod command converts UNIX files to DOS format and the dtox converts DOS format files to UNIX. In both cases, the command takes a single argument and outputs to stdout. Therefore, to actually "copy" to a file you need to re-direct stdout. An alternative to doscp is to mount the DOS disk. Afterwards you can use standard UNIX commands like cp to copy files. Although this isn't the best idea for floppies, it is wonderful for DOS hard disks. In fact, I have it configured so that all of my DOS file systems are mounted automatically via /etc/default/filesys. To be able to do this, you have to add the support for it in the kernel. Fortunately, it is simply a switch that is turned on or off via the mkdev dos script. Since it makes changes to the kernel, you need to relink and reboot. Once you have run mkdev dos, you can mount DOS filesystem by hand or, as I said, through /etc/default/filesys. For example, if we wanted to mount the first DOS partition on the first drive, you have two choices of devices: /dev/hd0d or /dev/dsk/0sC. I prefer the latter, since I have several DOS partition, some do not have an equivalent for the first form. Therefore, by using /dev/dsk/0sC, I am consistant in the names I use. If we wanted to mount it onto /usr/dos/c_drive, the command would be: mount -f DOS /dev/dsk/0sC /usr/dos/c_drive The only issue with this is that in ODT, the file name were all capitalized. In OpenServer, there is the lower option, which is used to show all the file names in lower case. Therefore, the command would look like this: mount -f DOS -o lower /dev/dsk/0sC /usr/dos/c_drive Although you can use the mkdev fs script to add a DOS filesystem, it displays a couple of annoying messages. Since I think it is just as easy to eadit /etc/default/filesys, I do so. There is also the issue that certain options are not possible through the mkdev fs script or the Filesystem manager. Therefore, I simply copy an existing entry and end up with something like this: bdev=/dev/dsk/0sC cdev=/dev/rdsk/0sC \ mountdir=/usr/dos/c_drive mount=yes fstyp=DOS,lower \ fsck=no fsckflags= rcmount=yes \ rcfsck=no mountflags= The key point is the fstyp entry. Since we can specify mount options here, I specified the lower option so that all filename's would come out in lower case. Each time I go into multi-user mode, this filesystem is mounted for me. For more details on the options here, check out the mount(ADM) man-page or the section on filesystems. (Note: The lower option is only available in OpenServer.) Keep in mind that if the DOS filesystem that you are mounting contains a compressed volume, you will not see the files with the compressed volume. This applies to both ODT and OpenServer. Another of the DOS commands that I use often is dosformat. Although there are a few options (-v to promopt for volume name, -q for quiet mode, -f to run in non-interactive mode), I never have used them. The one thing I need to point out is that you format a UNIX floppy with the raw device (e.g. /dev/rfd0), but with dosformat, you format the block device (e.g. /dev/fd0). The remaining files, which I use only on occassion are: dosrm- Removes files from a DOS filesystem dosmkdir - make a directory on a DOS filesystem dosrmdir - move directories from a DOS filesystem As with the kernel components, I suggest you go poke around the system a little. Take a look at the files on your system that we talked about to see what filesystems you have, where they are amount and anything else you can find out about your system. Look for different kinds of files. If they are hard links, try to find out what other files are linked to it. If you find a symbolic link, take a look at the file pointed to by that the symbolic link. In every case, look at the file permissions. Think about why are they set that way and what influence this has on their behavior. Also think about the kind of file it is and who can access it. If you aren't sure of what kind of file it is, you can use the file command that can find out for you. Next: Starting and Stopping the System Index Copyright 1996-1998 by James Mohr. All rights reserved. Used by permission of the author. Be sure to visit Jim's great Linux Tutorial web site at
http://aplawrence.com/Companion/Chapter06.html
crawl-002
refinedweb
18,208
71.75
SMBIOS Demystified Contents Introduction SMBIOS stands for System Management BIOS. It is a way for system vendors to present data about their system without having to resort to querying hardware and so forth. To make the experience of getting this information easy for users, there is a commonly agreed-upon specification. This SMBIOS specification can be found here. SMBIOS Data Format The SMBIOS data format is straightforward. However, it can be slightly tricky to understand it and, unfortunately, I could find no info on the Internet, except for the specification, on how to interpret it. This article is intended to demystify it. - SMBIOS data is a simple table of entries. Each entry is called a structure. - There is no fixed number of structures. In other words, the number of structures in the table can vary. - All structures are placed one after another and are packed closely; there is no padding data between two consecutive structures. - Each structure size is a multiple of byte length. The SMBIOS table is not bit packed; this makes it simple to navigate. - Each structure has a mandatory part called a structure header that has a fixed length. - Each structure is identified by a type. - Some structures are mandatory. - Some structure types will and should occur only once. - Some structure types can occur more than once. - Each structure has a formatted section containing, at a minimum, the header. - A structure could have an unformatted section. The unformatted section could contain proprietary information, OEM specific data, or it could contain string data. The following figure shows a graphic representation of the SMBIOS table. More about the structure The structure, as you can see, has a mandatory header occupying the following four bytes. Type: The first byte identifies the type of the stucture. For example, type 0 indicates a BIOS information structure; type 1 indicates a System Information structure, and so on. These details can be obtained from the specification (see the References section). Length of formatted section: The second bytes contain the length of a section of data called the formatted section. The formatted section contains any data that is fixed length for the type of structure. For predefined types, the details on the formatted section can be found in the specifications. Handle: A 2-byte–length field. Unformatted section: An unformatted section can follow the formatted section. This section can contain variable length data like strings or OEM-specific data. The interesting part here is the string data. The strings are ANSI strings and they are arranged as a table of NULL-terminated strings. Any fields in the formatted section that refer to strings shall indicate so by specifying the index of the string in this table. For example, if the structure were so defined: DDh ; example fictitous type 05h ; length of formatted section 12h ; 34h ; 2 bytes of handle 01h ; index of fictitous string data in string table 41h ; 'A' 42h ; 'B' 43h ; 'C' 44h ; 'D' 00h ; '\0' 00h ; END OF STRUCTURE For this structure, if one were to try to get the string corresponding to the fictitous string data, one would navigate to the byte at a distance of 05h (length of the formatted section) from the start of the structure, and then look for 01th (01 being the index for the fictitous string data field) string until one hits the end of the structure. The following picture explains it better. SMBIOS Data Retrieval Using WMI SMBIOS data can be retrieved for the system in two ways: - Using WMI. This is the procedure used in the attached example. For more information on using WMI, please refer to this link. The key here is to know the class to use and the property to query for. The SMBIOS document says this, WMI also supports reading the entire contents of SMBIOS data in a single buffer by using the MSSMBios_RawSMBiosTables class inside the root\wmi namespace. The SMBiosData property returns a buffer that contains the entire SMBIOS data table. - Using the EnumSystemFirmwareTables and GetSystemFirmwareTable APIs. SMBIOS Parser Sample The attached sample is a simple SMBIOS parser. When executed, the parser simply queries for SMBIOS data using WMI, parses it, and then fills a combo box with a list of structures encountered while parsing. When one selects a structure from the combo box, the corresponding location of the structure is highlighted on the right hand side and for a few types. The individual structure's parsed data is shown in the window below. The parser provides a few methods to parse info for selected few types, such as SMBIOS table types 0,1,2,3,4,11 A snapshot of the parser is shown below: For ease, the whole parsing has been wrapped under a class called SMBiosData whose public interface is below: class SMBiosData { public: //used to query the system for BIOS data. This is usually the //first method used. BOOL FetchSMBiosData(); //used to enumerate the fetched data to get the number of structures void EnumTables(DWORD dwParam, ENUMPROC pfnEnumProc); //used to query for specific structures BOOL GetData(SMBios_TYPE0& stSMBiosType0); BOOL GetData(SMBios_TYPE1& stSMBiosType1); BOOL GetData(SMBios_TYPE2& stSMBiosType2); BOOL GetData(SMBios_TYPE3& stSMBiosType3); BOOL GetData(SMBios_TYPE4& stSMBiosType4); BOOL GetData(SMBios_TYPE11& stSMBiosType11); //in case of some structures, it is easier to query by index, //because there could be multiple structures with the same type. //The method below can be used in such cases BYTE* GetTableByIndex(BYTE byIndex,DWORD& dwTotalTableSize); }; The sample code in the parser could serve as a good starting point to extend it to parse any other table types. I leave it as an exercise for interested readers. Resguardar Desarrollo EspecialPosted by Oscar on 12/27/2012 07:14am Soy analista y programador desde hace mucho tiempo. Aún no existÃa la carrera en el paÃs (Año 1971). Tengo varios desarrollos realizados que los he ido migrando entre distintos idiomas, GwBasic, Qbasic, VB5, VB6 y ahora estoy llevándolos a VB10. Anteriormente tenÃa control sobre la PC en que se instalaban tomando el Volumen del disco en el que se instalaban pero me gustarÃa poder controlar La BIOS donde se instala. Voy a probar estas indicaciones y en caso que lo logre me pondré en contacto nuevamente. Desde ya ¡MUCHAS GRACIAS!Reply
http://www.codeguru.com/cpp/misc/misc/system/article.php/c12347/SMBIOS-Demystified.htm
CC-MAIN-2015-48
refinedweb
1,037
54.42
Working with Configuration Files and Visual Basic Introduction .Net developers are quite spoilt for choice when it comes to storing little pieces of information. Common places in which developers can store data are the following: - Configuration files - The Registry - Flat files - INI files - Databases It all depends on the need of the user, and obviously the amount of data that needs storing. It is senseless saving a couple of strings into a database; it is also senseless storing huge amounts of data into anything other than a database. What are Configuration Files? As the name implies, a Configuration file allows you to store configuration settings. These configuration settings could be anything such as a database connection, common strings, or objects that will be used throughout your entire application. The benefit of using a Config file is that it is automatically part of your application. This eliminates the need to create separate files in order to store your settings. Configuration files are in XML format. This means that every setting stored inside a config file can easily be read if you understand the very basics of XML. Every Windows Forms application includes a file called app.config, which I will talk about now. App.Config As said, any Windows Forms application includes this file as part of the solution - so create a VB.NET Windows Forms application quickly. You can store all your Database connection strings, Resource locations (et al.) inside it. If you were to open the App.Config file inside Visual Studio it will look like the following: <?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> </configuration> Doesn't look like much. This simply tells the application that it expects .NET Framework 4.5 in order to run. Now where do the Settings I mentioned come in? You have to edit the App.Config file to include your desired settings. Edit your App.Config to look like the next code listing: <?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <appSettings> <add key="TestKey" value="whatever"/> </appSettings> </configuration> All I included here was the appSettings section. Here I created a sub key named TestKey and supplied a senseless value (as this is just an example). Now, you have added a section to your Config file, and you can manipulate it through VB.NET Code. Design your form to resemble Figure 1 below. Figure 1 - Our Design Coding Before you can jump in and code, you first need to set a project reference to System.Configuration by following these steps: - Click Project - Click Add Reference - Click Assemblies - Click Framework (if necessary) - Scroll to System.Configuration and check the box next to it, as shown in Figure 2. Figure 2 - Added Project Reference Now that all the semantics are out of the way, you can start coding. As usual (I am a creature of habit) add the Imports statements first: Imports System.Configuration 'Need to add project reference as well The reference and the namespace allows us to be able to read any configuration file as well as to supply you with the necessary tools to do it. Create the following modular objects: Dim cAppConfig As Configuration = ConfigurationManager.OpenExeConfiguration(Application.StartupPath & "\Config_File_Ex.exe") Dim asSettings As AppSettingsSection = cAppConfig.AppSettings The first object you created (cAppConfig) is a Configuration object. You use this to open the application's config file via the use of the ConfigurationManager class' OpenExeConfiguration method. The next object is an AppSettingsSection object, which reads the appSettings key within the specified Configuration file object. Storing a Value Inside a Configuration File Now that everything is set up, you can finally store a value inside the appSettings key you created earlier. Add the following code behind the button labelled 'Store': Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click asSettings.Settings.Item("TestKey").Value = 5 'Save Original Value cAppConfig.Save(ConfigurationSaveMode.Modified) End Sub Here you opened the TestKey inside appSettings and give it a value. The next line simply saves the Configuration into the Config file. Reading from a Configuration File Add the next code behind the button labelled 'Show': Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click Try Dim appSettings = ConfigurationManager.AppSettings 'Read Stored Value Dim result As String = appSettings("TestKey") If IsNothing(result) Then result = "Not found" End If MessageBox.Show(result) Catch ec As ConfigurationErrorsException MessageBox.Show("Error reading app settings") End Try End Sub You created an AppSettings object to read through the Config file's AppSettings section. Then, you read from the specified key - in this case it is TestKey. If there is data present it will show the data inside a MessageBox, else, it will inform you that nothing has been stored. Editing Config File Values Add the next code behind the button labeled 'Edit': Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 'Re-Open file and Store a new value cAppConfig = ConfigurationManager.OpenExeConfiguration(Application.StartupPath & "\Config_File_Ex.exe") asSettings = cAppConfig.AppSettings asSettings.Settings.Item("TestKey").Value = 15 'Save Modified Value cAppConfig.Save(ConfigurationSaveMode.Modified) End Sub Inside the Edit button you simply open the Configuration file and the desired key, then you store a new value and save the file again. Conclusion In this article you have learned how to manipulate data in Configuration Files. I hope you have enjoyed it as much as I did. Until next time, cheers! System.UnauthorizedAccessExceptionPosted by Sam on 01/12/2017 09:44am Hello, I get a System.UnauthorizedAccessException error when trying to save the "TestKey" Value to the Config File. Any Ideas?? CheersReply Mr ?Posted by norab7 on 12/19/2015 08:01am FIXED "Config_File_Ex.exe" ERROR When he says "Config_File_Ex.exe" this is supposed to be YOUR PROJECT NAME. Since my project is under a alias for the time being, it's named PixieVB3 so instead of my line being "Config_File_Ex.exe" it is instead "PixieVB3.exe". Just make sure to change your "Config_File_Ex.exe" text into your project name.Reply Getting an error with Config_File_Ex.exePosted by John on 11/05/2015 10:38am When I try to store a value I get an error "parameter 'exePath' is invalid". I tried to set some references on "Copy local", I search for "Config_File_Ex.exe" but cannot find it. In other words I'm not able to store my values. What to do?Reply
http://www.codeguru.com/columns/vb/working-with-configuration-files-and-visual-basic.htm
CC-MAIN-2017-13
refinedweb
1,081
50.33
mount(2) mount(2) mount - mount a file system #include <sys/types.h> #include <sys/mount.h> int mount (const char *spec, const char *dir, int mflag, .../* char *fstyp, const char *dataptr, int datalen*/); mount requests that a removable file system contained on the block special file identified by spec be mounted on the directory identified by dir. spec and dir are pointers to path names. fstyp is the file system type number. The sysfs(2) system call can be used to determine the file system type number. If both the MS_DATA and MS_FSS flag bits of mflag are off, the file system type defaults to the root file system type. Only if either flag is on is fstyp used to indicate the file system type. If the MS_DATA flag is set in mflag the system expects the dataptr and datalen arguments to be present. Together they describe a block of file-system specific zero. Note that MS_FSS is obsolete and is ignored if MS_DATA is also set, but if MS_FSS is set and MS_DATA is not, dataptr and datalen are both assumed to be zero. After a successful call to mount, all references to the file dir refer to the root directory on the mounted file system. The low-order bit of mflag is used to control write permission on the mounted file system: if 1, writing is forbidden; otherwise writing is permitted according to individual file accessibility. mount may be invoked only by a process with the super-user privilege. It is intended for use only by the mount utility. mount fails if one or more of the following are true: EACCES Search permission is denied on a component of dir or spec. EPERM The calling process does not have the super-user privilege. EBUSY dir is currently mounted on, is someone's current working directory, or is otherwise busy. Page 1 mount(2) mount(2) EBUSY The device associated with spec is currently mounted. EBUSY There are no more mount table entries. EFAULT spec, dir, or datalen points outside the allocated address space of the process. EINVAL The super block has an invalid magic number or the fstyp is invalid. ELOOP Too many symbolic links were encountered in translating spec or dir. ENAMETOOLONG The length of the path argument exceeds {PATH_MAX}, or the length of a path component exceeds {NAME_MAX} while _POSIX_NO_TRUNC is in effect. ENOENT None of the named files exists or is a null pathname. ENOTDIR A component of a path prefix is not a directory. EREMOTE spec is remote and cannot be mounted. ENOLINK path points to a remote machine and the link to that machine is no longer active. EMULTIHOP Components of path require hopping to multiple remote machines and the file system type does not allow it. ETIMEDOUT A component of path is located on a remote file system which is not available [see intro(2)]. ENOTBLK spec is not a block special device. ENXIO The device associated with spec does not exist. ENOTDIR dir is not a directory. EROFS spec is write protected and mflag requests write permission. ENOSPC The file system state in the super-block is not FsOKAY and mflag requests write permission. E2BIG The file system's size parameters are larger than the size of special device spec. Either mkfs(1M) was run on a different overlapping device or the device has been changed with fx(1M) since mkfs was run. EFSCORRUPTED The filesystem has a corruption forcing failure of the mount. Page 2 mount(2) mount(2) EWRONGFS The wrong filesystem type was supplied in fstyp, or there is no filesystem on spec. It is the responsibility of the caller to assure that the block size of the device corresponds to the blocksize of the filesystem being mounted. This is particularly important with CDROM devices, as the default block size of the device can vary between 512 bytes and 2048 bytes. The mount(1M) command manages this for filesystems via dks(7M) DIOCSELFLAGS and DIOCSELECT ioctls. fx(1M), mkfs(1M), mount(1M), sysfs(2), umount(2), dks(7M),fs(4), xfs(4) Upon successful completion a value of 0 is returned. Otherwise, a value of -1 is returned and errno is set to indicate the error. PPPPaaaaggggeeee 3333
http://nixdoc.net/man-pages/IRIX/man2/mount.2.html
CC-MAIN-2020-05
refinedweb
711
64.61
After a few years in use. We have seen Cisco 871 and 851 routers that would hang if you had a single download that was more than 100M large. It is intermittent. Sometimes the problem goes away, sometimes it happens on very small downloads (just a 10KB web page). It seems that the just about all the downloads eventually finish, but the bigger the download the longer the hang. Is there a way to resolve this? (short of router replacement which is what we have been doing) We are revisiting this on a Cisco 851 that is one year and two months old. At this point, similar hangs seem to be occurring, at a much less important scale. In this case, the customer has purchased a 30Mbps up/down internet connection, and they are only able to get 5Mbps/20Mbps up/down. At times, download speed is reduced to 5Mbps. I will attempt what has already been suggested below next time I am out there (hopefully next week) and edit in my findings. I an ACL on Vlan1 and on the Fa4. I also have a few ACLs that were replaced and are not used. The ACLs are about 45 lines and about half the lines are remarks. I have posted the config below. Personal information is masked with words such as WAN IP or hostname HIDDEN WAN IP hostname HIDDEN If you have suggestions such as performance improvements for the configuration code, or information such as whether I can expect 30Mbps on an 851, that would be appreciated. Current configuration : 18157 bytes ! HIDDEN ! boot-start-marker boot-end-marker ! logging buffered 51200 logging console critical enable secret 5 --GIBBERISH--- ! aaa new-model ! ! aaa authentication login local_authen local aaa authorization exec local_author local ! ! aaa session-id common clock timezone EST -5 ! crypto pki trustpoint TP-self-signed-4140887523 enrollment selfsigned subject-name cn=IOS-Self-Signed-Certificate-4140887523 revocation-check none rsakeypair TP-self-signed-4140887523 ! ! dot11 syslog no ip source-route no ip dhcp use vrf connected ip dhcp binding cleanup interval 60 ip dhcp excluded-address 10.10.10.1 ip dhcp excluded-address 192.168.1.1 ! ip dhcp pool ccp-pool import all network 10.10.10.0 255.255.255.248 default-router 10.10.10.1 lease 0 2 ! ip dhcp pool sdm-pool1 import all network 192.168.1.0 255.255.255.0 dns-server --DNS Server 1-- --DNS Server 2-- default-router 192.168.1.1 ! ! ip cef ip inspect name DEFAULT100 appfw DEFAULT100 ip inspect name DEFAULT100 cuseeme ip inspect name DEFAULT100 ftp ip inspect name DEFAULT100 h323 ip inspect name DEFAULT100 icmp inspect name DEFAULT100 https ip inspect name DEFAULT100 dns no ip bootp server no ip domain lookup ip domain name noexist.example.com ip name-server --DNS Server 2-- ip name-server --DNS Server 1-- ! appfw policy-name DEFAULT100 application im aol service default action reset service text-chat action reset server deny name login.oscar.aol.com server deny name toc.oscar.aol.com server deny name oam-d09a.blue.aol.com application im msn service default action reset service text-chat action reset server deny name messenger.hotmail.com server deny name gateway.messenger.hotmail.com server deny name webmessenger.msn.com application http port-misuse im action reset alarm application im yahoo service default action reset service text-chat action reset server deny name scs.msg.yahoo.com server deny name scsa.msg.yahoo.com server deny name scsb.msg.yahoo.com server deny name scsc.msg.yahoo.com server deny name scsd.msg.yahoo.com server deny name messenger.yahoo.com server deny name cs16.msg.dcn.yahoo.com server deny name cs19.msg.dcn.yahoo.com server deny name cs42.msg.dcn.yahoo.com server deny name cs53.msg.dcn.yahoo.com server deny name cs54.msg.dcn.yahoo.com server deny name ads1.vip.scd.yahoo.com server deny name radio1.launch.vip.dal.yahoo.com server deny name in1.msg.vip.re2.yahoo.com server deny name data1.my.vip.sc5.yahoo.com server deny name address1.pim.vip.mud.yahoo.com server deny name edit.messenger.yahoo.com server deny name http.pager.yahoo.com server deny name privacy.yahoo.com server deny name csa.yahoo.com server deny name csb.yahoo.com server deny name csc.yahoo.com ! ! ! username surfn privilege 15 secret 5 $1$1hrm$0yfIN0jK56rOm9cXfm2a21 ! ! archive log config hidekeys ! ! ip tcp synwait-time 10 ip ssh time-out 60 ip ssh authentication-retries 2 ! ! ! interface Null0 no ip unreachables ! interface FastEthernet0 ! interface FastEthernet1 ! interface FastEthernet2 ! interface FastEthernet3 ! interface FastEthernet4 description $ES_WAN$$FW_OUTSIDE$ ip address --WAN IP-- 255.255.255.0 ip access-group 123 in ip verify unicast reverse-path no ip redirects no ip unreachables no ip proxy-arp ip inspect DEFAULT100 out ip nat outside ip virtual-reassembly ip route-cache flow duplex auto speed auto ! interface Vlan1 description $ETH-SW-LAUNCH$$INTF-INFO-HWIC 4ESW$$ES_LAN$$FW_INSIDE$ ip address 192.168.1.1 255.255.255.0 ip access-group 102 in no ip redirects no ip unreachables no ip proxy-arp ip nat inside ip virtual-reassembly ip route-cache flow ip tcp adjust-mss 1452 ! ip forward-protocol nd ip route 0.0.0.0 0.0.0.0 --ISP Gateway-- ! ip http server ip http access-class 2 ip http authentication local ip http secure-server ip http timeout-policy idle 60 life 86400 requests 10000 ip nat inside source list 1 interface FastEthernet4 overload ! logging trap debugging access-list 1 remark Telnet, SSH access access-list 1 permit 192.168.1.0 0.0.0.255 access-list 1 deny any access-list 2 remark HTTP, HTTPS access access-list 2 permit 192.168.1.0 0.0.0.255 access-list 2 deny any access-list 101 HIDDEN access-list 102 HIDDEN access-list 121 HIDDEN access-list 122 HIDDEN access-list 123 HIDDEN no cdp run ! control-plane ! banner exec ^C % Password expiration warning. -----------------------------------------------------------------------. You will not be able to login to the router with this username after you exit this session. It is strongly suggested that you create a new username with a privilege level of 15 using the following command. username <myuser> privilege 15 secret 0 <mypassword> Replace <myuser> and <mypassword> with the username and password you want to use. ----------------------------------------------------------------------- ^C banner login ^CCAuthorized access only! Disconnect IMMEDIATELY if you are not an authorized user!^C ! line con 0 login authentication local_authen no modem enable transport output telnet line aux 0 login authentication local_authen transport output telnet line vty 0 4 access-class 100 in privilege level 15 authorization exec local_author login authentication local_authen transport input telnet ssh ! scheduler max-task-time 5000 scheduler allocate 4000 1000 scheduler interval 500 end George, I'm seeing the following message: %FW-4-TCP_OoO_SEG: Dropping TCP Segment: seq:3558911335 1500 bytes is out-of-order; expected seq:3558888055. Reason: TCP reassembly queue overflow - session 192.168.23.38:54435 to 65.199.63.58:801024 The following command seems to have worked for me by extending the queue reassembly queue. ip inspect tcp reassembly queue length 1024 I suppose it's a long shot, since I don't know your config. Hope that helps! Colin Jaccino How many users do you have behind these routers? Presumably you're doing NAT on a single, external address. Modern software, especially webservices like facebook chat, etc. open a lot of concurrent TCP connections. Cisco's, I believe, have a statically sized NAT translation table. It may be overflowing and evicting the oldest connection? I'm afraid that I cannot offer any advice on checking if the NAT tables are overflowing or not. I would not be inclined to suspect the firmware, especially if its been working reasonably for years before. I would, however, suggest giving the interface statistics a quick double check. If you're seeing dropped, invalid, badrx checksum, etc. errors on an interface, then that may well be the source of your problem. Either failing hardware, insufficient electrical isolation, or something else. I've stopped counting how many 'cheap' 5 port 10/100 or gigabit switch's i've seen semi-fail and become inconsistent and erratic in the past 3-4 years due to bulging/exploding capacitors internally. A show interfaces counters errors statement should identify any troublesome interfaces very quickly. Good luck. This sounds a lot like a path MTU problem where a path is switching during the transfer with a different MTU and because no ip unreachables is defined, it does not notify that it needs to fragment the packets. no ip unreachables It's fairly easy to test this with different ping packet sizes or if the problem happens fairly often, put the command ip tcp adjust-mss 1360in the outbound path WAN interface, or Fa4 in this case. 1360 should be safely below any shrunk MTUs and won't affect throughput terribly. ip tcp adjust-mss 1360 If it clears up with this command, it was an MTU problem and you can try to raise it to 1440 or 1460 to gain a bit of throughput. I can't see your ACL but make sure you are allowing at least permit icmp any any packet-too-big permit icmp any any packet-too-big By posting your answer, you agree to the privacy policy and terms of service. asked 4 years ago viewed 6498 times active 2 years ago
http://serverfault.com/questions/215443/why-do-cisco-ios-routers-hang-in-the-middle-of-large-downloads/223128
CC-MAIN-2015-22
refinedweb
1,585
58.69
Ok so i got this CSharp coding problem put to me and it has me absolutely stumped, it has to do with interfaces and cards, here is the skeleton code which i must alter: public interface ICard { } public interface IPackCards : IReadOnlyCollection<ICard> { void Shuffle (); ICard TakeCardFromTopOfPack (); } public interface IPackCardsCreator { IPackCards Create (); } public class PackCardsCreator : IPackCardsCreator { public IPackCards Create() { throw new NotImplementedException(); } } Problem: Please finish the implementation of PackOfCardsCreator and create implementations of IPackOfCards and ICard. The PackOfCardsCreator should create a standard pack of cards. This should be made up of 52 cards, with 4 different suits (Clubs, Hearts, Spades and Diamonds) and numbered 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, and Ace. You are free to do this however you like. IPackOfCards.Shuffle() should rearrange the cards in a random order. Repeated shuffles should not all return the cards in the same order. IPackOfCards.TakeCardFromTopOfPack() should return and remove the first card from cards in the pack. by AbsoluteLove via /r/csharp
http://howtocode.net/2015/06/csharp-coding-problem-i-am-stumped/
CC-MAIN-2018-43
refinedweb
167
50.77
A friendly place for programming greenhorns! Big Moose Saloon Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login JavaRanch » Java Forums » Java » Beginning Java Author Why is my string still writing data to my file that i've asked it not to? Nick Rowe Ranch Hand Joined: May 26, 2010 Posts: 88 posted Jul 27, 2010 05:51:57 0 Basically i have a program to read in the contents of a folder and capture instances of a substring stored between two strings. I want the instances of the substring called "resourceline" to be stored within an array and then sorted and printed into a new document. However i only want the instances to be stored IF they dont already exist and if the string does not contain certain symbols. I am doing this because i get too much irrelevant data come accross. The problem is the progam is working but still writing data that i dont want. please help regards S my code is below /** Imported Java Libraries */ import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Collections; import java.util.List; import java.io.PrintWriter; import java.io.FileWriter; /** class to find string */ public class Find { BufferedReader br = null; /** method to find the value between the beginning and end of a string*/ public Find(String fileName, String begin, String end,String whereToWrite) throws java.io.IOException { try { /** read in file */ String resourceline = null; ArrayList<String> arrayList = new ArrayList<String>(); File myDir = new File("C:\\Documents and Settings\\Kieren McDonald\\Desktop\\Nick\\Java\\Test\\resources"); if (myDir.exists() && myDir.isDirectory()) { File[] files = myDir.listFiles(); for (int i = 0; i < files.length; i++) { br = new BufferedReader(new FileReader(files[i])); while ((resourceline = br.readLine()) != null) { resourceline = find(begin, end, resourceline); if (resourceline != null) { resourceline = resourceline.trim(); boolean checkContains1=resourceline.contains("$"); boolean checkContains2=resourceline.contains("="); boolean checkContains3=resourceline.contains("\>"); boolean checkContains4=resourceline.contains(":"); boolean checkContains4=resourceline.contains("."); if (checkContains1 || checkContains2 || checkContains3 || checkContains4 || checkContains5) { } if (arrayList.contains(resourceline)){ } else{ arrayList.add(resourceline); } } } System.out.println("/**This Is A List Of Includes Within The Component*/"); sortAndPrint(arrayList); System.out.println("/*******This Is The End Of The list Of Includes*******/"); writeResults(arrayList, "C:\\Documents and Settings\\Kieren McDonald\\Desktop\\Nick\\Java\\Test\\filetest.txt"); } } else { System.out.println("This is not a directory"); } /** * declaring string identifiers for beginning and end of string * aswel as one other line string to store the data between */ /** while line is not equal to null then find 3 string values */ } catch (FileNotFoundException ex) { ex.printStackTrace(); } finally { br.close(); } } /** method to sort and print the array collection */ private void sortAndPrint(List<String> results) { Collections.sort(results, String.CASE_INSENSITIVE_ORDER); for (String resourceline : results) { System.out.println(resourceline); } } /** method to find the value between the beginning and end of a string */ public String find(String beg, String end, String resourceline) { /** match pattern to store string between strings and match to line */ Pattern p = Pattern.compile(beg + "(.*)" + end); Matcher m = p.matcher(resourceline); return m.find() ? resourceline.substring(m.start(1), m.end(1)) : null; } /** method to print the results of the array into a new document */ private void writeResults(ArrayList<String> arrayList, String filename) { try { PrintWriter writer = new PrintWriter(filename); for (String resourceline : arrayList) { writer.println(resourceline); } System.err.println("/***Your Data Has Been Written To The File Successfully "); writer.close(); } catch (Exception e) { System.out.println("can't create output file \"" + filename + "\""); e.printStackTrace(); } } /** main method to find the resource name calling */ public static void main(String[] args) throws IOException { Find f = new Find("myDir", "<\\$", "=", "C:\\Documents and Settings\\Kieren McDonald\\Desktop\\Nick\\Java\\Test\\filetest.txt"); } } akhter wahab Ranch Hand Joined: Mar 02, 2009 Posts: 151 I like... posted Jul 27, 2010 06:07:50 0 provide one example what you are providing the input, what it gives the output and what you want to desire from this code ........ Start Earning Online || Start Earning Using Java Prabhakar Reddy Bokka Ranch Hand Joined: Jul 26, 2005 Posts: 193 I like... posted Jul 27, 2010 06:08:00 0 if (checkContains1 || checkContains2 || checkContains3 || checkContains4 || checkContains5) { } Use && in place of || and check. Hope it works fine now. SCJP 5, SCWCD 5 David Newton Author Rancher Joined: Sep 29, 2008 Posts: 12617 I like... posted Jul 27, 2010 06:49:20 0 Prabhakar Reddy Bokka wrote: Use && in place of || and check. No, that would mean the "blank" code would execute only if *all* of the conditions are met; my understanding is that if *any* of the characters are found it's a match. (I realize it's hard to tell because of the strange nature of the code.) David Newton Author Rancher Joined: Sep 29, 2008 Posts: 12617 I like... posted Jul 27, 2010 06:54:24 0 @Nick: Again--PLEASE post compilable code. There are three errors in this source. Ernest Friedman-Hill author and iconoclast Marshal Joined: Jul 08, 2003 Posts: 24189 34 I like... posted Jul 27, 2010 07:27:07 0 As I see it, this should follow your requirement about duplicates, but ignore your requirement about special characters. There are two completely unconnected conditionals: the first one, "if (checkContains1...", controls access to an empty block, so it does absolutely nothing. Then the next conditional is tested regardless of the outcome of the first . It checks for duplicates, and otherwise then adds the line to the list. If your "checkContains" check had a "continue" in it, or if it was attached to the later conditional with an "else", then we'd be getting somewhere. [Jess in Action] [AskingGoodQuestions] I agree. Here's the link: subject: Why is my string still writing data to my file that i've asked it not to? Similar Threads Substring capture To Write A list Of instances in A New Document Returning A List Of Variables From A Folder Of Documents And Returning Them Into A New Document Calling the method from another method within the same class If String Contains (symbols) then call main method Dumping A string value??? All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/504373/java/java/string-writing-data-file-ve
CC-MAIN-2015-06
refinedweb
1,045
50.23
This is my code: //VariableArguments3.java public class VariableArguments3 { static void test(String s,int ...v) { System.out.println("length:"+v.length+" String:" +s); for(int x:v) System.out.println("x="+x); } static void test(String s,double ...d) { System.out.println("length:"+d.length+" String:" +s); for(double x:d) System.out.println("x="+x); } } and //VariableArguments3.java public class VariableArguments3Test { public static void main(String args[]) { VariableArguments3.test("harshal",33,43,34,23,24); VariableArguments3.test("hosha",43,442); VariableArguments3.test("hosha",67.7,7.53,73.23); } } i am getting following error: VariableArguments3Test.java:5: reference to test is ambiguous, both method test( java.lang.String,int...) in VariableArguments3 and method test(java.lang.String, double...) in VariableArguments3 match VariableArguments3.test("harshal",33,43,34,23,24); ^ VariableArguments3Test.java:6: reference to test is ambiguous, both method test( java.lang.String,int...) in VariableArguments3 and method test(java.lang.String, double...) in VariableArguments3 match VariableArguments3.test("hosha",43,442); ^ Now i want to ask that why the VariableArguments3.test("harshal",33,43,34,23,24); and VariableArguments3.test("hosha",43,442); does not transfer the control to static void test(String s,int ...v) in the first file. Why does it treat static void test(String s,int ...v) and static void test(String s,double ...d) as equal. Why are the integers passed are treated as equal to double?Shouldn't the integer implicitly convert to double only when method for interger is not specified? What version of Java are you running? I tried... public void x(String s, int... i) {System.out.println("i");} public void x(String s, double... d) {System.out.println("d");} public void run() { x("abc", 1,2); x("abc", 1.0,2.0); } ... and that works exactly as you would expect - Java 1.7 Windows 64. i am using : java version "1.6.0_33" Java(TM) SE Runtime Environment (build 1.6.0_33-b03) Java HotSpot(TM) Client VM (build 20.8-b03, mixed mode, sharing) Windows 32 bits Just to be sure, so it's just like yours, I tried class Test { public static void x(String s, int... i) {System.out.println("i "+i[0]);} public static void x(String s, double... d) {System.out.println("d "+d[0]);} } ... public class Demo { public static void main(String[] args) { Test.x("abc", 1,2); Test.x("abc", 1.0,2.0); } ... ... and still it compiles and executes exactly as expected. Can you try that exact code on your machine and see what result you get? when i execute your code i am getting this error: Demo.java:5: reached end of file while parsing }→ ^ 1 error Yes, obviously that wasn't a complete file (hence the ...'s between the classes and at the end). It just a bit of code that you can insert into an existing file to test it ok i will do it now. Anybody else out there watching? Can anyone else replicate this? ok, the previous error occured because i didn't put } in the end. Now i corrected it and i am getting the same error that i got first time. Demo.java:3: reference to x is ambiguous, both method x(java.lang.String,int...) in Test and method x(java.lang.String,double...) in Test match Test.x("abc", 1,2); ^ 1 error Well now, this is very interesting. Culd this be a difference between 1.6 and 1.7? may be this could be the difference(but this should be executed using 1.6 also), but let's wait till some other member try to execute this using java 1.6 public class JavaApplication186 { /** * @param args the command line arguments */ public static void main(String[] args) { Test.x("abc", 1, 2); Test.x("abc", 1.0, 2.0); } } class Test { public static void x(String s, int... i) { System.out.println("i " + i[0]); } public static void x(String s, double... d) { System.out.println("d " + d[0]); } } Hmm I got this exact code to compile under JDK 7 and JDK6? Then what's the problem on my side? How did you checked on both the versions?Can we keep both version installed on the same pc? Thank you David. So what could it be about hszforu's configuration that's different? How did you checked on both the versions?Can we keep both version installed on the same pc? I have both JDK's (yes you can) so just let my Netbeans compile under the libraries of each. I did your code too and all fine, I even went to JDK 5 (using netbeans project properties) but no error. Not sure whats wrong. Thank you David. Pleasure reference to test is ambiguous found an interesting article: especially this: The problem here is that, when a value is passed to a mathod, it may be automatically converted to a wider data type For example, this is perfectly legal: public class Test { public void doIt(int a) {...} public static void main(String[] args) { Test t = new Test(); byte b = 1; t.doIt(b); } } This is valid because a byte can be safely converted to an int. Therefore, an implicit cast takes place prior to invocation of the doIt method. You don't actually send a byte to doIt, you send an int to doIt. That int was created by implicitly widening the original byte value. In your case, you have three integer literals. In Java, a numeric literal is considered an int. Therefore, you're trying to pass 3 ints to a method. The compiler then looks for any methods by that name that can take 3 ints. There is no such method, but there are these other two that can take combinations of ints and longs. Well, an int can be converted to a long, so these methods are applicable. so as we can see the compiler doesnt know which to choose in the OPs code an int can be impliclity converted to a double, though I'm not sure why it won't replicate this on other PC's with same version, maybe its an IDE bug? It's a Java compiler bug. Fixed in Java 7. Ok thanks , but if it's a bug, then how DavidKroukamp successfully executed it under 1.6. I guess my netbeans complied using jdk 6 libraries & rules but not the compiler ok Thanks both of you.
http://www.daniweb.com/software-development/java/threads/427395/problem-with-ints-and-doubles
CC-MAIN-2014-15
refinedweb
1,074
69.68
On the week of Black Friday, Cloudflare automatically detected and mitigated a unique ACK DDoS attack, which we’ve codenamed “Beat”, that targeted a Magic Transit customer. Usually, when attacks make headlines, it’s because of their size. However, in this case, it’s not the size that is unique but the method that appears to have been borrowed from the world of acoustics. Acoustic inspired attack As can be seen in the graph below, the attack’s packet rate follows a wave-shaped pattern for over 8 hours. It seems as though the attacker was inspired by an acoustics concept called beat. In acoustics, a beat is a term that is used to describe an interference of two different wave frequencies. It is the superposition of the two waves. When the two waves are nearly 180 degrees out of phase, they create the beating phenomenon. When the two waves merge they amplify the sound and when they are out of sync they cancel one another, creating the beating effect. Acedemo.org has a nice tool where you can create your own beat wave. As you can see in the screenshot below, the two waves in blue and red are out of phase and the purple wave is their superposition, the beat wave. Reverse engineering the attack It looks like the attacker launched a flood of packets where the rate of the packets is determined by the equation of the beat wave: y‘beat=y1+y2. The two equations y1 and y2 represent the two waves. Each equation is expressed as where fi is the frequency of each wave and t is time. Therefore, the packet rate of the attack is determined by manipulation of the equation to achieve a packet rate that ranges from ~18M to ~42M pps. To get to the scale of this attack we will need to multiply y‘beat by a certain variable a and also add a constant c, giving us ybeat=ay‘beat+c. Now, it’s been a while since I played around with equations, so I’m only going to try and get an approximation of the equation. By observing the attack graph, we can guesstimate that by playing around with desmos’s cool graph visualizer tool, if we set f1=0.0000345 and f2=0.00003455 we can generate a graph that resembles the attack graph. Plotting in those variables, we get: Now this formula assumes just one node firing the packets. However, this specific attack was globally distributed, and if we assume that each node, or bot in this botnet, was firing an equal amount of packets at an equal rate, then we can divide the equation by the size of the botnet; the number of bots b. Then the final equation is something in the form of: In the screenshot below, g = f 1. You can view this graph here. Beating the drum The attacker may have utilized this method in order to try and overcome our DDoS protection systems (perhaps thinking that the rhythmic rise and fall of the attack would fool our systems). However, flowtrackd, our unidirectional TCP state tracking machine, detected it as being a flood of ACK packets that do not belong to any existing TCP connection. Therefore, flowtrackd automatically dropped the attack packets at Cloudflare’s edge. The attacker was beating the drum for over 19 hours with an amplitude of ~7 Mpps, a wavelength of ~4 hours, and peaking at ~42 Mpps. During the two days in which the attack took place, Cloudflare systems automatically detected and mitigated over 700 DDoS attacks that targeted this customer. The attack traffic accumulated at almost 500 Terabytes out of a total of 3.6 Petabytes of attack traffic that targeted this single customer in November alone. During those two days, the attackers utilized mainly ACK floods, UDP floods, SYN floods, Christmas floods (where all of the TCP flags are ‘lit’), ICMP floods, and RST floods. The challenge of TCP based attacks TCP is a stateful protocol, which means that in some cases, you’d need to keep track of a TCP connection’s state in order to know if a packet is legitimate or part of an attack, i.e. out of state. We were able to provide protection against out-of-state TCP packet attacks for our “classic” WAF/CDN service and Spectrum service because in both cases Cloudflare serves as a reverse-proxy seeing both ingress and egress traffic. However, when we launched Magic Transit, which relies on an asymmetric routing topology with a direct server return (DSR), we couldn’t utilize our existing TCP connection tracking systems. And so, being a software-defined company, we’re able to write code and spin up software when and where needed — as opposed to vendors that utilize dedicated DDoS protection hardware appliances. And that is what we did. We built flowtrackd, which runs autonomously on each server at our network’s edge. flowtrackd is able to classify the state of TCP flows by analyzing only the ingress traffic, and then drops, challenges, or rate-limits attack packets that do not correspond to an existing flow. flowtrackd works together with our two additional DDoS protection systems, dosd and Gatebot, to assure our customers are protected against DDoS attacks, regardless of their size or sophistication — in this case, serving as a noise-canceling system to the Beat attack; reducing the headaches for our customers. Read more about how our DDoS protection systems work here.
https://engineeringjobs4u.co.uk/an-acoustics-inspired-ddos-attack
CC-MAIN-2021-25
refinedweb
917
67.08
User-defined literals are a convenient feature added in C++11. C++ always had a number of built-in ways to write literals: pieces of source code that have a specific type and value. They are part of the basic building blocks of the language: 32 043 0x34 // integer literals, type int 4.27 5E1 // floating point literals, // type double 'f', '\n' // character literals, type char "foo" // string literal, type const char[4] true, false // boolean literals, type bool These are only the most common ones. There are many more, including some newcomers in the newer standards. Other literals are nullptr and different kinds of prefixes for character and string literals. There also are suffixes we can use to change the type of a built-in numeric literal: 32u // unsigned int 043l // long 0x34ull // unsigned long long 4.27f // float 5E1l // long double Suffixes for user-defined literals With C++11, we got the option of defining our own suffixes. They can be applied to integer, floating point, character and string literals of any flavor. The suffixes must be valid identifiers and start with an underscore – those without an underscore are reserved for future standards. Using the literals User-defined literals are basically normal function calls with a fancy syntax. I’ll show you in a second how those functions are defined. First, let’s see some examples of how they are used: - user-defined integer literal with suffix _km 45_km - user-defined floating point literal with suffix _mi 17.8e2_mi - user-defined character literal with suffix _c 'g'_c - user-defined character literal ( char32_t) with suffix _c U'%'_c - user-defined string literal with suffix _score "under"_score - user-defined string literal (raw, UTF8) with suffix _stuff u8R"##("(weird)")##"_stuff Defining literal operators The functions are called literal operators. Given an appropriate class for lengths, the definition of literal operators that match the first two examples above could look like this: Length operator "" _km(unsigned long long n) { return Length{n, Length::KILOMETERS}; } Length operator ""_mi(long double d) { return Length{d, Length::MILES}; } More generally, the syntax for the function header is <ReturnType> operator "" <Suffix> (<Parameters>). The return type can be anything, including void. As you see, there can be whitespace between the "" and the suffix – unless the suffix standing alone would be a reserved identifier or keyword. That means, if we want our suffix to start with a capital letter after the underscore, e.g. _KM, there may be no white space. (Identifiers with underscores followed by capitals are reserved for the standard implementation.) The allowed parameter lists are constrained: for a user-defined integral or floating point literal, you can already see an example above. The compiler first looks for an operator that takes an unsigned long long or long double, respectively. If such an operator can not be found, there has to be either one taking a char const* or a template<char...> operator taking no parameters. In the case of the so-called raw literal operator taking a const char, the character sequence constituting the integral or floating point literal is passed as the parameter. In the case of the template, it is passed as the list of template arguments. E.g. for the _mi example above this would instantiate and call: operator ""_mi<'1', '7', '.', '8', 'e', '2'>() Use cases The example with the units above is a pretty common one. You will have noted that both operators return a Length. The class would have an internal conversion for the different units, so with these user defined literals it would be easy to mix the units without crashing your spaceship [Wikipedia]: auto length = 32_mi + 45.4_km; std::cout << "It's " << length.miles() << " miles\n"; //60.21 std::cout << "or " << length.kilometers() << " kilometers.\n"; //96.899 The standard library also contains a bunch of these (and yes, they still are called ‘user-defined’ in standard speak). They are not directly in namespace std but in subnamespaces of std::literals: - From std::literals::complex_literals, the suffixes i, ifand ilare for the imaginary part of std::complexnumbers. So, 3.5ifis the same as std::complex<float>{0, 3.5f} - From std::literals::chrono_literals, the suffixes h, min, s, ms, usand nscreate durations in std::chronofor hours, minutes, seconds, milli-, micro- and nanoseconds, respectively. - In std::literals::string_literals, we have the suffix sto finally create a std::stringright from a string literal instead of tossing around char const*. A word of caution While user defined literals look very neat, they are not much more than syntactic sugar. There is not much difference between defining and calling a literal operator with "foo"_bar and doing the same with an ordinary function as bar("foo"). In theory, we could write literal operators that have side effects and do anything we want, like a normal function. However, that is not what people would expect from something that does not look like ‘it does something’. Therefore it is best to use user defined literals only as obvious shorthand for the construction of values. Playing with other modern C++ features A while ago I came across a case where I had to loop over a fixed list of std::strings defined at compile time. In the old days before C++11, the code would have looked like this: static std::string const strings[] = {"foo", "bar", "baz"}; for (std::string const* pstr = strings; pstr != strings+3; ++pstr) { process(*pstr); } This is horrible. Dereferencing the pointer and the hard-coded 3 in the loop condition just don’t seem right. I could have used an std::vector<std::string> here, but that would mean a separate function to prefill and initialize the const vector since there were no lambdas. Today we have range based for, initializer_list, auto and user-defined literals for strings: using namespace std::literals::string_literals; //... for (auto const& str : {"foo"s, "bar"s, "baz"s}) { process(str); } And the code looks just as simple as it should. References [Wikipedia] The Mars Climate Orbiter: Cause of Failure
https://accu.org/index.php/journals/2318
CC-MAIN-2020-29
refinedweb
1,005
53.1
Alright this mite b kind of long so thx in advance if u can help me i really really appreciate this. my program was already done. its an association and containment program between pets and their owners and ive done all the stuff already except the owners birthdate.. I now have to use the schools Date class to output the owners birthdate and im havin trouble doing that. i had it working b4 using their class now icant get it. Its alot of diff files ill post what i think shows the prob and if u need more ill post it. here is the date.cpp file i wont post the .h b/c its pretty much the same ig uess but w/ ou the definitions Date.cpp - THIS CANT B CHANGED i didnt write this lol here is my owners.h - ive cut it downhere is my owners.h - ive cut it downCode:#include "Date.h" #include <iostream> #include <cstdlib> // When we're not in a header file, it is ok to // have "using namespace std" using namespace std; namespace CS1124{ Date::Date(string date) { // atoi comes month = atoi(date.substr(0,2).c_str()); day = atoi(date.substr(3,2).c_str()); year = atoi(date.substr(6,4).c_str()); } void Date::display(std::ostream& os) const { os << month << '/' << day << '/' << year; } bool Date::earlierThan(Date d) const { if (year > d.year) return false; else if (year < d.year) return true; else if (month > d.month) return false; else if (month < d.month) return true; else if (day >= d.day) return false; else return true; } int Date::getYear() const { return year; } void Date::setYear(int x) { year = x; } } and the cpp cut down as welland the cpp cut down as wellCode:#ifndef OWNER_H #define OWNER_H #include "Pet.h" #include "Date.h" #include <string> namespace CS1124 { class Owner { public: //constructor initializes the name of the owner and the birthdate Owner(std::string ownerName, std::string date); void displayDate (); private: //int month, day, year; std::string ownerName; //owners name Date date; //from date class. will get the birthdate Pet* pet; // pointer to the pet class for a pet }; //Overload << to output the information std::ostream& operator << (std::ostream & os,const Owner& owner); } #endif im sorry its so long - basically i just want to display the date and i have to use the date class to get it and display... ive tried doingim sorry its so long - basically i just want to display the date and i have to use the date class to get it and display... ive tried doingCode:#include "Owner.h" #include "Date.h" using namespace std; namespace CS1124 { //constructor intializes the owners name, the birthdate from the date class //as well as setting the owner to have no initial pet Owner::Owner(std::string ownerName, std::string date): ownerName(ownerName), date(date), pet(NULL) {} //output the owners and pets names void Owner::displayDate() { date.display(); } ostream& operator << (ostream & os,const Owner& owner) { //-------------------------------------------- //THIS IS WHERE MY PROBLEM ISS!!!!!!! //owner.displaydate in specific //----------------------------------------------- //display the owner os<< "Owner: " << owner.getName() << " DOB: " <<" " << owner.displayDate(); os << " My Pet: "; //Check if he has a pet if(owner.getPet())//display that pet os<<owner.getPet()->getName(); else //if not say he doesnt os<<"I don't have a pet."; return os; } } date.display() in the overload << function that didnt work. i tried now as u can c making a display func inside of owner that dislays the date but thast not working any help is appreciated.. im aslo going to attach the files incase any1 gets really bored. BTW i coulnt upload Pet.h and pet.cpp b/c im liimted to 5 but i can in another post if any1 wants it lol i doubt it
http://cboard.cprogramming.com/cplusplus-programming/70863-help-calling-function.html
CC-MAIN-2015-48
refinedweb
621
74.9
Peng Ren4,119 Points code not working, can't figure out why I ran my code in workspaces, apart from saying something is off with tab and indentation, workspace doesn't say where else is wrong. can anyone gimme a hand? thanks a mil! def combiner(argu): sum = 0 word = '' for it in argu: if isinstance(it, (int,float)): sum += ''.join(it) elif isinstance(it, str): word += ''.join(it) return word+str(sum) 1 Answer diogorferreira19,362 Points When you are adding the it to either variables (sum and word), you don't need to .join() them - It raises an error anyways as itis not an iterable like the array they are passing to you, itwould be things like the strings 'apple' 'dog' or integers like 9 or 7 - The return statement is also inside the for loop just indent it back so it only calls after the for loop is called otherwise it would return after ever loop These are the changes I made to your code def combiner(argu): sum = 0 word = '' for it in argu: if isinstance(it, (int,float)): sum += it elif isinstance(it, str): word += it return word+str(sum) Jialong Zhang9,816 Points Jialong Zhang9,816 Points You can only use join in a list, tuple, dictionary. You convert them to string, and separate by the seperator. The usage of join is something like:
https://teamtreehouse.com/community/code-not-working-cant-figure-out-why
CC-MAIN-2019-51
refinedweb
230
73.31
Pandas is a great python module that allows you to manipulate the dataframe or your dataset. There are many functions in it that efficiently do manipulation. There is a time where you need to divide two columns in pandas. In this entire tutorial, you will how to divide two columns in pandas using different methods. Methods to divide two columns in Pandas In this section, you will know all the methods to divide two columns in pandas. Please note that I am implementing all the examples on Jupyter Notebook. Make sure to do it for better understanding. Method 1: Using a simple division operator The first method you can use to divide two columns is the simple division (/) operator. Here you will divide column1 with other columns. Execute the below lines of code. import pandas as pd data = {"col1":[100,200,300,400,500],"col2":[10,20,30,40,50]} df= pd.DataFrame(data) df["result"] = df["col1"]/df["col2"] print(df) You can see in the above code I am first creating data and converting it to dataframe using pd.DataFrame() method. Lastly, I am dividing df[“col1”] with df[“col2”] and assigning it to the result column. When you will run the code you will get the following output. Output Method 2: Pandas divide two columns using div() function The second method to divide two columns is using the div() method. It divides the columns elementwise. It accepts scalar value, series, or dataframe as an argument for dividing with the axis. If the axis is 0 the division is done row-wise and if the axis is 1 then division is done column-wise. Execute the below lines of code. import pandas as pd data = {"col1":[100,200,300,400,500],"col2":[10,20,30,40,50]} df= pd.DataFrame(data) df["result"] = df["col1"].div(df["col2"].values) print(df) In the above, you can see I am dividing col1 with the value of col2 bypassing the df[“col2”] .values as an argument. By default, the axis is 0. Output Conclusion Pandas python module can do fast manipulation on any dataframe. These are the method to divide two columns in dataframe. You can use any of them. I hope you have liked this tutorial. If you have any queries 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/divide-two-columns-in-pandas-methods/
CC-MAIN-2021-39
refinedweb
409
67.55
GroupCheckBox - Creating group checkboxes By MrCreatoR, in AutoIt Example Scripts Recommended Posts Similar Content -?? - Jibberish Hello, I have used this forum to get help many times. I thought it was time to (hopefully) help others. I created a script that reads a text file with a list of videos, displays the videos in a GUI with checkboxes next to the names, and displays the selected videos. This will become a part of a larger script I am creating to test a video player. The tough part for me was creating the GUI and Dynamic list of videos. I had a lot of trouble finding samples to help me, but finally found one written by Melba23. The link is in the code, so he gets credit for helping! I also have not used arrays much and they are very picky about looping through the arrays without getting the dreaded error " Array variable has incorrect number of subscripts or subscript dimension range exceeded." However diligence paid off! To run this code, take the video names commented below and create a videos.txt file in your script execution directory. You can put however many video names in this list. Thus the dynamic features of the code. Cheers! Jibberish #include <MsgBoxConstants.au3> #include <StringConstants.au3> #include <array.au3> #include <File.au3> #include <GUIConstantsEx.au3> Local $sMediaFile = @ScriptDir & "\videos.txt" ;~ Videos in videos.txt are: ;~ bbb_1080_60s.mp4 ;~ bbb_1080_60s_1.mp4 ;~ bbb_1080_60s_2.mp4 ;~ tos_4K_60s_HEVC.mp4 ;~ tos_4K_60s_HEVC_1.mp4 ;~ tos_4K_60s_HEVC_2.mp4 ;~ ;~ Additional videos can be added to this list. The functions are Dynamic. Dim $aMediaManifest Local $aArrayFile Local $aVideos Local $sVideoName Local $i ; MAIN ; Put the Video File Names into an Array _FileReadToArray($sMediaFile, $aArrayFile) Local $iVideoCount = UBound($aArrayFile) -1 ; Get the number of videos - 1 to prevent errors _ArrayDelete($aArrayFile, 0) ;Counter just gets in the way ; Move backwards through the array deleting the blank lines For $i = $iVideoCount - 1 To 0 Step -1 If $aArrayFile[$i] = "" Then _ArrayDelete($aArrayFile, $i) EndIf Next $aVideos = DisplayVideos($aArrayFile) $iVideoCount = UBound($aArrayFile) -1 _ArrayDisplay($aVideos) ; Display the checked videos ;~ End of MAIN ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ; ; GUI to display Videos in checkboxes ; ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Func DisplayVideos($aArrayFile) Local $iTop = -1 Local $iLeft = -1 Local $iWidth Local $iHeight = $iVideoCount * 30 Local $iL = 10 Local $iT = 10 Local $iRow = 0 Local $aVideo Local $iA = 0, $iB = 0 Local $sFill = "" $iMMCount = UBound($aArrayFile) $iMMNewCount = $iMMCount - 1 Local $aGUICheckbox[$iMMCount] Local $aCheckedVideos[$iMMCount] ; Put the Video File Names into an Array $hGUI = GUICreate("Video Checkbox", $iLeft, $iTop, $iWidth, $iHeight) GUICtrlCreateLabel("Videos", 180, $iT) $iT = $iT + 30 ; This is a great example of using arrays to create GUI check boxes or radio buttons For $i = 0 To $iMMNewCount Step 1 $sMP4Text = $aArrayFile[$i] $aGUICheckbox[$i] = GUICtrlCreateCheckbox($sMP4Text, 30, $iT) $iT += 30 Next $idClose1 = GUICtrlCreateButton("Start", $iL, $iT) GUISetState(@SW_SHOW) ; This section reads the checkboxes and puts the video names in an array in their original position ; in case this is important (as it is to me) ; This was the toughest part to code, and I found no samples online until I saw Melba23's sample here: ; ; I got this working with only a little modification. THANK YOU MELBA23 While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $idClose1 For $i = 0 To $iMMNewCount Step 1 Switch GUICtrlRead($aGUICheckbox[$i]) Case $GUI_CHECKED $aCheckedVideos[$i] = $aArrayFile[$i] Case $GUI_UNCHECKED EndSwitch Next ExitLoop EndSwitch WEnd GUIDelete($hGUI) Return $aCheckedVideos EndFunc ;==>DisplayVideos
https://www.autoitscript.com/forum/topic/177520-groupcheckbox-creating-group-checkboxes/
CC-MAIN-2018-26
refinedweb
557
51.28
hello Java Hello World HELLO World program in Java hello Java Error in Hello World Java Error in Hello World Servlet Java Servlet error Tomcat Quick Start Guide Tomcat Quick Start Guide This tutorial is a quick reference of starting development application using JSP, Servlets and JDBC technologies. In this quick and very Hi vineet, Alphabetical sarching is completed please tell me other parts means If user click the search button then all data should be displayed but table has been stored in the 900 or more than 900 then page   hi roseindia - Java Beginners . Thanks. Amardeep Hello Eyeryone... Hello Eyeryone... how to download java material in roseindia.net website material please kindly help me... by visu hello hello how to print from a-z, A-Z with exact order using for loop? Thanks for all concern hi roseindia - Java Interview Questions :// Thanks Struts 2.1.8 Hello World Example Struts 2.1.8 Hello World Example In this section we will learn how to develop our first Hello World... to develop simple Hello World example in Struts 2.8.1. You will also learn how Hello World - Java Beginners Hello World Java Beginner - 1st day. Looked at the Hello World......){ System.out.println("Hello World!"); } } what am I doing wrong. Am I expecting... for more information. Flex Java Developers versa. Roseindia has a strong team of Flex Java developers that can develop... applications in Flex. Our Flex Java developers team include Flex programmers, XML...Flex Java Developers Adobe Flex is a standards-based programming methodology Hello world Hello world (First java program)  .... Hello world program is the first step of java programming language... learned how to write and then test the Hello World! java program Hello - Java Beginners Simple JSF Hello Application Simple JSF Hello Application  ... application. In this example we will explain all you need, to develop this application... with the greeting content to the user. Steps Followed : We will follow the following steps Displaying Hello World using GWT Hello World using GWT in java. By GWT we mean Google Web Toolkit,Google Web... Displaying Hello World using GWT  ... JavaScript front-end applications in the Java programming language. The steps Hello world program Hello world program hello world program class Hello{ public static void main(String[] args) { System.out.println("Hello...:// find all unique character in string using java find all unique character in string using java example: hello how are you. output should be waryu Struts 2 Hello World AnnotationTest Struts 2 Hello World example!!<... successfully developed and tested the Hello World application using Java...Video tutorial of creating Struts 2 Hello World Annotation Example in Eclipse Java String : Replace All Java String : Replace All This section defines how to replace all character with specified character without using system methods. Replace All method : You can replace all specific character in a given string with another character the solutions import javax.swing.table.*; import javax.swing.*; import java.util.*; import java.awt.*; import java.awt.event.*; import java.awt.print.*; import Develop Hello World example using Spring 3.0 Framework ; button. And add all the libraries to Java Build Path.  ... Spring 3 Hello World Example  ..., create new project in Eclipse IDE and then write simple Hello World application Roseindia Spring Tutorial Roseindia Spring tutorials provide you complete coverage of wide range... at Roseindia starting from starting from environment setup, inversion of control... steps. In addition to that, Spring tutorials roseindia makes you Java - Applet Hello World Java - Applet Hello World This example introduces you with the Applet in Java... is a program provided by java which is designed for execution within the web browser Please help need quick!!! Thanks Please help need quick!!! Thanks hey i keep getting stupid compile...(){ Scanner input = new Scanner(System.in); double[] team = new double[10]; for(int i = 0; i < team.length; i++){ team[i JavaScript - JavaScript Tutorial of the best Quick reference to the JavaScript. In this JavaScript reference you will find most of the things about java script. JavaScript tutorial is classified... with the Java Scripting language. You will learn the benefits of using JavaScript Quick introduction to web services Quick introduction to web services Introduction: Web services... talk to java web services and vice versa. So, Web services are used JAVA7 : "Hello World" Example is beginning point of java program execution. System.out.println(?Hello World...JAVA7 : "Hello World" Example This tutorial elaborate a simple example of JAVA 7. Creating Java Program : Before writing java program we Hello world (First java program) Hello world (First java program)  ... and running. Hello world program is the first step of java programming language...;java HelloWorld You will see the following result on the command prompt. Hello Java count words from file Java count words from file In this section, you will learn how to determine the number of words present in the file. Explanation: Java has provides several.... Here is the file.txt: Hello World All glitters Hello World in Echo3 framework Hello World in Echo3 framework Since "Hello World" example is everyone's... with the "Hello World" example in Echo3. We have illustrated the first java - Java Beginners java All the data types uses in java and write a program to add 2... all the data type used in Java :... that these links would be helpful to you. Thanks RoseIndia Team php list all server variables PHP list All server variables is present in the $_SERVER environment variables. Using the for each loop all keys and values can be accessed Example of PHP List all Server <?php print"<table Plz provide me all the material for Java Plz provide me all the material for Java Plz provide me all the material for Java Please go through the following link: Java Tutorials all comment in jsp all comment in jsp Defined all comment in jsp ? jsp... compiled as we all know that they are not executed and they simply serve... and hence it doesn't remove them. All HTML comments are maintained in the response hello sir, please give me answer - Java Beginners hello sir, please give me answer Write a program in Java that calculates the sum of digits of an input number, prints... ways in java? so , sir please tell me full solution of this program Here is your complete How would you honestly evaluate the strengths and weaknesses of your previous/current company/boss/team? previous/current company/boss/team?  ... is the least interested in the company/boss/team. They are simply checking how you... your current/previous boss/team/company behind their back, the interviewer Hibernate Tutorial for Beginners Roseindia is an Object-Relational Mapping (ORM) framework for Java built by JBoss... the Java classes to a Database tables using an XML file Hibernate maps... Java objects from database. Programmer must not worry about the unfamiliar Hello World Program in JRuby "java" stringHello= "Hello World" stringDate... Hello World Program in JRuby JRuby Introduction JRuby team developed JRuby, which JSP Hello World JSP Hello World We are going to discus about JSP hello world. In this example... instances. we can print simple "Hello World" String on web browser...;% JAVA CODE %> Example <%@ page language="java" contentType=" Displaying Hello using RMI Displaying Hello using RMI This Example describes the way to display Hello... technique for supporting distributed objects in java. The steps involved Java hello world Java hello world  ..., JavaBeans, Mobile Java. Genarally, Hello world program is the first step.../java/beginners/hello_world.shtml   Finding all palindrome prime numbers - Java Beginners Finding all palindrome prime numbers How do i write a program to Find all palindrome prime numbers between two integers supplied as input (start and end points are excluded Dojo Hello World Dojo Hello World In this tutorial, you will learn how to create a "Hello... be follow the its directory structure. Try Online: Hello World
http://roseindia.net/tutorialhelp/comment/14567
CC-MAIN-2013-48
refinedweb
1,306
57.57
Chapter 4 - The Basics Of Page Creation Curiously, the first tutorial that programmers follow when learning a new language or a framework is the one that displays "Hello, world!" on the screen. It is strange to think of the computer as something that can greet the whole world, since every attempt in the artificial intelligence field has so far resulted in poor conversational abilities. But symfony isn't dumber than any other program, and the proof is, you can create a page that says "Hello, <Your Name Here>" with it. This chapter will teach you how to create a module, which is a structural element that groups pages. You will also learn how to create a page, which is divided into an action and a template, because of the MVC pattern. Links and forms are the basic web interactions; you will see how to insert them in a template and handle them in an action. Creating a Module Skeleton As Chapter 2 explained, symfony groups pages into modules. Before creating a page, you need to create a module, which is initially an empty shell with a file structure that symfony can recognize. The symfony command line automates the creation of modules. You just need to call the tests, and you don't need to bother with it until Chapter 15. The actions.class.php (shown in Listing 4-1) forwards to the default module congratulation page. The templates/indexSuccess.php file is empty. Listing 4-1 - The Default Generated Action, in actions/actions.class.php <?php class mymoduleActions extends sfActions { public function executeIndex() { $this->forward('default', 'module'); } } note If you look at an actual actions.class.php file, you will find more than these few lines, including a lot of comments. This is because symfony recommends using PHP comments to document your project and prepares each class file to be compatible with the phpDocumentor tool (). For each new module, symfony creates a default index action. It is composed of an action method called executeIndex and a template file called indexSuccess.php. The meanings of the execute prefix and Success suffix will be explained in Chapters 6 and 7, respectively. In the meantime, you can consider that this naming is a convention. You can see the corresponding page (reproduced in Figure 4-1) by browsing to the following URL: The default index action will not be used in this chapter, so you can remove the executeIndex() method from the actions.class.php file, and delete the indexSuccess.php file from the templates/ directory. note Symfony offers other ways to initiate a module than the command line. One of them is to create the directories and files yourself. In many cases, actions and templates of a module are meant to manipulate data of a given table. As the necessary code to create, retrieve, update, and delete records from a table is often the same, symfony provides a mechanism.php Template <p>Hello, world!</p> If you need to execute some PHP code in the template, you should avoid using the usual PHP syntax, as shown in Listing 4-4. Instead, write your templates using the PHP alternative syntax, as shown in Listing 4-5, to keep the code understandable for non-PHP programmers. Not only will the final code be correctly indented, but it will also help you keep the complex PHP code in the action, because only control statements ( if, foreach, while, and so on) have an alternative syntax. Listing 4-4 - The Usual PHP Syntax, Good for Actions, But Bad for Templates <p>Hello, world!</p> <?php if ($test) { echo "<p>".time()."</p>"; } ?> Listing 4-5 - The Alternative PHP Syntax, Good for Templates <p>Hello, world!</p> <?php if ($test): ?> <p><?php echo time(); ?></p> <?php endif; ?> The job of the action is to do all the complicated calculation, data retrieval, and tests, and to set variables for the template to be echoed or tested. Symfony makes the attributes of the action class (accessed via $this->variableName in the action) directly accessible to the template in the global namespace (via $variableName). Listings 4-6 and 4-7 show how to pass information from the action to the template. Listing 4-6 - Setting an Action Attribute in the Action to Make It Available to the Template <?php class> Note that the use of the short opening tags ( <?=, equivalent to <?php echo) is not recommended for professional web applications, since your production web server may be able to understand more than one scripting language and consequently get confused. Besides, the short opening tags do not work with the default PHP configuration and need server tweaking to be activated. Ultimately, when you have to deal with XML and validation, it falls short because <??name=anonymous', 'class=special_link confirm=Are you sure? absolute=true') ?> // Both calls output the same => <a class="special_link" onclick="return confirm('Are you sure?');" href=""> I never say my name</a> Whenever you use a symfony helper that outputs an HTML tag, you can insert additional tag attributes (like the class attribute in the example in Listing 4-12) instead? Because then your URLs will be formatted differently (as in, without ? nor =), the usual PHP variables won't work anymore, and only the routing system will be able to retrieve the request parameters. And you may want to add input filtering to prevent malicious code injection, which is only possible if you keep all request parameters in one clean parameter holder. The $sf_params object is more powerful than just giving a getter equivalent to an array. For instance, if you only want to test the existence of a request parameter, you can simply use the $sf_params->has() method instead of testing the actual value with get(), as in Listing 4-15. Listing 4-15 - Testing the Existence of a Request Parameter in the Template <?php if ($sf_params->has('name')): ?> <p>Hello, <?php echo $sf_params->get('name') ?>!</p> <?php else: ?> <p>Hello, John Doe!</p> <?php endif; ?> You may have already guessed that this can be written in a single line. As with most getter methods in symfony, both the getRequestParameter() method in the action and the $sf_params->get() method in the template (which, as a matter of fact, calls the same method on the same object) accept a second argument: the default value to be used if the request parameter is not present. <p>Hello, <?php echo $sf_params->get('name', 'John Doe') ?>!</p> Summary In symfony, pages are composed of an action (a method in the actions/actions.class.php file prefixed with execute) and a template (a file in the templates/ directory, usually ending with Success.php). They are grouped in modules, according to their function in the application. Writing templates is facilitated by helpers, which are functions provided by symfony that return HTML code. And you need to think of the URL as a part of the response, which can be formatted as needed, so you should refrain from using any direct reference to the URL in action naming or request parameter retrieval. Once you know these basic principles, you can already write a whole web application with symfony. But it would take you way too long, since almost every task you will have to achieve during the course of the application development is facilitated one way or another by some symfony feature . . . which is why the book doesn't stop now.
https://symfony.com/legacy/doc/book/1_0/ar/04-The-Basics-of-Page-Creation
CC-MAIN-2021-10
refinedweb
1,234
62.58
Seems my mail setup is broken. sending this the third time to the list... -------------------------------------------- Hi all, Nathan C Summers <[EMAIL PROTECTED]> writes: > On 21 Feb 2001, Sven Neumann wrote: > > Nathan C Summers <[EMAIL PROTECTED]> writes: > > > > > Problem: Many tools instruct the core to destroy themselves on certain > > > kinds of state changes, such as a change of image or display. While some > > > tools are quite good at handling these changes, others are quite unstable > > > psychologically and commit hara-kari for the smallest reasons. > > > > This problem should go away as soon as all tools are proper objects > > with init and finalize functions, destroy signals etc. > > That lessens but does not solve the problem that the code is more > complicated because of the destruction of tools due to state changes. I'm quite a bit biassed about wether we should destroy tools after use or not, but IMHO a tool should simply be able to handle both. Of course it has to handle it's destruction :) and being able to change displays will enable features we may not think of currently. Also, there would be no need to decide now if we want to destroy the tools or not. > > IMO the GimpToolInfo object Mitch just introduced to resurrect the tool > > system is the right way to go. GimpToolInfo objects stay around so Gimp > > knows what tools are available, can display icons, etc., the real GimpTool > > only exists when needed. > > I really like what Mitch has done with the tool code. He read my mind > when it came to renaming the gimp_tool_emit_* functions to more standard > names. The GimpToolInfo objects are elegant. > > Mitch: if you haven't yet written the code to get rid of the items marked > as needing to go away in the GimpTool class structure, let me know so > that I can write it and you can spend your time on less trivial code. Yeah, I went through the code when I re-integrated the tool stuff with the context and could not resist to apply some coding style paranoia. Most of the fields are already removed, I suggest to leave the remaining two (pdb string and cursors) there until there are some more tools back. The pdb_string could become a virtual function which returns the string, I'll care about making something real out of the cursor code when there are some more tools. > I also wonder what happened to standard_control_func. I know it was > misnamed, but it contained code that all of the current tools use and was > fit for inheritance. In general, it should be ran before the tool's > specialized control code. The function is now in the context manager because it's a wrapper around the active tool's "control" method. > > > Problem: Some tools, such as iscissors, keep around a lot of cached data > > > generated from the image they are attached to. Changing the image they > > > are working on clears this cache. This can be slow when working on > > > multiple images or layers. <discussion snipped> Hm, I'd rather vote for making the tool system stable again with all tools in their proper places in the tool hierarchy before we start adding fancy stuff like caches. And BTW, GLib already provides a cache mechanism which produces the requested data on the fly. > It is. I just think of the Gimp part as a namespace. Besides, after > typing GimpPaintingTool way too many times (yes, I found the macro command > in my editor...) I'm kind of sick of typing that big, long name. ;) > > (btw, why the "ing" ??). > > Because I figured that people would confuse GimpPaintTool with the > paintbrush. Please make it GimpPaintTool, you just talked about long names above :) > > If I remember correctly, the > > DrawCore is that ugly thing we use to draw on the display, so it should > > probably totally go away and be implemented on top of the yet to be written > > GimpDisplay. > > There isn't much code to it. But it will have to stay until GimpDisplay > gets written, as you can't meaningfully write code for an API that doesn't > exist. ;) Yeah, i guess we should put that to a separate tool so we can easily change it once there is a real GimpDisplay. > OK, here is the class hierarchy (some tools have been left out for > brevity) > > GtkObject > | > GimpObject > | > GimpTool > | \ > | GimpTextTool > | \ > | GimpDynamicTextTool? > | > GimpDrawingTool > | | \ > | | GimpColorPicker > | | > | GimpPaintingTool > | \ > | GimpPaintbrush > | > GimpTransformingTool > | | > GimpRotate GimpPerspective Well, I guess we should rather save some "ing" and add "Tool" all over the place to get a consistent namespace: GtkObject | GimpObject | GimpTool | \ | GimpTextTool | \ | GimpDynamicTextTool? | GimpDrawTool | | \ | | GimpColorPickerTool | | | GimpPaintTool | \ | GimpPaintbrushTool | GimpTransformTool | | GimpRotateTool GimpPerspectiveTool Also, the policy is to name files exactly as the objects they contain, e.g. gimptool.[ch], gimpcolorpickertool.[ch]. This may look a bit overly picky but a consistent file namespace is important in such a large codebase. > I'd like all the tools that don't take a specific point as input to be > turned into something else. My definition of a tool is something that you > click on the image with. They should also use the image view directly (as > should plugins). > > For example, by color select would count as a tool, but > contrast/brightness wouldn't. Of course the brightness/contrast stuff should be a tool, derived from GimpColorMapTool, how else do you want to get the display events there? > It will take some effort to do, of course, but it's worth it in simplicity > and user understanding. (Why do some things that work like filters not > respond to repeat last filter?, etc.) The "repeat last filter" stuff is just a bad hack due to the fact that not all gimp operations go through the PDB and can thus be repeated. While browsing through the code with this fact in mind i noticed that it cannot be _that_ hard to achieve this goal: once all main objects we can perform operations on (image, drawable, ...) are proper objects and live in their subdirs, we can redirect most commands.c callbacks and most stuff tools do to e.g. app/drawable/gimpdrawable-commands.[ch] where the respective PDB functions will be called. Looks like a bit of work, but if we want to hack GIMP 1.4's interface in a way that we can use it for 2.0, the way to go is to separate it cleanly from the core. ciao, --Mitch _______________________________________________ Gimp-developer mailing list [EMAIL PROTECTED] [Michael Natterer ] Re: [Gimp-developer] Re: RFC: eliminating tool destruction and adding better caching support Michael Natterer Sat, 24 Feb 2001 19:53:17 -0800 - [Gimp-developer] List config (was Re:... Michael Natterer - [Gimp-developer] List config (wa... Guillermo S. Romero / Familia Romero - [Michael Natterer <mitch@gimp... Michael Natterer
https://www.mail-archive.com/gimp-developer@lists.xcf.berkeley.edu/msg00069.html
CC-MAIN-2017-17
refinedweb
1,112
69.92
#include <nrt/Core/Typing/Exception.H> Exception base class for NRT. This is essentially the same as std::exception but in the nrt namespace. It is tricky to ensure that constructor, destructor, and what() functions of derived exceptions won't throw. The recommended definition of a derived exception is as follows: If you want a more complicated initializer list, then use this fancy syntax for your constructor: See here for more info: Definition at line 121 of file Exception.H. Constructor with a given error message. The message is given as an old-school C string to ensure that the exception constructor won't throw. In the constructor we just set whatptr to that C string. Typically that string would be a plain string message in your code (i.e., not dynamically allocated, temporary object, etc). Return a C string describing the error. In derived classes, do not overload what(), but instead just set whatptr to point to your error message. Referenced by nrt::ParameterCore< T >::set().
http://nrtkit.net/documentation/classnrt_1_1exception_1_1Exception.html
CC-MAIN-2020-10
refinedweb
167
58.28
TypeError: 'module' object is not callable Hi everybody I am new here to use the deep sleep shield. I add the deepsleep.py in the library and sync the project. I don't know if it's right and I am very confused this process: You can see the deepsleep.py file is in the left side of my screenshots. The problem is always: TypeError: 'module' object is not callable! import pycom import time from machine import Pin, Timer from deepsleep import DeepSleep echo = Pin(Pin.exp_board.G7, mode=Pin.IN) trigger = Pin(Pin.exp_board.G8, mode=Pin.OUT) # Colors different color stand for different state off = 0x000000 red = 0xff0000 green = 0x00ff00 blue = 0x0000ff # Turn off hearbeat LED pycom.heartbeat(False) #enable the deepsleep ds = DeepSleep() trigger(0) chrono = Timer.Chrono() while True: ds.go_to_sleep(60) # go to sleep for 60 seconds print("Wake up") chrono.reset() trigger(1) time.sleep_us(10) trigger(0) while echo() == 0: pass chrono.start() while echo() == 1: pass chrono.stop() distance = chrono.read_us() / 58.0 if distance > 400: print("Out of range") else: print("Distance {:.0f} cm".format(distance)) time.sleep(1) - cronywalls last edited by import : from MyClass import MyClass In Python , a script is a module, whose name is determined by the filename . So when you start out your file MyClass.py with import MyClass you are creating a loop in the module structure. In Python, everything (including functions, methods, modules, classes etc.) is an object , and methods are just attributes like every others. So,there's no separate namespaces for methods. So when you set an instance attribute, it shadows the class attribute by the same name. The obvious solution is to give attributes different names. @jcaron Thank you. I tried but still like this, I don't know why it's so complicated. I run the deepsleep.py and there is no action in the console, if the deepsleep code is right. I downloaded from there. Would it be because you have the directory as /Lib instead of /lib (i.e. try using lowercase). The errors do not seem to be very consistent. Note that Pymakr uploads files it knows about but it can leave odd stuff on the module's filesystem. I recommend you either use FTP to check that you only have the files required, or clear the flash and then re-upload with Pymakr, it should help. Also, don't add all those other files in lib, you'll end up with issues. @rachelsimida if you type in the REPL prompt: from deepsleep import DeepSleep dir (DeepSleep) What do you get as output? I believe you should have deepsleep.py directly in the lib folder, not a subfolder. This is my device.
https://forum.pycom.io/topic/2941/typeerror-module-object-is-not-callable/10
CC-MAIN-2019-13
refinedweb
455
78.04
Extension Problem I attempted to create a bootstrap extension for Robotlegs 2 to be used in my applications. I looked at the SignalCommandMap extension as an example and implemented similarly. This is the extension file: public class BootstrapExtension implements IExtension { /*============================================================================*/ /* Private Properties */ /*============================================================================*/ private const _uid:String = UID.create(BootstrapExtension); /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function extend(context:IContext):void { context.injector.map(IBootstrap).toSingleton(Bootstrap); } public function toString():String { return _uid; } } Here is the some of the Bootstrap class: public class Bootstrap implements IBootstrap { /*============================================================================*/ /* Private Properties */ /*============================================================================*/ private var _injector:Injector; private var _signalCommandMap:ISignalCommandMap; /*============================================================================*/ /* Constructor */ /*============================================================================*/ public function Bootstrap( injector:Injector, signalCommandMap:ISignalCommandMap ) { _injector = injector; _signalCommandMap = signalCommandMap; } . . . } My question is: as far as I understand, swiftsuspenders will inject the parameters of the constructor for the Bootstrap class. This is the way it is defined also in other extensions. However, this doesn't happen all the time for this extension. I mean that sometimes the Injector is mapped successfully... and other times it is not and I get simply NULL. Is there something wrong with my implementation to this extension? Thanks MBarjawi Comments are currently closed for this discussion. You can start a new one. Keyboard shortcuts Generic Comment Form You can use Command ⌘ instead of Control ^ on Mac Support Staff 1 Posted by creynders on 04 Apr, 2013 01:38 PM You mean an error is thrown that no mapping is found for type Injector? Or..? How do you verify that _injector is null? trace? breakpoint? In the constructor? 2 Posted by mbarjawi on 04 Apr, 2013 03:17 PM Thank you for your reply. No error is thrown from robotlegs which I think is strange. Mainly, it happens that when I am in debug mode and have a break point inside the constructor, I can see that the injector is null. When I run without breakpoints and without debugging, it runs normally... but not all the times. Only few times it will give a null object error (because I am using the injector later on in my class). Similarly, only few times while in debug mode, the injector will come in normally. Support Staff 3 Posted by Ondina D.F. on 04 Apr, 2013 03:22 PM Hi guys, I tried MBarjawi’s example with Swiftsuspenders-v2.0.0rc2.swc and it looks like the signalCommandMap has ‘eaten’ the injector :P. Without signalCommandMap the injector gets injected just fine. But with contructor injections for both, injector and signalCommandMap, the injector is null inside Bootstrap. In fact, it affects not only the injector, but any other dependencies provided as ctor injections. I think that behavior has to do with this bug: which has been fixed in the latest version ( only source code) Workaround for the version with bugs: Map and instantiate signalCommandMap in BootstrapExtension, Or by using Or install SignalCommandMapExtension too, and instantiate signalCommandMap in your config. [EDIT] Or just inject them instead of constructor injection in Bootstrap. Of course, they won’t be available inside the constructor, in this case. @MBarjawi could you try the newest version of swiftsuspenders(source code :) and tell us if that fixes your problem? Ondina 4 Posted by mbarjawi on 04 Apr, 2013 04:46 PM I just tested using the latest version of swiftsuspenders... the problem disappeared :) Thanks so much, mbarjawi closed this discussion on 04 Apr, 2013 04:47 PM.
http://robotlegs.tenderapp.com/discussions/robotlegs-2/1319-extension-problem
CC-MAIN-2019-13
refinedweb
555
56.25
# Auto-generated file -- DO NOT EDIT!!!!! =head1 NAME KinoSearch::Index::Segment - Warehouse for information about one segment of an inverted index. =head1 DEPRECATED The KinoSearch code base has been assimilated by the Apache L<Lucy> project. The "KinoSearch" namespace has been deprecated, but development continues under our new name at our new home: L<> =head1 SYNOPSIS #; } =head1 DESCRIPTION, C<< segmeta.json >>; besides storing info needed by Segment itself, the "segmeta" file serves as a central repository for metadata generated by other index components -- relieving them of the burden of storing metadata themselves. =head1 METHODS =head2 add_field(field) Register a new field and assign it a field number. If the field was already known, nothing happens. =over =item * B<field> - Field name. =back Returns: the field's field number, which is a positive integer. =head2 store_metadata( I<[labeled params]> ) Store arbitrary information in the segment's metadata Hash, to be serialized later. Throws an error if C<< key >> is used twice. =over =item * B<key> - String identifying an index component. =item * B<metadata> - JSON-izable data structure. =back =head2 fetch_metadata(key) Fetch a value from the Segment's metadata hash. =head2 field_num(field) Given a field name, return its field number for this segment (which may differ from its number in other segments). Return 0 (an invalid field number) if the field name can't be found. =over =item * B<field> - Field name. =back =head2 field_name(field_num) Given a field number, return the name of its field, or undef if the field name can't be found. =head2 get_name() Getter for the object's seg name. =head2 get_number() Getter for the segment number. =head2 set_count(count) Setter for the object's document count. =head2 get_count() Getter for the object's document count. =head1 INHERITANCE KinoSearch::Index::Segment isa L<KinoSearch::Object::Obj>. =head1 COPYRIGHT AND LICENSE Copyright 2005-2011 Marvin Humphrey This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
https://web-stage.metacpan.org/dist/KinoSearch/source/lib/KinoSearch/Index/Segment.pod
CC-MAIN-2022-33
refinedweb
331
58.79
React is a client side JavaScript framework built by Facebook for Facebook .React is open source and hosted on GitHub.It is presented by Facebook as the V in MVC which means it is the View but in reality it is the whole MVC and you are going to realize that when you start working with this great framework. By learning React you can build modern JavaScript applications which have nothing to envy from existing apps.React is simple and readable with great features such as : Virtual DOM Data binding Reusable components Separation of concerns etc.. Throughout this article i'm going to show how you can develop rich text editors for your web applications or websites with React and another open source framework,also built by Facebook developers ,for building rich text editors called Draft.js Draft.js offers you a complete framework for building rich text editors and abstracts away cross browser differences so you can focus on building your rich text editor instead of worrying about browsers features support ,in addition Draft.js is built in React so you can take advantage of all features React has. You can build any type of rich text editors from dead simple to complex text editors . Installation You can easily install Draft.js via npm .Don't forget to install React and React DOM the only two dependencies of Draft.js : npm i --save draft-js react react-dom Now you can use it import React from 'react'; import ReactDOM from 'react-dom'; import {Editor, EditorState} from 'draft-js'; class MyEditor extends React.Component { constructor(props) { super(props); this.state = {editorState: EditorState.createEmpty()}; this.onChange = (editorState) => this.setState({editorState}); } render() { const {editorState} = this.state; return ReactDOM.render( React Router DOM v4 Tutorial (with Examples) Building Universal Server Rendered Apps with React and Next.js 3.0 Building Web Apps with Django ,Webpack and React Building Apps with Create React App and Django
https://www.techiediaries.com/building-rich-text-editors-with-javascript-and-react/
CC-MAIN-2017-43
refinedweb
322
56.45
calling data in int() by name / dataname data by name. referencing data by _name when adding data I do have the attribute namein this example well say name = SWKwith in the bt.feeds.GenericCSVData() Now with in def __init__(self):I am trying to call the data by name and can not seem to get it... IE self.data_SWK.closedoes not work... self.datas_SWK.closedoes not work either. referencing source data_NAME line 109 ` - self.dataX_name-> self.datas[X].name. But this is for an analyzer, maybe its not possible any other place. Maybe I am miss interpreting the documents. - backtrader administrators last edited by Yes you are misinterpreting the docs. Which means that they probably unclear. What you can reach is the name of the defined lines. A typical OHLCwill have an attribute named: self.lines.close which can be accessed as: self.close In a Strategyor Analyzeryou can reach the same as: self.dataX_close The potential benefits (which may not fit your purpose, goal) - Less typing - Save some Python lookup cycles (one dictaccess versus three) Many will consider that a classical dot-based notation is clearer self.dataX.close(and even the actual complete path self.dataX.lines.close) @backtrader ok, that is more clear. is there any where to get an list of all datas available ? The issue that arrises for my use-case is that if you are loading in 100 data feeds into a master strategy, how to know if self.data23.closeis symbol X or Y to pass it along to the sub-strategy class. potential solution could be just as simple as passing the symbol list as a param and then running something like ["foo", "bar", "baz"].index("bar")i suppose. assume backtrader loads the data in sequential order every time from the list of symbols . if not I believe I found a work around, by passing up through params the len()of data feeds added (IE how many) and then doing the following in int() datas_dic = {} for num in range(0,self.p.total_feeds): sym_name = self.datas[num]._name if not sym_name in datas_dic: datas_dic[sym_name] = ('self.datas%s' % num) returns a list looking similar to : {'WASH': 'self.datas2', 'ACN': 'self.datas1', 'SWK': 'self.datas0', 'WSBC': 'self.datas3'} FOR CONTEXT: this is needed because i am creating a large portfolio of pairs. I have a single master strategy that then creates sub strategies and I need to create a new sub strategy for every pair, and to create that sub strategy I need to know which datas it needs to run its calculations.
https://community.backtrader.com/topic/1080/calling-data-in-int-by-name-dataname/2
CC-MAIN-2022-27
refinedweb
430
67.35
Created on 2006-05-10 13:28 by hinsen, last changed 2010-08-09 16:37 by pitrou. This issue is now closed. PEP353 recommends to add the following code snippet to extension modules to ensure compatibility with pre-2.5 interpreters: #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #endif This is insufficient, because type definitions that use Py_ssize_t must also be added. Here is what works for me, though they may be more definitions to be included: #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN typedef Py_ssize_t (*lenfunc)(PyObject *); typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t); typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t); typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *); typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *); **); #endif However, the main problem is elsewhere. Extension modules may well need to use Py_ssize_t in their own data types, and may furthermore with to make these data types available to yet other extension modules. In practice, this requires the inclusion of a code block such as the one shown above inside header files. However, this requires a mechanism for avoiding redefinitions, which at the moment does not seem to exist. My request is to add such a mechanism to Python 2.5 and recommend its consistent use in an update of PEP353. Concretely, I propose that Python 2.5 should define a macro PY_HAS_PY_SSIZE_T, and that PEP353 should recommend the inclusion of the code snippet #ifndef PY_HAS_PY_SSIZE_T #define PY_HAS_PY_SSIZE_T typedef int Py_ssize_t; /* add all the other definitions here */ #endif that contains an exhaustive set of definitions that depend on Py_ssize_t. Logged In: YES user_id=21627 Please re-read the section immediately following the #ifdef code in PEP 353. It explains how you should avoid these other typedefs. Logged In: YES user_id=11850 I have read that section, but I am not yet convinced that I can avoid those casts with all common C compilers - and since I cannot try them all, I'd rather play safe and keep the casts. If they were never necessary, why were those typedefs introduced at all? Anyway, it is not the additional typedefs that are the essence of my feature request. The main issue is that if multiple header files introduce Py_ssize_t, the compiler will stop with an error message. Logged In: YES user_id=11850 Here is an illustration of my problem. Given the following three files: -- foo.h ------------------------- #include <Python.h> #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #endif typedef struct { Py_ssize_t index; } foo; -- bar.h ------------------------- #include <Python.h> #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #endif typedef struct { Py_ssize_t index; } bar; -- foobar.c ---------------------- #include "foo.h" #include "bar.h" foo a; bar b; int main(int argc, char **argv) { return 0; } ---------------------------------- I get from gcc: gcc foobar.c In file included from foobar.c:1: foo.h:1:20: error: Python.h: No such file or directory In file included from foobar.c:2: bar.h:4: error: redefinition of typedef 'Py_ssize_t' foo.h:4: error: previous declaration of 'Py_ssize_t' was here I see no solution to this problem that would work in the most general case in which all three files are part of different packages written by different authors, i.e. in the absence of a coordination. Logged In: YES user_id=11850 Oops, I forgot the -I option, but that doesn't really make a difference. For Python 2.5: gcc -I /usr/local/include/python2.5 foobar.c --> no error message For Python 2.4: gcc -I /Library/Frameworks/Python.framework/Versions/2.4/include/ python2.4 foobar.c In file included from /Library/Frameworks/Python.framework/Versions/2.4/ include/python2.4/Python.h:55, from foo.h:1, from foobar.c:1: /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/ pyport.h:396: warning: 'struct winsize' declared inside parameter list /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/ pyport.h:397: warning: 'struct winsize' declared inside parameter list In file included from foobar.c:2: bar.h:4: error: redefinition of typedef 'Py_ssize_t' foo.h:4: error: previous declaration of 'Py_ssize_t' was here Logged In: YES user_id=21627 I understand your request, and I sympathize with it (although I would call the macro Py_ssize_t_defined). However, I find it equally important that the other issue gets understood, as well. The macros are not necessary for portable code, and they never were. They were introduced for convenience only, so that you can have the actual type name for the self parameter (e.g. FooObject* instead of PyObject*). If the signatures are corrected to have PyObject* as their first parameter, the casts *should* become unnecessary. If they are then still required, that indicates a serious programming error. The evilness of these casts comes from the fact that they can silence warnings that would point to severe type errors if the cast wouldn't silence them. For example, if the parameter order or the number is wrong for one of these functions, the compiler won't notice because of the cast. The cast is only there to convert the first parameter (self), yet it can manage to convert any other parameter, as well. So getting these function pointers type correct not only increases portabiltiy in the presence of Py_ssize_t, but also improves correctness and readability of the code. This request, however legitimate, is completely outdated.
https://bugs.python.org/issue1485576
CC-MAIN-2021-49
refinedweb
890
57.37
DataGrid DataTipFunctionBrent Wientjes Mar 25, 2008 5:18 PM I am trying to have a varying datafield as a datatip source (unique field for each column). I see the Adobe examples but they all assume a single datatip source. An example would be a spreadsheet with additional information per cell. I wish to have a custom datatip appearance and place additional information elsewhere on the web page. I do not see a way to tell the function - return item.datatipfield; where datatipfield is defined by each datagridcolumn. Any help would be greatly appreciated. This content has been marked as final. Show 8 replies 1. Re: DataGrid DataTipFunctionriesvantwisk Mar 25, 2008 7:20 PM (in response to Brent Wientjes)properly you need to create a custom renderer and in that custom renderer decide what tooltip to show. Ries 2. DataGrid DataTipFunctionSreenivas R Mar 25, 2008 9:52 PM (in response to Brent Wientjes)DataGridColumn has dataTipField and dataTipFunction properties. Have you tried using them? 3. Re: DataGrid DataTipFunctionBrent Wientjes Mar 26, 2008 11:14 PM (in response to Sreenivas R)Yes, I am trying to write a custom datatip function. The part that I can not figure out is how to allow a general purpose renderer pick the appropriate fields. None of the examples I have seen have been generic. They all know there is only 1 field of interest in the grid and uniquely identifiy it in the routine. I would like to know how to select the field assigned to each column of the grid and then apply the logic to it. This does not work but something like label.text = data{field} is the type of thing I believe it wants but this is not the correct way of expressing it. Any simple code examples would be great! Tks, Brent 4. Re: DataGrid DataTipFunctionSreenivas R Mar 27, 2008 3:46 AM (in response to Brent Wientjes)Here is a sample. Let me know whether it fits your purpose or you were looking for something else. <mx:Script> <![CDATA[ private var inputData:Array = [ { name:"Sreenivas", nameComment:"Sreenivas Ramaswamy", email:"gmail", emailComment:"sreenivas.ramaswamy@gmail.com"}, { name:"Sameer", nameComment:"Sameer Bhat", email:"gmail", emailComment:"prosameer@gmail.com"}, { name:"Satish", nameComment:"Satish TJ", email:"gmail", emailComment:""} ]; ]]> </mx:Script> <mx:DataGrid <mx:columns> <mx:DataGridColumn <mx:DataGridColumn </mx:columns> </mx:DataGrid> 5. Re: DataGrid DataTipFunctionBrent Wientjes Mar 27, 2008 5:22 PM (in response to Sreenivas R)Thanks for the reply and help Sreenlvas. Your example is excellent for the default case of datatip usage. My wishes are a little more complex. The application example would be to have several datagridcolumns, each with a unique dataprovider data and datatip field. The customization would to be appraise the value of the datatip value and change the appearance or information to the user. A simple example of this would be the datagrid was the days of the week with the datatip being the total number of sales (or something) that day. If the number of sales exceeds some number - say 5, we add some additonal information - like a good job! symbol. Each day in the grid will have different values for the data and datatip fields. I would like to make 1 datatipfunction that is independent of the data field assigned to the column. A simple code example (does not work and I have smplified the syntax to show the point) dataDP = [df1: 11,dt1: a1,df2: 12,dt2: a2,df3: 13,dt3: a3] [df1: 21,dt1: b1,df2: 22,dt2: b2,df3: 23,dt3: b3] [df1: 31,dt1: c1,df2: 32,dt2: b2,df3: 33,dt3: c3] private function custom(o:Object):String {var extra:String = o.dataTipField == b2 ? " Good Job": " Ok"; return o.dataTipField + extra; } <mx:DataGrid <mx:columns> <mx:DataGridColumn dataField="df1" showDataTips="true" dataTipField="dt1"dataTipFunction="custom"//> <mx:DataGridColumn <mx:DataGridColumn </mx:columns> </mx:DataGrid> If the syntax were correct, the above would fail because the array field "dataTipField" does not exist in the object passed to the function "custom". If the function received a DataGridColumn object then I could write o[dataTipFunction] in place of the o.dataTipFunction and the routine would work. I have tried many variations but it seems the dataTipFunction wants a standard Object sent to it - not the DataGridColumn info. So what I am looking for is something that tells the function "custom" the dataprovider column assigned to that specific column. That would allow a single routine which could be applied to all the datagridcolumns. I can make what I want if I make a unique dataTipFunction for each column but in my real life example that means 10 different versions of the same "custom" function. The only difference in each one, is I call out the array field assigned to that specific column. That seems inefficient versus a single routine that can detect the array field assigned to it generically. 6. Re: DataGrid DataTipFunctionSreenivas R Mar 27, 2008 11:02 PM (in response to Brent Wientjes)Here is a customized sample. Hope this suits your requirement. The idea is to use a custom DataGridColumn. <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns: <mx:Script> <![CDATA[ import mx.controls.dataGridClasses.DataGridColumn; private var inputData:Array = [ { name:"Sreenivas", nameComment:"Sreenivas Ramaswamy", email:"gmail", emailComment:"sreenivas.ramaswamy@gmail.com"}, { name:"Sameer", nameComment:"Sameer Bhat", email:"yahoo", emailComment:"prosameer@gmail.com"}, { name:"Satish", nameComment:"Satish TJ", email:"gmail", emailComment:""} ]; private function mySingleCustomFunction(item:Object, column:DataGridColumn):String { var label:String = item[column.dataField]; var tip:String = item[column.dataTipField]; if (label.indexOf("Sree") != -1 ) tip += " , my name !"; if (label == "gmail" && tip.length) tip += " , GMAIL is good!"; return tip; } ]]> </mx:Script> <mx:DataGrid <mx:columns> <local:CustomDataGridColumn <local:CustomDataGridColumn </mx:columns> </mx:DataGrid> </mx:Application> //CustomDataGridColumn package { import mx.controls.dataGridClasses.DataGridColumn; public class CustomDataGridColumn extends DataGridColumn { public var myDataTipFunction:Function; public function CustomDataGridColumn(columnName:String=null) { super(columnName); } override public function itemToDataTip(data:Object):String { if (myDataTipFunction) { return myDataTipFunction(data, this); } return super.itemToDataTip(data); } } } 7. Re: DataGrid DataTipFunctionBrent Wientjes Mar 28, 2008 10:18 PM (in response to Sreenivas R)Thanks Sreenlvas for the support. I just spent the last hour typing in a solution I found yesterday. It uses the listData property cast to DataGridListData. I previewed, did a small edit and then hit Reply. This system was kind enough to kick me off and loose all the work. I'll try again tomorrow to show you the solution that was suggested as an alternative and what the overall datagrid can do. Brent 8. Re: DataGrid DataTipFunctionBrent Wientjes Mar 29, 2008 12:29 PM (in response to Brent Wientjes)Last night I tried to send the follow but as mentioned when I hit the reply button to post, the system logged me off and lost all the work. I guess it times out a user. Anyway, here's what I found about the same time you posted your suggested solution. The "secret sauce" that I found was from a liveDoc page labeled "accessing the listData property". It gave me the hint I needed. The essense of the "secret sauce" is to use a component that implements the IDropInListItemRenderer interface (label, text, textinput, textarea, etc.). You use the listData property and for a DataGrid cast it to DataGridListData property that gives you col, row, dataField and the rest of the object. You then write a listener for "change data" to manipulate everything. The actual application I am building uses a grid to show daily information. The information is a number with augmenting notes about the number. You may have an arbitrary quantity of notes for each number logged. You also edit the number through the grid and you create/edit notes about the number through the grid cell. Thus, I need the ability to view a matrix of data, edit that data, supplement the individual data entries with notes, view where those notes are in the matrix and get a quick indication of how many notes are present. This meant that each cell needed all the information about the number, location of the grid cell and how to affect the grid cell appearance. The solution requires custom label, renderer, editor, tooltip functions. The following is a stripped down version of the code that I got working for the above functionality. As before I have stripped part of the syntax to bring out the idea without cluttering things and w/o the editing/note portion. ds: data source --------------- [sun: 0,mon: 1,tue: 2,wed: 3,thu: 4,fri: 5,sat: 6, notectsun: 100,notectmon: 101,notecttue: 102,notectwed: 103,notectthu: 104,notectfri: 105,notectsat: 106], [sun: 7,mon: 8,tue: 9,wed: 10,thu: 11,fri: 12,sat: 13, notectsun: 107,notectmon: 108,notecttue: 109,notectwed: 110,notectthu: 111,notectfri: 112,notectsat: 113], [sun: 14,mon: 15,tue: 16,wed: 17,thu: 18,fri: 19,sat: 20, notectsun: 114,notectmon: 115,notecttue: 116,notectwed: 117,notectthu: 118,notectfri: 119,notectsat: 120] css: style sheet ------------- .noteData{color: #2222ff; font-size: 14; font-weight: bold; font-style: italic;} .noNoteData{color: #000000; font-size: 14;} custom: item renderer --------- <?xml version="1.0" encoding="utf-8"?> <mx:Label xmlns: <mx:Script><![CDATA[ import mx.controls.dataGridClasses.DataGridListData; private var colField:Array = ["sun","mon","tue","wed","thu","fri","sat"]; // <== data field pointers public function init():void {addEventListener("dataChange", handleDataChanged);} public function handleDataChanged(event:Event):void {var myListData:DataGridListData = DataGridListData(listData); // <== secret sauce var f:String = "notect" + colField[myListData.columnIndex]; var note:String = data[f] > 1 ? " notes": " note"; styleName = data[f] > 0 ? "noteData": "noNoteData"; toolTip = data[f] > 0 ? String(data[f]) + note: ""; // <== custom tooltip } ]]></mx:Script></mx:Label> main application -------------- (ActionScript ----------------) private function dfEntry(o:Object,data:DataGridColumn):String // <== custom label to format {return dfFormat.format(o[data.dataField]);} (MXML ------------------------) :NumberFormatter The above works pretty much like I envisioned with the exception of how to access number versus note editing access. I still have not figured out how to gain keyboard information when accessing grid cell data. I have an external checkbox to put the matirix into either number mode or note mode. It works ok but the ideal solution would be to have ctrl, shift or alt depressed and then click on a cell to change modes. The current user experience seems ok so maybe someday I'll figure that out. Thanks again, ... for the support. Hopefully, someone in the future that may read the above set of posts will can gain ideas and solve their design concerns. Best wishes, Brent
https://forums.adobe.com/thread/257332
CC-MAIN-2017-30
refinedweb
1,751
56.35
ost::Process - A class for containing portable process related functions that help create portable code. #include <process.h> Public Types typedef void(* Trap )(int) Public Member Functions bool lock (bool future=true) Lock a process in memory. void unlock (void) Unlock process pages. Static Public Member Functions static void detach (void) Detach current process into a daemon, posix only. static void attach (const char *devname) Attach the current process to another device or i/o session. static Trap setPosixSignal (int signo, Trap handler) Set a posix compliant signal handler. static Trap setInterruptSignal (int signo, Trap handler) Set system call interuptable signal handler. static int spawn (const char *exec, const char **argv, bool wait=true) Spawn a process and wait for its exit code. static int join (int pid) Get the exit status of another process, waiting for it to exit. static bool cancel (int pid, int sig=0) Cancel a running child process. static const char * getEnv (const char *name) Get system environment. static void setEnv (const char *name, const char *value, bool overwrite) Set system environment in a standard manner. static const char * getConfigDir (void) Get etc prefix path. static const char * getHomeDir (void) Get home directory. static const char * getUser (void) Get user name. static bool setUser (const char *id, bool grp=true) Set user id by name. static bool setGroup (const char *id) Set the effective group id by name. static size_t getPageSize (void) Return the effective operating system page size. static void setPriority (int pri) Used to set process priority and optionally enable realtime. static void setScheduler (const char *policy) Used to set process scheduling policy. static void setRealtime (int pri=0) Portable shortcut for setting realtime. static bool isScheduler (void) Return true if scheduler settable. static bool isRealtime (void) Return true if realtime scheduling. A class for containing portable process related functions that help create portable code. These are typically referenced thru Process::xxx static member functions. Many of these members are used both for win32 and posix systems although some may be platform specific. Peocess wrapper class. Author: David Sugar <dyfet@ostel.com> typedef void(* ost::Process::Trap)(int) static void ost::Process::attach (const char * devname) [static] Attach the current process to another device or i/o session. It is deamonified and dissasociated with the prior parent process and controlling terminal. Parameters: devname path to attach to. static bool ost::Process::cancel (int pid, int sig = 0) [static] Cancel a running child process. Returns: 0 on success. Parameters: pid process id. sig cancel signal to apply. static void ost::Process::detach (void) [static] Detach current process into a daemon, posix only. Perhaps a similar method can be used for creating win32 ’services’? static const char* ost::Process::getConfigDir (void) [static] Get etc prefix path. Returns: etc prefix. static const char* ost::Process::getEnv (const char * name) [static] Get system environment. Returns: system environ symbol. Parameters: name of symbol. static const char* ost::Process::getHomeDir (void) [static] Get home directory. Returns: user home directory. static size_t ost::Process::getPageSize (void) [static] Return the effective operating system page size. Returns: system page size. static const char* ost::Process::getUser (void) [static] Get user name. Returns: user login id. static bool ost::Process::isRealtime (void) [inline, static] Return true if realtime scheduling. static bool ost::Process::isScheduler (void) [static] Return true if scheduler settable. static int ost::Process::join (int pid) [static] Get the exit status of another process, waiting for it to exit. Returns: exit code from process. Parameters: pid process id. bool ost::Process::lock (bool future = true) Lock a process in memory. Ideally you should be deep enough where additional memallocs for functions will not kill you, or use false for future. Returns: true if successful. Parameters: future pages as well... static void ost::Process::setEnv (const char * name, const char * value, bool overwrite) [static] Set system environment in a standard manner. Parameters: name of environment symbol to set. value of environment symbol. overwrite true if replace existing symbol. static bool ost::Process::setGroup (const char * id) [static] Set the effective group id by name. Returns: true if successful. static Trap ost::Process::setInterruptSignal (int signo, Trap handler) [static] Set system call interuptable signal handler. return previous handler. Parameters: signo signal no. handler trap handler. static Trap ost::Process::setPosixSignal (int signo, Trap handler) [static] Set a posix compliant signal handler. Returns: previous handler. Parameters: signo signal no. handler trap handler. static void ost::Process::setPriority (int pri) [static] Used to set process priority and optionally enable realtime. static void ost::Process::setRealtime (int pri = 0) [static] Portable shortcut for setting realtime. .. static void ost::Process::setScheduler (const char * policy) [static] Used to set process scheduling policy. static bool ost::Process::setUser (const char * id, bool grp = true) [static] Set user id by name. Returns: true if successful. static int ost::Process::spawn (const char * exec, const char ** argv, bool wait = true) [static] Spawn a process and wait for it’s exit code. In win32 this is done with the spawn system call. In posix, this is done with a fork, an execvp, and a waitpid. Warning: The implementation differences between posix and win32 systems may cause side effects. For instance, if you use atexit() and this spawn method, on posix systems the function set up with atexit() will be called when the parent process of the fork exits, which will not happen on Win32 systems. Returns: error code from process. Parameters: exec name of executable. argv list of command arguments. wait for process to exit before return. void ost::Process::unlock (void) Unlock process pages. Generated automatically by Doxygen for GNU CommonC++ from the source code.
http://huge-man-linux.net/man3/ost_Process.html
CC-MAIN-2017-30
refinedweb
944
52.66
Answer: Every runtime environment must provide three streams viz. standard input, standard output and standard error to every C program. These streams are stdin, stdout and stderr and these are pointers to FILE structure. stdin is default to read from a device which is mostly a keyboard, stdout writes default to a output device which is mostly a terminal or user screen. stderr writes error messages default to terminal or user screen. perror() function writes its error messages to a place where stderr writes its own. A C program which communicates interactively uses these default streams to perform input and/or output to default devices. For ex. #include <stdio.h> int main(void) { char *str; printf("how are you, dear xyz?\n"); gets(str); return 0; } Above program asks the user, “how are you, dear xyz?” and reads in user’s response. Notice that these default streams are always opened and program has not to bother to open or close them. While on the other side, reading from and writing to files in a C program requires to take a series of steps, 1. Declare a pointer of type FILE * for each file to be active at the same time. This pointer points to a FILE structure. Then call fopen(), passing it file to be opened and the mode, whether reading, or writing or both to open a stream. fopen() returns a pointer to FILE structure. Every stream has a FILE structure associated with it. This pointer can be used to access its associated stream. fopen() and operating system may verify whether the given file exists, and on some implementations, operating system may check if you have required permissions for accessing the file in the way you have specified and initializes the FILE structure. 2. Next step is to use the FILE structure to perform I/O from and to the files. 3. After you are done with the file I/O, call the fclose() function, passing it FILE structure associated with a given stream to close the stream and releasing the file pointer for use by other stream when needed. Closing the stream prevents you from accessing the associated file again and guarantees that stream buffer is flushed to the file. Let’s take a simple C program to see difference, /* * fopen_fclose.c -- program attempts to open, process and * close files one by one */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int exit_status = EXIT_SUCCESS; FILE *fp; int ch; printf("**Program reads in file names as command-line arguments,\n" "attempts to open stream associated with each file in read " "mode\nthen reads from each file one-by-one, before closing" " each.**\n"); while (*++argv != NULL) { /* open files */ fp = fopen(*argv, "r"); /* test if fopen succedded */ if (fp == NULL) { /* give user error massage */ printf("No such %s file", *argv); /* not to exit, instead process another */ /*file name if there's any */ exit_status = EXIT_FAILURE; continue; } /* here we process file */ /* read the contents of the file line by line */ while ((ch = fgetc(fp)) != EOF) { putchar(ch); } putchar('\n'); /* Now we close the stream by passing fp to fclose() */ /* also test if fclose did not fail */ if (fclose(fp) != 0) { perror("fclose(): *argv"); exit(EXIT_FAILURE); } } } Notice that file names are passed to the program on command-line. Program attempts to open a stream in read mode, one-by-one, for each file, then reads from file and closes the file until a null string is reached. In the event of when a file name doesn’t exist program doesn’t abort. Instead it continues to open the other file if there’s any. Notice that functions like printf(), putchar(), perror() write to the standard output, while fgetc() reads from the file not from the standard input. Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
http://www.sanfoundry.com/c-tutorials-basic-difference-between-io-standard-streams-files/
CC-MAIN-2017-22
refinedweb
636
71.04
Object-oriented programming makes code understandable by encapsulating moving parts. Functional programming makes code understandable by minimizing moving parts. — Michael Feathers, author of Working with Legacy Code, via Twitter In this installment, I discuss one of the building blocks of functional programming: immutability. An immutable object's state cannot change after construction. In other words, the constructor is the only way you can mutate the object's state. If you want to change an immutable object, you don't — you create a new object with the changed value and point your reference to it. ( String is a classic example of an immutable class built into the core of the Java language.) Immutability is key to functional programming because it matches the goals of minimizing the parts that change, making it easier to reason about those parts. Implementing immutable classes in Java Modern object-oriented languages like Java, Ruby, Perl, Groovy, and C# have built convenient mechanisms to make it easy to modify state in controlled ways. However, state is so fundamental to computation that you can never predict where it will leak out. For example, writing high-performance, correct multithreaded code is difficult in object-oriented languages because of the myriad mutability mechanisms. Because Java is optimized for manipulating state, you have to work around some of those mechanisms to gain the benefits of immutability. But once you know to avoid a few pitfalls, building immutable classes in Java gets easier. Defining immutable classes To make a Java class immutable, you must: - Make all fields final. When you define fields as finalin Java, you must either initialize them at declaration time or in the constructor. Don't panic if your IDE complains that you don't initialize them at the declaration site. It'll realize that you've come back to your senses when you write the appropriate code in the constructor. - Make the class finalso that it cannot be overridden. If the class can be overridden, its methods' behaviors can be overridden as well, so your safest bet is to disallow subclassing. Notice that this is the strategy used by Java's Stringclass. - Do not provide a no-argument constructor. If you have an immutable object, you must set whatever state it will contain in the constructor. If you have no state to set, why do you have an object? Static methods on a stateless class would work just as well. Thus, you should never have a no-argument constructor for an immutable class. If you're using a framework that requires this for some reason, see if you can satisfy it by providing a private no-argument constructor (which is visible via reflection). Notice that the lack of a no-argument constructor violates the JavaBeans standard, which insists on a default constructor. But JavaBeans cannot be immutable anyway, because of the way the setXXXmethods work. - Provide at least one constructor. If you haven't provided a no-argument one, this is your last chance to add some state to the object! - Do not provide any mutating methods other than the constructor. Not only must you avoid typical JavaBeans-inspired setXXXmethods, but you must also be careful not to return mutable object references. The fact that the object reference is finaldoesn't mean that you can't change what it points to. Thus, you need to make sure you defensively copy any object references you return from getXXXmethods. "Traditional" immutable class An immutable class that meets the previous requirements appears in Listing 1: Listing 1. An immutable Address class in Java public final class Address { private final String name; private final List<String> streets; private final String city; private final String state; private final String zip; public Address(String name, List<String> streets, String city, String state, String zip) { this.name = name; this.streets = streets; this.city = city; this.state = state; this.zip = zip; } public String getName() { return name; } public List<String> getStreets() { return Collections.unmodifiableList(streets); } public String getCity() { return city; } public String getState() { return state; } public String getZip() { return zip; } } Note the use of the Collections.unmodifiableList() method in Listing 1 to make a defensive copy of the list of streets. You should always use collections to create immutable lists rather than arrays. Although it is possible to copy arrays defensively, it leads to some undesirable side-effects. Consider the code in Listing 2: Listing 2. Customer class that uses arrays instead of collections public class Customer { public final String name; private final Address[] address; public Customer(String name, Address[] address) { this.name = name; this.address = address; } public Address[] getAddress() { return address.clone(); } } The problem with the code in Listing 2 manifests when you try to do anything with the cloned array that comes back from the call to the getAddress() method, as shown in Listing 3: Listing 3. Test that shows correct but unintuitive outcome public static List<String> streets(String... streets) { return asList(streets); } public static Address address(List<String> streets, String city, String state, String zip) { return new Address(streets, city, state, zip); } @Test public void immutability_of_array_references_issue() { Address [] addresses = new Address[] { address(streets("201 E Washington Ave", "Ste 600"), "Chicago", "IL", "60601")}; Customer c = new Customer("ACME", addresses); assertEquals(c.getAddress()[0].city, addresses[0].city); Address newAddress = new Address( streets("HackerzRulz Ln"), "Hackerville", "LA", "00000"); // doesn't work, but fails invisibly c.getAddress()[0] = newAddress; // illustration that the above unable to change to Customer's address assertNotSame(c.getAddress()[0].city, newAddress.city); assertSame(c.getAddress()[0].city, addresses[0].city); assertEquals(c.getAddress()[0].city, addresses[0].city); } When you return a cloned array, you protect the underlying array — but you are handing back an array that looks like an ordinary array, meaning that you can change the array's contents. (Even if the variable holding the array is final, that applies only to the array reference itself, not to the array's contents.) Using Collections.unmodifiableList() (and the family of methods in Collections for other types), you receive an object reference that has no mutating methods available. Cleaner immutable classes You frequently hear that you should also make your immutable fields private. I disagree with that sentiment, based on hearing someone who has a different but clear vision clarify ingrained assumptions. In a Michael Fogus interview with Clojure creator Rich Hickey (see Resources), Hickey talks about the lack of data-hiding encapsulation of many of the core parts of Clojure. This aspect of Clojure has always bothered me because I'm so steeped in state-based thinking. But then I realized that you don't need to worry about exposing fields if they are immutable. Many of the safeguards we use for encapsulation are really just there to prevent mutation. Once we tease apart those two concepts, a cleaner Java implementation emerges. Consider the version of the Address class in Listing 4: Listing 4. Address class with public, immutable fields public final class Address { private final List<String> streets; public final String city; public final String state; public final String zip; public Address(List<String> streets, String city, String state, String zip) { this.streets = streets; this.city = city; this.state = state; this.zip = zip; } public final List<String> getStreets() { return Collections.unmodifiableList(streets); } } Declaring public getXXX() methods for immutable fields only benefits if you want to hide the underlying representation, But that's of dubious benefit in the era of refactoring IDEs that can find such changes trivially. By making the fields both public and immutable, you can directly access them in code without worrying about accidentally changing them. If you never need to mutate the collection internally, you can cast the embedded list to unmodifiableList in the constructor, which allows you to make the streets field public and eliminate the need for the getStreets() method. As I'll show in the next example, Groovy allows you to create a guard access method like getStreets() and yet allow it to appear as a field. Using immutable public fields seems unnatural at first if you listen to angry monkeys, but their differentness is a benefit: you are unaccustomed to dealing with immutable types in Java, and this looks like a new type, as illustrated in Listing 5: Listing 5. Unit test of the Address class @Test (expected = UnsupportedOperationException.class) public void address_access_to_fields_but_enforces_immutability() { Address a = new Address( streets("201 E Randolph St", "Ste 25"), "Chicago", "IL", "60601"); assertEquals("Chicago", a.city); assertEquals("IL", a.state); assertEquals("60601", a.zip); assertEquals("201 E Randolph St", a.getStreets().get(0)); assertEquals("Ste 25", a.getStreets().get(1)); // compiler disallows //a.city = "New York"; a.getStreets().clear(); } Accessing the public, immutable fields avoids the visual overhead of a series of getXXX() calls. Notice also that the compiler won't allow you to assign to one of the primitives, and if you try to call a mutating method on the street collection, you'll get an UnsupportedOperationException (as caught at the top of the test). Using this style of code is a strong visual indicator that it's an immutable class. Downsides One possible disadvantage of the cleaner syntax is the effort entailed in learning this new idiom. But I think it's worth it: it encourages you to think about immutability when creating classes because of an obvious stylistic difference, and it cuts down on unnecessary boilerplate code. But there are some downsides to this coding style in Java (which, to be fair, was never designed to accommodate immutability directly): - As Glenn Vanderburg pointed out to me, the biggest downside is that the style violates what Bertrand Meyer (creator of the Eiffel programming language) called the Uniform Access Principle: "All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation." In other words, accessing a field shouldn't expose whether it's a field or a method that returns a value. The Addressclass's getStreets()method isn't uniform with the other fields. This problem can't really be solved in Java; it is solved in some of the other JVM languages in the way they enable immutability. - Some frameworks that rely heavily on reflection won't work with this idiom because they require a default constructor. - Because you create new objects rather than mutate old ones, systems with lots of updates can cause inefficiencies with garbage collection. Languages like Clojure have built-in facilities to make this more efficient with immutable references, which is the default in those languages. Immutability in Groovy Building the public-immutable-field version of the Address class in Groovy yields a nice clean implementation, shown in Listing 6: Listing 6. Immutable Address class in Groovy class Address { def public final List<String> streets; def public final city; def public final state; def public final zip; def Address(streets, city, state, zip) { this.streets = streets; this.city = city; this.state = state; this.zip = zip; } def getStreets() { Collections.unmodifiableList(streets); } } As usual, Groovy requires less boilerplate code than Java — and there are other benefits as well. Because Groovy allows you to create properties by using familiar get/ set syntax, you can create a truly protected property for the object reference. Consider the unit tests shown in Listing 7: Listing 7. Unit tests showing uniform access in Groovy class AddressTest { @Test (expected = ReadOnlyPropertyException.class) void address_primitives_immutability() { Address a = new Address( ["201 E Randolph St", "25th Floor"], "Chicago", "IL", "60601") assertEquals "Chicago", a.city a.city = "New York" } @Test (expected=UnsupportedOperationException.class) void address_list_references() { Address a = new Address( ["201 E Randolph St", "25th Floor"], "Chicago", "IL", "60601") assertEquals "201 E Randolph St", a.streets[0] assertEquals "25th Floor", a.streets[1] a.streets[0] = "404 W Randoph St" } } Notice that in both cases, the test terminates when an exception is thrown because of a violation of the immutability contract. In Listing 7, however, the streets property looks just like the primitives, but it is actually protected via its getStreets() method. Groovy's @Immutable annotation One of the underlying tenets of this series is that functional languages should handle more low-level details for you. A good illustration is the @Immutable annotation added in Groovy version 1.7, which makes all the coding in Listing 6 moot. Listing 8 shows a Client class that uses this annotation: Listing 8. Immutable Client class @Immutable class Client { String name, city, state, zip String[] streets } By virtue of using the @Immutable annotation, this class has the following characteristics: - It is final. - Properties automatically have private backing fields with get methods synthesized. - Any attempts to update properties result in a ReadOnlyPropertyException. - Groovy creates both ordinal and map-based constructors. - Collection classes are wrapped in appropriate wrappers, and arrays (and other cloneable objects) are cloned. - Default equals, hashcode, and toStringmethods are automatically generated. This annotation provides a lot of bang for the buck! It also acts as you would expect, as shown in Listing 9: Listing 9. The @Immutable annotation handling expected cases correctly @Test (expected = ReadOnlyPropertyException) void client_object_references_protected() { def c = new Client([streets: ["201 E Randolph St", "Ste 25"]]) c.streets = new ArrayList(); } @Test (expected = UnsupportedOperationException) void client_reference_contents_protected() { def c = new Client ([streets: ["201 E Randolph St", "Ste 25"]]) c.streets[0] = "525 Broadway St" } @Test void equality() { def d = new Client( [name: "ACME", city:"Chicago", state:"IL", zip:"60601", streets: ["201 E Randolph St", "Ste 25"]]) def c = new Client( [name: "ACME", city:"Chicago", state:"IL", zip:"60601", streets: ["201 E Randolph St", "Ste 25"]]) assertEquals(c, d) assertEquals(c.hashCode(), d.hashCode()) assertFalse(c.is(d)) } Trying to replace the object reference yields an ReadOnlyPropertyException. And trying to change what one of the encapsulated object references points to generates a UnsupportedOperationException. It also creates appropriate equals and hashcode methods, as shown in the last test — the object contents are the same, but they do not point to the same reference. Of course, both Scala and Clojure support and encourage immutability and have clean syntax for it, the implications of which will pop up in future installments. Benefits of immutability Embracing immutability is high on the list of ways to think like a functional programmer. Although building immutable objects in Java requires a bit more up-front complexity, the downstream simplification forced by this abstraction easily offsets the effort. Immutable classes make a host of typically worrisome things in Java go away. One of the benefits of switching to a functional mindset is the realization that tests exist to check that changes occur successfully in code. In other words, testing's real purpose is to validate mutation — and the more mutation you have, the more testing is required to make sure you get it right. If you isolate the places where changes occur by severely restricting mutation, you create a much smaller space for errors to occur and have fewer places to test. Because changes only occur upon construction, immutable classes make it trivial to write unit tests. You do not need a copy constructor, and you need never sweat the gory details of implementing a clone() method. Immutable objects make good candidates for use as keys in either Maps or Sets; keys in dictionary collections in Java cannot change value while being used as a key, so immutable objects make great keys. Immutable objects are also automatically thread-safe and have no synchronization issues. They can also never exist in unknown or undesirable state because of an exception. Because all initialization occurs at construction time, which is atomic in Java, any exception occurs before you have an object instance. Joshua Bloch calls this failure atomicity: success or failure based on mutability is forever resolved once the object is constructed (see Resources). Finally, one of the best features of immutable classes is how well they fit into the composition abstraction. In the next installment, I'll start investigating composition and why it is so important in the functional-thinking world. Resources Learn - The Productive Programmer (Neal Ford, O'Reilly Media, 2008): Neal Ford's most recent book discusses tools and practices that help you improve your coding efficiency. - Clojure: Clojure is a modern, functional Lisp that runs on the JVM. - Rich Hickey Q&A: Michael Fogus interviews Clojure creator Rich Hickey. - Stuart Halloway on Clojure: Learn more about Clojure from this developerWorks podcast. - Scala: Scala is a modern, functional language on the JVM. - The busy Java developer's guide to Scala: Dig more deeply into Scala in this developerWorks series by Ted Neward. - Effective Java, 2d ed. (Joshua Bloch, Addison Wesley, 2008): Read more about failure atomicity. -
http://www.ibm.com/developerworks/library/j-ft4/index.html
CC-MAIN-2016-44
refinedweb
2,754
54.42
SYNOPSIS #include <tracefs.h> int tracefs_print_init(struct tracefs_instance *instance); int tracefs_printf(struct tracefs_instance *instance, const char *fmt, …); int tracefs_vprintf(struct tracefs_instance *instance, const char *fmt, va_list ap); void tracefs_print_close(struct tracefs_instance *instance); DESCRIPTION Set of functions to write formated strings_print_init() function initializes the library for writing into the trace buffer of the selected instance. It is not mandatory to call this API before writing strings, any of the printf APIs will call it automatically, if the library is not yet initialized. But calling tracefs_print_init() in advance will speed up the writing. The tracefs_printf() function writes a formatted string in the trace buffer of the selected instance. The fmt argument is a string in printf format, followed by variable arguments …. The tracefs_vprintf() function writes a formatted string in the trace buffer of the selected instance. The fmt argument is a string in printf format, followed by list ap of arguments. The tracefs_print_close() function closes the resources, used by the library for writing in the trace buffer of the selected instance. RETURN VALUE The tracefs_print_init(), tracefs_printf(), and tracefs_vprintf() functions return 0 if the operation is successful, or -1 in case of an error. EXAMPLE #include <tracefs.h> if (tracefs_print_init(NULL) < 0) { /* Failed to initialize the library for writing in the trace buffer of the top trace instance */ } void foo_print(char *format, ...) { va_list ap; va_start(ap, format); if (tracefs_vprintf(NULL, format, ap) < 0) { /* Failed to print in the trace buffer */ } va_end(ap); } void foo_print_string(char *message) { if (tracefs_printf(NULL, "Message from user space: %s", message) < 0) { /* Failed to print in the trace buffer */ } } tracefs_print).
https://trace-cmd.org/Documentation/libtracefs/libtracefs-marker.html
CC-MAIN-2022-27
refinedweb
261
52.09
Tutorial: Spock Part 5 – Other Useful Tips We’ve now covered all the key features for creating and running tests with Spock. In Part 5, we finish up the Spock tutorial by looking at additional features that can help you to write short, descriptive, correct. Helper Methods When tests get big, we may want to split out large parts of code, or common code, into helper methods. Let’s say we have a test like this one. def "should use a helper method"() { given: Renderer renderer = Mock() def shapeFactory = new ShapeFactory(renderer) when: def polygon = shapeFactory.createDefaultPolygon() then: polygon.numberOfSides == 4 polygon.renderer == renderer //could check lots of different values on this polygon... } It uses a ShapeFactory to create a default shape, and then we perform a number of checks to make sure this meets our expectations. You can imagine in real production code there might be a lot of values to check here. We may be tempted to move all these checks into their own method, especially if they’re going to be used by more than one test. def "should use a helper method"() { //given... when... code then: checkDefaultShape(polygon, renderer) } private static void checkDefaultShape(Polygon polygon, Renderer renderer) { polygon.numberOfSides == 4 polygon.renderer == renderer } Run the test – it will pass. However, if we change the code so it should fail, we’ll see that it still passes. This helper method is not doing what we expect. If we move our assertions into a helper method like this, it can no longer use the comparison operators to define the expected behaviour. Instead, we need to add the assert keyword specifically. private static void checkDefaultShape(Polygon polygon, Renderer renderer) { assert polygon.numberOfSides == 4 assert polygon.renderer == renderer } Now if you run the test with incorrect values in checkDefaultShape, it should fail. There’s something else to be aware of too – it fails on the first assertion that fails, it never runs the assertion to check the polygon’s renderer. Later we’ll look at how to address that. with() Let’s look at one approach to testing multiple properties of a single object. We can change the previous test to the following: def "should use a helper method"() { given: Renderer mockRenderer = Mock() def shapeFactory = new ShapeFactory(mockRenderer) when: def polygon = shapeFactory.createDefaultPolygon() then: with(polygon) { numberOfSides == 4 renderer == null } } We can use Spock’s with() and a closure to check multiple values on the polygon. Inside this closure, we don’t have to say polygon., we just assert the property matches the expected value. Note that in this test the mock Renderer created in the given block is called mockRenderer – this is so that it’s clear that the renderer in the with block is polygon.renderer, not the renderer from the test scope. Change the test so it fails, so we can see what this looks like: As with the helper method, if the first assertion fails, it doesn’t run any further assertions. This might be what you want from your test, if one value is wrong the whole test should fail regardless. However, sometimes we want to run all the assertions so we can see exactly what’s working and what’s not. verifyAll() Let’s look at how to make sure all our assertions are run, regardless of whether one of them fails. Try this test (note that with string method names we can easily add quotes and other special characters). def "should demonstrate 'verifyAll'"() { given: Renderer mockRenderer = Mock() def shapeFactory = new ShapeFactory(mockRenderer) when: def polygon = shapeFactory.createDefaultPolygon() then: verifyAll(polygon) { numberOfSides == 5 renderer == null } } We can replace our with() call with verifyAll() instead. Run this (the code above should fail) and see what happens – not only does the number of sides assertion fail, but the check on the renderer also fails. org.opentest4j.MultipleFailuresError: Multiple Failures (2 failures) org.spockframework.runtime.SpockComparisonFailure: Condition not satisfied: numberOfSides == 5 | | 4 false org.spockframework.runtime.SpockComparisonFailure: Condition not satisfied: renderer == null | | | false Mock for type 'Renderer' named 'mockRenderer' With verifyAll, all assertions are run and we can see which fail and which pass. This can help us when we’re iterating quickly between writing and fixing tests. Go back and fix this test: then: verifyAll(polygon) { numberOfSides == 4 renderer == mockRenderer } (Note that this code differs slightly from the video, since using two variables called renderer made it really hard to see what was being tested) Setup and Teardown If you’ve used other testing frameworks, the concept of test or specification class setup and tear down will be familiar. Spock provides a setup method (we can use IntelliJ IDEA’s code generation to create this), which will be run before every individual test method in this class. This can be used to set up a clean state at the start of each test. To clean up data or state at the end of every test method, you need a cleanup method. This is run after every individual test method. Use the setupSpec method to set up state once at the start of the specification, this is for things that should not change between individual test methods. Create a cleanupSpec method for final teardown code, this method will be called once at the very end of running all the tests. One final piece of useful information. The tests in this tutorial created the “objects under test” in the test methods themselves. However, you might also want to create your test instance as a field in the test. You can use the @Subject annotation on the field to show that this is the object under test (you can use this annotation on local variables in the methods too). You can then reference this field in the test methods just as you’d expect in any Java or Groovy class. @Subject private Polygon polygon = new Polygon(5) Specifications as Documentation Let’s take a look at one last feature to help document the requirements via tests. We’ve seen that Spock has a focus on readability and tests as documentation. The @Subject annotation, the labelled blocks, Strings as test method names plus all you can do to customise these String values all contribute to being able to use the automated tests as a documentation for what the system should do. We can also add more information, again for readability or documentation purposes, to the blocks in our tests. def "should be able to create a stub"() { given: "a palette with red as the primary colour" Palette palette = Stub() palette.getPrimaryColour() >> Colour.Red and: "a renderer initialised with the red palette" def renderer = new Renderer(palette) expect: "the renderer to use the palette's primary colour as foreground" renderer.getForegroundColour() == Colour.Red } We can add a String next to the label to give a more detailed description of the block. If we want to split a block into further blocks, for readability or to add documentation, we can use the and: label, this is just to let us break things up further. The text is available to the Spock runtime, so these messages can be used in messages and reports. Conclusion Spock is powerful and has even more to offer than we’ve looked at here. Believe it or not we’ve only touched the surface of what Spock can offer. We’ve seen the basics of a test, we’ve seen how to use labels to define tests, we’ve seen the power of data driven testing, and we’ve covered a range of tips and tricks for writing correct and readable tests. If you want to find out more about Spock, take a look at the excellent reference documentation. There’s also a Spock Primer which is a great place to start with Spock.
https://blog.jetbrains.com/idea/2021/02/tutorial-spock-part-5-other-useful-tips/
CC-MAIN-2021-43
refinedweb
1,296
61.77
Haskell Quiz/The Solitaire Cipher/Solution JFoutz From HaskellWiki < Haskell Quiz | The Solitaire Cipher This took longer than expected. I didn't read the specification closely enough to realize both jokers count as 53 rather than A == 53 and B == 54 Other than that, looking through Data.List for shortcuts was educational. I really like zipWith and groupBy. This could probably use a lot more orginization, and a bit more commentary. Fortunately the function names match the spec closely, which helps. import Data.Char import Data.List import System -- discard any non a to z characers, uppercase the rest -- split into groups of 5, padded with 'X' prep ls = loop $ map toUpper $ filter (\x -> and [isAscii x, isLetter x]) ls where loop [] = [] loop ls | length ls < 5 = [take 5 (ls ++ "XXXX")] | otherwise = (take 5 ls) : loop (drop 5 ls) drawMsg msg = concat $ intersperse " " (loop msg) where loop msg | length msg > 5 = (take 5 msg) : loop (drop 5 msg) | otherwise = [msg] churn f msg = drawMsg $ toChr $ zipWith f (toNum $ concat $ prep msg) (keyStream [1..54]) crypt msg = churn solAdd msg decrypt msg = churn solSub msg main = do { x <- getArgs ; case (head x) of "c" -> putStrLn $ crypt $ concat $ tail x "d" -> putStrLn $ decrypt $ concat $ tail x _ -> putStrLn "Try solitaire c my message, or d my message"} -- letters to numbers and back toNum = map (\x -> ord x - 65) toChr = map (\x -> chr (x + 65)) -- add and subtract base solitaire style solAdd x y = mod (x + y) 26 solSub x y = mod (x + 26 - y) 26 --keyStream down1 x ls = move $ break (==x) ls where move (x:xs, t:[]) = x:t:xs move (xs, c:n:cx) = xs ++ n : c : cx down2 x ls = down1 x $ down1 x ls notEither a b = (\x y -> x /= a && y /= a && x /= b && y /= b) tripleCut a b ls = swap a b $ concat $ reverse $ groupBy (notEither a b) ls swap a b [] = [] swap a b (x:xs) | a == x = b : swap a b xs | b == x = a : swap a b xs | otherwise = x : swap a b xs cardVal c = if c == 54 then 53 else c countCut ls = glue $ splitAt (cardVal $ last ls) (init ls) where glue (f,b) = b ++ f ++ [last ls] jokerA = 53 jokerB = 54 keyStep deck = countCut $ tripleCut jokerA jokerB $ down2 jokerB $ down1 jokerA deck getCard deck = deck !! (cardVal $ head deck) keyStream deck = let d2 = keyStep deck out = getCard d2 in if out == jokerA || out == jokerB then keyStream d2 else out : keyStream d2
https://wiki.haskell.org/index.php?title=Haskell_Quiz/The_Solitaire_Cipher/Solution_JFoutz&oldid=12010
CC-MAIN-2015-18
refinedweb
410
56.66
scipy.interpolate.interp2d multivariate interpolation and list alignement Given a set of (x[i],y[i],Value[i]) we can create a list or tuple and plot them with the command list_plot3d. In this way we take a 3d plot where in fact the z-axis corresponds to the value of an f(x,y). Instead of doing this, it appears that with scipy.interpolate.interp2d it is possible to avoid using the list_plot3d and create a contour-density kind of plot. As shown in the link it is feasible to do this but the fact is that it is too complicated to understand for a beginner like me. Is possible to explain this just to the simple point that someone takes the tuple and tries to create a contour-like plot? EDIT: It seems that the part of the code below is enough to make a contour plot: import numpy, scipy.interpolate f_interpolation = scipy.interpolate.interp2d(*zip(*data)) plot_interpolation = contour_plot(lambda x,y: f_interpolation(x,y)[0], (30,40), (20,30), cmap='jet', contours=numpy.arange(0.1,30,5), colorbar=True) Notice on the second line that it refers to some data obviously given before this part of the code. I found out that for this code to work one has to have fully aligned data to feed to the code above. Example: ( 37.850629, 5.421135, 22.162571637111411), ( 37.706629, 0.421472, 5.229876952864690), ( 7.706629, 28.421472, 15.229876952864690), If in any way the data that might be a tuple, or a list from what i understand, are not formatted as above, the code doesn't run. How is it possible to right align all elements as well as keep them aligned in relation to the decimal place in a list?
https://ask.sagemath.org/question/9143/scipyinterpolateinterp2d-multivariate-interpolation-and-list-alignement/
CC-MAIN-2019-43
refinedweb
295
60.35
Is there a simple way in Java (that doesn't involve writing a for-loop) to create an array of objects from a property of another array of different objects? For example, if I have an array of objects of type A public class A { private String p; public getP() { return p; } } A[i].p i Arrays.copyOf(U[] original, int newLength, Class<? extends T[]> newType) Arrays.copyOf(arrayA, arrayA.length, (A a) -> a.getP()); With Java 8, you can use the Stream API and particularly the map function: A[] as = { new A("foo"), new A("bar"), new A("blub") }; String[] ps = Stream.of(as).map(A::getP).toArray(String[]::new); Here, A::getP and String[]::new are method/constructor references. If you do not have a suitable method for the property you want to have, you could also use a lambda function: String[] ps = Stream.of(as).map(a -> a.getP()).toArray(String[]::new);
https://codedump.io/share/QsxNMljRsTxE/1/java-creating-an-array-from-the-properties-of-another-array
CC-MAIN-2017-09
refinedweb
155
66.03
pylibscrypt 1.0.3 Scrypt for Python There are a lot of different scrypt modules for Python, but none of them have everything that I’d like, so here’s One More1. Features Requirements - Python 2.7 or 3.4 or so. Pypy 2.2 also works. Older versions may or may not. - If you want speed: libscrypt 1.8+ (older may work) or py-scrypt 0.6+ Usage from pylibscrypt import * # Print a raw scrypt hash in hex print(scrypt('Hello World', 'salt').encode('hex')) # Generate an MCF hash with random salt mcf = scrypt_mcf('Hello World') # Test it print(scrypt_mcf_check(mcf, 'Hello World')) print(scrypt_mcf_check(mcf, 'HelloPyWorld')) Versioning The package has a version number that can be read from python like so: print(pylibscrypt.__version__) The version number is of the form X.Y.Z. The number X will only be incremented if an incompatible change is done, but this is not planned. The number Y will be incremented for new features or API for which a caller may wish to check. The last number will be incremented for bugfix-only releases.5 to report test coverage. If you would like to include a new feature, it should be adequately covered with tests. TODO - Embed C implementation for when there’s no system library? -.0.3.xml
https://pypi.python.org/pypi/pylibscrypt/1.0.3
CC-MAIN-2017-30
refinedweb
218
77.03
I don't know if everything 3D works, but the first error you note below is fixed in svn, and I suspect in 0.87.7, the last release. 0.87.5 is rather old--quite a bit has changed between minor releases. Eric Matthew Koichi Grimes wrote: >> > > > > > ------------------------------------------------------------------------- > Take Surveys. Earn Cash. Influence the Future of IT > Join SourceForge.net's Techsay panel and you'll get the chance to share your > opinions on IT & business topics through brief surveys - and earn cash > > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users@... >> Dear all, I am coming back to an issue for which I didn't get a direct answer (except for a very nice module from Angus McMorland!): - at the moment different backends in mpl automatically provides, when an image (or a plot) is displayed with e.g. imshow (plot), the coordinates x and y directly in the toolbar. - When it is indeed an image wich is displayed, it would, in my opinion makes a LOT of sense to also display the "z" coordinate, namely the 'intensity' value of the pixel of the image on which the cursor is standing. The questions are then: does this also make sense to you, and if yes, would it be possible for someone to implement it as an intrinsic feature of mpl backends? (I am not competent to answer the feasibility part here, although the module Angus nicely provided on the list is an excellent example, even if it adds one more layer which may be avoidable). thanks for any input here! cheers Eric Hi all I am trying to plot the trajectory of the Lorenz system with the axes3d.py module (version 0.87.7). The code is the following: from numpy import * from scipy.integrate import odeint import pylab as p import matplotlib.axes3d as p3 def Lorenz(w, t, s, r, b): x, y, z = w return array([s*(y-x), r*x-y-x*z, x*y-b*z]) # Parameters s = 8.0 r = 28.1 b = 8/3.0 w_0 = array([0., 0.8, 0.]) # Initial condition time = arange(0., 100., 0.01) # time vector trajectory = odeint(Lorenz, w_0, time, args=(s, r, b)) # 10^5 x 3 array # There must be better ways to do this: x = trajectory[:,0] y = trajectory[:,1] z = trajectory[:,2] # 3D plotting fig=p.figure() ax = p3.Axes3D(fig) ax.plot3D(x,y,z) # I guess this is the method to use p.show() I get however some errors related with the autoscale_view() method (see below). I have two questions: Is plot3D the correct choice for plotting a 3D curve? In that case, is there any way to fix these errors? Thanks a lot for your help and for making matplotlib possible, dani Errors (pdb output): lorenz.py ---> 42 plot3D(x,y,z) /usr/lib/python2.4/site-packages/matplotlib/axes3d.py in plot3D(self, xs, ys, zs, *args, **kwargs) 488 def plot3D(self, xs, ys, zs, *args, **kwargs): 489 had_data = self.has_data() --> 490 lines = Axes.plot(self, xs,ys, *args, **kwargs) 491 if len(lines)==1: 492 line = lines[0] /usr/lib/python2.4/site-packages/matplotlib/axes.py in plot(self, *args, **kwargs) 2129 lines = [line for line in lines] # consume the generator 2130 -> 2131 self.autoscale_view(scalex=scalex, scaley=scaley) 2132 return lines TypeError: autoscale_view() got an unexpected keyword argument 'scalex' > /usr/lib/python2.4/site-packages/matplotlib/axes.py(2131)plot() 2130 -> 2131 self.autoscale_view(scalex=scalex, scaley=scaley) 2132 return lines Hi, I am a newbie in matplotlib. I want to use the following label (in latex) \langle \partial_x U(x) \rangle. When i use ylabel(r"$\langle \partial_x U(x) \rangle$",fontsize=30); matplotlib complains by saying Traceback (most recent call last): File "/usr/lib/python2.3/site-packages/matplotlib/backends/backend_gtk.py", line 277, in expose_event self._render_figure(width, height) File "/usr/lib/python2.3/site-packages/matplotlib/backends/backend_gtkagg.py", line 91, in _render_figure FigureCanvasAgg.draw(self) File "/usr/lib/python2.3/site-packages/matplotlib/backends/backend_agg.py", line 369, in draw self.figure.draw(renderer) File "/usr/lib/python2.3/site-packages/matplotlib/figure.py", line 498, in draw for a in self.axes: a.draw(renderer) File "/usr/lib/python2.3/site-packages/matplotlib/axes.py", line 1362, in draw self.yaxis.draw(renderer) File "/usr/lib/python2.3/site-packages/matplotlib/axis.py", line 578, in draw self.label.draw(renderer) # memory leak here, vertical text File "/usr/lib/python2.3/site-packages/matplotlib/text.py", line 334, in draw bbox, info = self._get_layout(renderer) File "/usr/lib/python2.3/site-packages/matplotlib/text.py", line 179, in _get_layout w,h = renderer.get_text_width_height( File "/usr/lib/python2.3/site-packages/matplotlib/backends/backend_agg.py", line 242, in get_text_width_height width, height, fonts = math_parse_s_ft2font( File "/usr/lib/python2.3/site-packages/matplotlib/mathtext.py", line 1222, in math_parse_s_ft2font handler.expr.set_size_info(fontsize, dpi) File "/usr/lib/python2.3/site-packages/matplotlib/mathtext.py", line 870, in set_size_info self.elements[0].set_size_info(self._scale*fontsize, dpi) File "/usr/lib/python2.3/site-packages/matplotlib/mathtext.py", line 795, in set_size_info Element.set_size_info(self, fontsize, dpi) File "/usr/lib/python2.3/site-packages/matplotlib/mathtext.py", line 708, in set_size_info element.set_size_info(self.fontsize, dpi) File "/usr/lib/python2.3/site-packages/matplotlib/mathtext.py", line 796, in set_size_info self.metrics = Element.fonts.get_metrics( File "/usr/lib/python2.3/site-packages/matplotlib/mathtext.py", line 409, in get_metrics cmfont, metrics, glyph, offset = \ File "/usr/lib/python2.3/site-packages/matplotlib/mathtext.py", line 429, in _get_info raise ValueError('unrecognized symbol "%s"' % sym) ValueError: unrecognized symbol "\partial" I searched the forum for something similar and could not find anything. Also my latex can typeset the above if i run it in a separate tex file. I am using the GTKAgg backend. Could someone please help me out? Bye Vijay -- View this message in context: Sent from the matplotlib - users mailing list archive at Nabble.com. Hi, >. In the meantime, I did the following to my local dev copy of IPython: Instead of the existing "import..." viq exec into user namespace, I do: import pylab as P import numpy as N import matplotlib as M It would be nice if controlling this type of thing was configurable. --b >>>>> "Christopher" == Christopher Barker <Chris.Barker@...> writes: Christopher> F1 = OOlab.Figure() F2 = OOlab.Figure() We have this: fig1 = pylab.figure() fig2 = pylab.figure() ax1 = fig.add_subplot(111) line, = ax1.plot([1,2,3]) line.set_color('green') ax1.set_title('hi mom') Yes, it would be nice to be able to do ax1.title = 'hi mom' but other than that pretty much everything you describe already exists. Instead of thinking about OOlab, which mostly already exists, I think it's more useful to focus on a few shortcuts which will make OO use as easy as pylab. It is already -- I pretty much use the OO interface exclusively in all my work. All my scripts start with from pylab import figure, close, show, nx and that's all, and it works fine. One helpful tip: the children point to their parents, so expanding on Jeff's point about the line containing a pointer to the axes it lives in, you can also reference the figure and canvas as upstream containers line.axes.figure.canvas.draw() for example. Christopher> Why couldn't plot(x,y) create and return a figure Christopher> object? Or an axis object? -- I haven't thought it Christopher> out too much yet. Because it returns a line object. But I do think it is a design limitation to plot make an axes method. >> For interactive use, I really don't see any advantage to an OO Christopher> interface. Christopher> Well, for *just* interactive use, I agree, but I see Christopher> some very large advantages to an OO style for Christopher> embedding in programs and larger projects. Sure, all programmers agree with that. For scripts and apps, the OO interface is clearly superior. Teachers teaching students who are new to programming, however, are adamant that the pylab/proceedural interface is crucial to get them to adopt python over matlab, and I trust them. And for interactive quick-and-dirty minimize-the-typing work, the current figure, current axes approach is quite handy. Christopher> As handy as it is to have a command line to play Christopher> with, if I'm writing more than four or five lines Christopher> (and I usually am!), I'm happier putting them in a Christopher> file and running them as a script. Even in that case, Christopher> I don't mind a little extra typing. Christopher> What I'm envisioning for "OOlab" is a set of utility Christopher> functions that do make some of the pylab stuff easy Christopher> -- not well thought out yet, but something like: It's all there with the exception of GUI window management, and you might as well use pylab for that. That saves you a lot of boilerplate. Christopher> F = ooLab.figure(1) # I often need to plot more than Christopher> one figure anyway, so I don't mind having to type Christopher> that. Christopher> ax = F.plot(x,y) # there could be this and subplot Well, this breaks the whole concept of multiple axes, though one could have a helper function that assumes subplot(111) ... But explicit is better than implicit so may as well instantiate the Axes with fig.add_subplot... Christopher> ax.set_title = "A title for the plot" # or better Christopher> yet: ax.title = "A title for the plot" # I'd like to Christopher> see more properties in MPL too! Agreed. Christopher> ax.grid(True) . . . Exists... Christopher> Note that some of this comes from my love of Christopher> namespaces -- I really don't like "import*" -- the Christopher> way that can work is using more OO, so you don't need Christopher> to type the module name everywhere.. Christopher> I don't see much advantage to keeping the idea of a Christopher> "current figure" or "current axis" -- it's just not Christopher> that hard to keep a reference. Maybe it does help for Christopher> quickie command line stuff, but I think for even Christopher> quickie scripts, it's clearer to name your axes, etc. Agreed. I should rewrite all the examples and move the existing examples into a "matlab-like" dir. The examples would all start with the minimal import of figure, show, nx and close. Christopher> However, the proof is in the pudding -- what needs to Christopher> be done is for someone to sit down and start using Christopher> MPL in interactive/quickie script use without pylab, Christopher> and write something for OOlab whenever something is Christopher> harder to do than it should be. Then we'll see how it Christopher> works out. No, one should just use pylab for figure creation and destruction and add convenience methods to shorten some calls if needed, just as we did when we added fig.savefig as a shorthad for fig.canvas.print_figure on your suggestion. We don't need a new interface though we could improve the existing one to handle some annoyances. We do, however, want to use properties in the existing interface. Note also for the interactive use, we could probably utilize ipython to call draw in special hooks. Fernando: if one does In[5]: o.set_something(blah) can we configure ipython to do gcf().canvas.draw() iff o is an instance of a matplotlib.Artist? JDH FWIW On Jan 11, 2007, at 5:29 PM, Bob Ippolito wrote: > On 1/11/07, Nicholas Riley <njriley@...> wrote: >> On Thu, Jan 11, 2007 at 02:21:19PM -0800, Christopher Barker wrote: >>>. >> > > Well I'm back in the country now and I just got my mbp back from > applecare today... so if "someone" sends me updated binaries I'll > gladly sync them to pythonmac.org. > > -bob > PPS: Belinda, now that you've done all this work, I do hope you can > go the extra mile and figure out how to make a binary package of it > all for others! I certainly would like to to do this, but its gonna have to wait until after TheCurrentCrisis alleviates. Hopefully before Feb (in the worst case, mid-June), as I too am annoyed at how hard this seemed to be for the Mac. I also find it disconcerting that Vincent had different troubles than I w/the same source instructions (did they ever get resolved)? As had Erin. At the same time, until about May I'll have access to both Intel and PPC Macs, so I have an ideal env. on which to test. I have only a vague idea how to make dmgs (have perused the incomprehensible hdutils man page), though, so may need some help. At the same time, I'm not qualified to fix the Vincent/Erin problems and have no idea how to go about making "universals" that work for everyone. In fact, these current threads lead me to wonder if it can actually be done (the sad alternative is this: anyone w/a Mac that wants to use the matscinum suite [defined below], unless you have piles of time to waste, stick w/matlab provided you can afford it). W/all this talk about numpy integrating w/python (via a PEP), it seems the best customers for such a move would be a unified matscinum community. Right now that community (at least on the Mac) is accessible to the uber-gang only (of which I barely pass the bar, but since I've gotten SOMETHING working, w/much online help, I feel I've earned the right to include myself). I should mention a friend of mine who knows a lot more about sys stuff than I do had a heck of a time getting all this running on Linux---the entire package: matplotlib, numpy, scipy---lets call it the matscinum suite. In fact, it really seems this integration/ installation issue should be addressed across these 3 respective mailing lists, for if one doesn't work, the others become unusable for on non-trivial number of people (Perhaps there should be a list that is a combo of these three?) FWIW, this is just hot off the macpython sig list: --------- >. --------- I agree with the sentiments but also recognize that the documentation at scipy (where most of this stuff is loaded) is inaccurate, e.g. the superpak doesn't work. Well, that's it for now. I'll try your wx rec's as soon as I find the time (likely next week). Gotta run and thanks for all the help, --b so use pylab.gca() ? On Jan 11, 2007, at 3:31 PM, Christopher Barker wrote: > Jeff Whitaker wrote: > >> Chris: In the pylab interface, figure() returns a figure instance >> and >> plot(x,y) returns a list of Line2d instances. > > yes, but it's the axis instance that you are most likely to@... > > ---------------------------------------------------------------------- > --- >@... >
http://sourceforge.net/p/matplotlib/mailman/matplotlib-users/?viewmonth=200701&viewday=12
CC-MAIN-2014-10
refinedweb
2,486
65.93
Open Bug 1347169 Opened 3 years ago Updated 1 year ago Allow chrome UI to be enlarged or shrunk using a manifest property Categories (WebExtensions :: Frontend, enhancement, P3) Tracking (Not tracked) People (Reporter: mikedeboer, Unassigned) References (Blocks 1 open bug) Details (Whiteboard: triaged) User Story As a theme author I’d like to set a property in a theme WebExtension manifest that will allow the chrome UI to be enlarged or shrunk when set during runtime and web pages inside tabs are not, because their their zoom level can be controlled separately using page zoom. If this is not possible, we can also allow content and chrome to scale together (limited to .9x, 1x, 1.1x for example) Attachments (2 files) No description provided. Priority: -- → P5 Severity: normal → enhancement mass move of existing themes bugs to new WebExtensions: Themes component Component: WebExtensions: Frontend → WebExtensions: Themes Product: Toolkit → WebExtensions I talked with Tim about this bug and we think that this doesn't make sense as part of the Theming API since it feels like more of an accessibility feature and the theming API also has abilities to set themes on a per-window basis which doesn't make as much sense for this. We think that the browserSettings namespace is a better fit. Mike, are you okay with changing the namespace on this? Tim can begin working on this now, if so. Assignee: nobody → ntim.bugs Component: Themes → Frontend Flags: needinfo?(mconca) Priority: P5 → P1 Thanks, Jared. I agree with taking this out of themes. I'd like to pause before putting it into browserSettings, though. Two reasons: 1) There are a few other proposed accessibility-related API, enough that we've been discussing creating a new namespace just for them. This would fit into that namespace. 2) This API replicates a function already found in most (all?) OS's, and we've explicitly been avoiding adding WebExtension API that duplicate functionality already available. Regarding #2, I know the accessibility team has been making an effort to have Firefox inherit and use more OS functionality, rather than implement accessibility features into the product. I'd like to get David Bolter's opinion on if there is value in letting extensions change the size of the Firefox chrome UI. Flags: needinfo?(mconca) → needinfo?(dbolter) Priority: P1 → P3 Thanks Mike. Aside: as a general comment we do have a history of trying to inherit os functionality, and yet I think we can sometimes do better than the os (e.g. Windows High Contrast Mode is not right for the web). My gut says there is value in letting extensions change the chrome UI but it also feels like it could be misused. I'm going to redirect this question to Jamie, our newish engineering manager for accessibility, for further thoughts/delegation. Flags: needinfo?(dbolter) → needinfo?(jteh) There are two parts to "inheriting" OS accessibility functionality: 1) whether the OS implementation of that functionality actually has any impact on Firefox and 2) whether we respect the OS accessibility settings. They are related, but different. 1. Because Firefox renders pretty much all of its own widgets (we don't use native OS widgets), we don't just get most visual accessibility tweaks from the OS "for free". For example, if you turn on high contrast, without specific code in Firefox, it's not going to have any impact. (We do have specific code for that, but it's somewhat broken on the modern web as David noted. That's out of scope here, though.) 2. Despite that, once we do have code for a specific a11y tweak, we can still choose to tie that tweak to the OS setting; e.g. if the user set high contrast in Windows, let's turn on Firefox high contrast. So, in talking about functionality to enlarge/shrink the chrome, we need to consider two things: 1. Does Firefox even support this at all? I'm not sure of the answer to this question. Certainly, I don't think we get this for free from the OS, unless they're running magnifier or similar (overkill for many users), and even if they were, it would be less optimal (pixelation, etc.). 2. How does someone enable it? here, you could either say "there's an OS setting for that and we should respect it", "let's add a WebExtension API", or both. I think we need an answer from the reporter as to why, for example, the Windows 10 Settings -> Ease of Access -> Display -> Change the size of apps and text on the main display isn't sufficient. And if the answer is that there's a desire to make the Firefox UI bigger but not other things on the system, why? The other thing to keep in mind, though, is that the needs of users with vision impairments are *incredibly* varied. It's possible that respecting OS settings just doesn't give some users the kind of customisation they need. High contrast is a good example of this. In Windows, it's more or less an on/off setting, but the most comfortable implementation depends on the user's needs, and on/off just might not be enough to provide for this. In those cases, allowing add-on authors to customise this makes a lot of sense: we can't implement settings to suit every possible need, but if add-ons have the power to do what is needed, we can still "help" those users. NI Eitan because he'll probably have some additional thoughts and his expertise/context in this area is far greater than mine. Flags: needinfo?(jteh) → needinfo?(eitan) The case (sales-pitch) for the feature It's desired and useful Until the end of XUL add-ons, Theme Font & Size Changer was a popular add-on maintaining 100K+ users year after year and it was a featured add-on several times. Enlarging the UI was my concept back in 2005 and no one wanted to touch it because they didn't see a need or use for it ("the OS does that" was one excuse). Baris Derin eventually developed it. I am legally blind but I do not use (many) Windows accessibility features because they're not great and I have developed content for the masses and not just for those with disabilities and so I need(ed) to see things as they did even if it meant struggles for myself. I've received many emails over the years from users with visual impairments, elderly individuals, and others thanking and praising us for the add-on. When the add-on worked properly, the reviews on the add-on's page were very positive and appreciative. Extra appeal While it was never intended, Theme Font & Size Changer became very popular with general Firefox users too (with no visual or other issues), who used HD large screens, dual monitors, and Hi-Res settings overall on various monitors. I myself use a 32" TV as a monitor. For what it's worth, layout.css.devPixelsPerPx isn't a good alternative since it enlarges everything. It's doable Vivaldi implemented UI scaling (as a default feature) and touts it as a feature (we suspect as a result of Theme Font & Size Changer's popularity, reviews, and usefulness). I've never looked into it and I don't have the expertise to anyway, but I believe that Vivaldi uses Chromium so perhaps looking into it would be helpful for implementing the feature into Firefox. I know that the number of users of accessibility features, add-ons, apps, etc are low in comparison, but, we all still try to take care of users with greater issues who are simply trying to use the Internet with fewer struggles. This feature help with that. And like I said above, it appeals to different Firefox users for different reasons. Thanks Ken for all of that context, that is very useful. Some unordered thoughts: 1. Ideally, yes.. "the OS does that" should be good enough, but it is pretty obvious that many users are introduced to large font UIs through extensions like Ken's, and that is a good thing. 2. I'm not sure the best namespace to fit this in, but I think this would be useful both as an API and manifest key for lightweight themes. 3. Some thought needs to be put into the max font size, since at some point it will severely break the UI and not leave the user with an easy way to undo it. 4. Currently, Firefox's UI is pretty bad at scaling the icons along with the fonts. That is unfortunate since we rely on visual language much more than text in the UI. It would be cool if some work was put into icon scaling. Flags: needinfo?(eitan) Assignee: ntim.bugs → nobody
https://bugzilla.mozilla.org/show_bug.cgi?id=1347169
CC-MAIN-2020-10
refinedweb
1,480
59.64
Hi, y'all, I'm working on a project which is essentially converting a rotary phone into a smart home device. I've got the dialer and hook circuits up and working with my Uno Wifi Rev 2, but I'm running into some real issues with the ringer. I've been referring to this tutorial and this one for the most part, but they're kinda sparse as far as fine details on how they got their ringers to work. I've created an electromagnet using magnet wire, and I can ring the bell by just connecting the the electromagnet to an 9v battery. I've tried using an l298n driver to turn the magnet on and off, which is what the person in the first tutorial did, but this doesn't seem to do anything (code below). I've also tried (very naively) to use a relay module I had lying around to simply turn power on and off to the magnet, but that doesn't do anything either, it's very likely relays don't work the way I think they do. I'm using a Keyestudio brand module that I got with a sensor kit, and I've got the +9v of the battery plugged into the middle port and the magnet plugged into the right port. The other wire of the magnet and the battery's GND are plugged into GND on my breadboard. A couple pieces of information that may be helpful, I've seen other phones which have two electromagnets which pull the mallet back and forth. My phone had one electromagnet (which required too much power, so I made a homemade one) and one regular magnet. The regular one keeps the mallet in place until the electromagnet is turned on, at which point it will smack one bell. Then when the magnet is turned off, the mallet returns to its original position and smacks the other bell. At least this is how I think it works. I don't think I need to reverse polarity on the magnet, but I could be wrong. Also, I've connected my 9v battery and the magnet to a breadboard, expecting the mallet to stand attention, but I had to mess with the magnet's wires a bit to get it to turn on. Maybe the 28 AWG magnet wire is too thin for my driver and relay, and it's not making a good connection? Finally, it's only allowing me to have two links in this post, so I'll comment with some more links. I'm a complete novice, so I'm at my wit's end at this point. Can y'all think of anything I could try? Thanks in advance. #include "Arduino.h" void setup(void) { Serial.begin(9600); Serial.println("START"); pinMode(6, OUTPUT); // Input 1 pinMode(7, OUTPUT); // Input 2 } void loop(void) { digitalWrite(6, LOW); digitalWrite(7, HIGH); Serial.println("ON"); delay(1000); digitalWrite(6, LOW); digitalWrite(7, LOW); Serial.println("OFF"); delay(1000); }
https://forum.arduino.cc/t/rotary-phone-ringer/915619
CC-MAIN-2021-49
refinedweb
506
68.1
On Wed, May 30, 2012 at 02:22:00AM -0500, Jonathan Nieder wrote: > Thibaut Girka wrote: > > > Well, no, after a quick inspection, it appears the test behaves correctly. > > Then, I have no idea why it would fail. > > Thanks. Ok, a new test to try: > > # get the source: > git clone git://sourceware.org/git/glibc.git [...] > If it reproduces the problem, then that would mean this is not Debian- > specific, so please write to libc-help@sourceware.org in that case to > request advice[1]. (If we are lucky, someone might recognize the bug or > know of some command like "strace -f" or patch that could help track > it down.) I'll try that. In the meantime, I've came up with a simpler (only one spawner, no signal handling) test (attached) that exhibits the same issue. It appears that, for some reason, at some point in time, the threads aren't cleaned up anymore (just monitor /proc/$pid/task when the test is running), even though the pthread_join calls succeed... This isn't always reproductible, but it happens fairly often. Regards, Thibaut Girka. #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <sys/types.h> #include <unistd.h> #define NB_THREADS 20 void *thread_func(void *arg) { return arg; } int main(void) { unsigned int i = 0, j; void *result; pthread_t threads[NB_THREADS]; printf("Please watch /proc/%d/task as I'm running!\n", getpid()); /* Pre-spawn NB_THREAD threads */ for (j = 0; j < NB_THREADS; j++) { if (pthread_create(&threads[j], NULL, thread_func, (void *) j) != 0) { perror("pthread_create"); return 1; } } /* Now, close one thread, spawn another. FIFO style. */ while(1) { if (pthread_join(threads[i % NB_THREADS], &result) != 0) { perror("pthread_join"); break; } if ((unsigned int) result != (i % NB_THREADS)) { printf("Invalid reslut: %d!\n", (unsigned int) result); break; } if (pthread_create(&threads[i % NB_THREADS], NULL, thread_func, (void *) (i % NB_THREADS)) != 0) { perror("pthread_create"); break; } i += 1; if (i % 50000 == 0) printf("%d threads created\n", i); } printf("%d threads created\n", i); return 0; } Attachment: signature.asc Description: Digital signature
https://lists.debian.org/debian-glibc/2012/05/msg00164.html
CC-MAIN-2015-32
refinedweb
331
76.42
Only Get Non-Alpha Pixels in an Image This week, I found myself wanting to do some computation over pixels in an image. This image, in fact from PIL import Image im = Image.open('images/Abomasnow.png') im In particular, I wanted to run K-means clustering over the image to determine what the 3 most popular colors were– visually, I expected to see something like green, white, and maybe pink/gray(?) A First Pass I load my Image object into numpy.array that sklearn can eat import numpy as np arr = np.array(im) It’s a 200 by 200 image, so this should work pretty quickly. arr.shape (200, 200, 4) Building and training the model is easy enough. We want a KMeans object instantiated with 3 means. from sklearn.cluster import KMeans model = KMeans(3) Next, we’re going to take our 200 x 200 x (RGB) values and put them into one, 40000 x 3 matrix (pixel location doesn’t matter for K-means) reshaped_arr = arr[:, :, :3].reshape(-1, 3) reshaped_arr.shape (40000, 3) Fit the model model.fit(arr[:, :, :3].reshape(-1, 3)) KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300, n_clusters=3, n_init=10, n_jobs=None, precompute_distances='auto', random_state=None, tol=0.0001, verbose=0) Aaaaaand our means model.cluster_centers_ array([[105.41553813, 132.43644571, 131.09289617], [232.71566397, 231.75916993, 235.93683444], [ 1.47778587, 1.78674436, 1.75863074]]) We’ve got gray Image.new('RGB', (300, 100), color=(232, 231, 235)) Greenish Image.new('RGB', (300, 100), color=(105, 132, 131)) And… black? Image.new('RGB', (300, 100), color=(1, 2, 2)) What happened? Did You Catch the Spoiler? Let’s go back to our image array. We had a 4th value in our 3rd dimension. The first 3 account for R, G, and B. But the fourth represents alpha or the transparency. arr.shape (200, 200, 4) The image printed out nicely enough when we loaded it up im But if you were to open it up in some alpha-channel-aware software, like paint.net, you’d see that the background was actually transparent. Image.open('images/alpha_channel.PNG') Indeed, if you inspect a random pixel in the upper-left corner of this image, you’ll see that it’s got a 0 value for its alpha channel at the end, but critically, it gives us 0, 0, 0 RGB values. In other words, numpy thinks that like 40% of this picture is pure black. arr[10, 10] array([0, 0, 0, 0], dtype=uint8) Clearing out the Clear So we want to re-run our clustering algorithm, this time only considering pixles with the max value for the alpha channel, 255 And so we’ll line all of the pixels up once more (including the alpha channel for the next step) all_pixels = arr.reshape(-1, 4) all_pixels.shape (40000, 4) Then some basic numpy array filtering reveals that my 40% was actually closer to like 60-something just_non_alpha = all_pixels[all_pixels[:, 3] == 255] just_non_alpha.shape (18747, 4) Refitting the model, we get new centers. Promising. model = KMeans(3) model.fit(just_non_alpha) KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300, n_clusters=3, n_init=10, n_jobs=None, precompute_distances='auto', random_state=None, tol=0.0001, verbose=0) model.cluster_centers_ array([[182.57885015, 183.38536135, 194.31147541, 255. ], [252.58630872, 252.45704698, 252.62241611, 255. ], [100.3142406 , 130.10723514, 128.00387597, 255. ]]) Again, we’ve got greenish Image.new('RGB', (300, 100), color=(103, 130, 129)) Gray Image.new('RGB', (300, 100), color=(182, 183, 194)) … and very, very white. Image.new('RGB', (300, 100), color=(252, 252, 252)) Oh well. The dude’s a snowman. Go figure. At least this one makes sense.
https://napsterinblue.github.io/notes/python/numpy/filter_alpha_points/
CC-MAIN-2021-04
refinedweb
623
66.94
Welcome to WebmasterWorld Guest from 54.196.74.142 How do you all manage your warehouse/shipping operations? Our business is growing rapidly and we are feeling the pains. We seem to have issues with sending out the proper products. Our products are all very similiar and can be confusing. Say someone orders : 3 widget a's size 5 3 widget a's size 3 4 widget b's size 5 . . . It can be a long confusing list and we pick the stock and box and there are quite frequently errors. Our process is . 1. Print all orders 2. Take 1 order and pick products 3. Box products 4. Label and close box 5. Move on to next order Anything anyone does to ensure quality shipments would be great. Thanks Besides that, the process you listed cannot really be changed so much. My biggest problem is still getting people who can read and comprehend the english language. High school kids have a huge problem with that. I have a fellow here who speaks no english, and he does much better than any high schooler. Go figure. The other big problem is finding people who actually care. I haven't found one yet. I'm a small town, resources are limited. I have though about bar coding my inventory, but it won't help keep products from going into the wrong package. That solution does work for large assembly line warehouses, but for small shops like ours the best solution is to pay attention. I once threatened to withhold payday earnings when mistakes occurred. I doubt that the practice is legal, but the threat helped for a while... mistakes dropped dramatically, how-to questions increased. Regular training might help, with a focus on the most frequent problems. I have thought about bar codes, but cant wrap my head around how this works and how it would help. I was thinking of a QA process ... like check every 10th box ... but this could be very time consuming. I had thought about putting a process in place where the packager had to highlight each line item being boxed so I KNEW they actually read it. There has to be some way. My problem is the packers want the money but not the work. All the technology in the world won't help you if you don't have accountability in your system - people need to help to account for their errors. Having at least two people involved helps a lot. Have one person pick and one person pack each order. And require that the packager has to verify each order, line by line. Have you considered a monetary incentive? Start with a bonus pool of money - for simplicity let's say $200/month. During the month, anytime an order is shipped incorrectly, you deduct YOUR cost for fixing that mistake from the pool. For example, if a package was mis-shiped and now you have to re-send the right item (call it $5.00 for shipping) and send a pre-paid return label to get the wrong item back (call it another $5.00) then you deduct the $10.00 from the pool. If it was a Next Day Air package, then you deduct the Next Day Air charges for the replacement package (call it $30.00) and the return (call it $5.00 for GND). Whatever is left in the pool at the end of the month is paid as a bonus to the employee(s). In this case, the two mistakes would have removed $45.00 from the pool, giving them a $155.00 bonus. Although they ARE paid to do the job right in the first place, it's obviously not happening and it's costing you money. Letting them share in the success of getting it right and having the cost literally come out of their own paycheck will reduce errors faster than you might imagine. So you might as well give the money that you are paying to UPS/FedEx to your employees instead. And, you'll increase customer satisfaction as well. As a side benefit, this process will also help catch the situation where the customer receives the $200.00 Widget B instead of the $15.00 Widget A that they ordered and never call to "complain" about getting a much more expensive item. Good luck! So we put our heads together and custom wrote our own WMS software package. We do lots of things wrong at our company, and we still have many areas to improve upon, but I have to say that our WMS is now world class and I'd put it up against any system out there. It's a whole lot easier process to implement than you might think. But the key is to think the whole process through and study, study, study. We spent a month putting together a system on paper and perfecting it. The actual coding and conversion to the new system took all of about 2 weeks. We started out by laying our warehouse into grids 25' x 25' square. Think of a chart with 10 rows on top and 6 down the side. The rows on top are numbered and the side rows are lettered. So you wind up with location C5 somewhere out in the middle. We further refined the 25' x 25' locations by isles, then by 4' x 4' locations within the isle, and then by shelves. What you end up with is a location that looks like B1L1-C5R2-Z4S3A. That decodes to Building 1, Level 1, Sector C5, Row 2, Zone 4, Shelf 3, Shelf Section A. Each location is barcoded with laminated labels on each shelf section. It might look complicated, but it really isn't. We can take a new picker and after about 5 minutes of training give them a location and they can walk to within arms length (4'x4') of the item to be picked.! Each item is then put away and scanned into a location. The WMS software keeps up with every item in inventory and where it is located. No more "lost" inventory! Our pickers carry wireless scanners that have the orders automatically fed to them by our invoicing software. Orders are assigned to a picker and the scanner displays the items to be picked, which is sorted by the shortest distance around the warehouse. When an item is scanned by the picker, it is "grayed out" on their pick list. When the assigned group of orders is completed, they carry the picked items to a packing station. The packing station also scans each item in similar fashion as it placed into a box. The packing station uses recessed table top scanners, same as Wal-Mart uses. Corded scanners are used as backup for large, cumbersome items. Overhead of the packing station we have motion-detecting video cameras that record each order as it is being packed. When the packer scans the order to begin the process, it time-stamps the video with date and order number. The video is fed to a DVR with 750 gigs of storage, enough for about 45 days worth of shipments. The video serves 2 purposes: One, it holds the packer accountable for making sure sufficient packaging material is used in each shipment. Two, we have video proof that each item was in the box when it left our warehouse. Our customer service reps have access to the video and they can pull it up by simply typing in the customer order number. Once the order is completed at the packing station, a barcode label is generated that contains the order number and packing station id. The label is placed on the outside of the package(s). The packaged order then moves to a shipping location which utilizes software to determine which carrier (UPS, FedEX or USPS) has the best rate for that shipment. The person manning the shipping location scans the order barcode (generated at the packing station) and that pre-populates the shipping software with the customer name and address. So that is it in a nutshell. Our order accuracy has increased from a dismall 95% to an outstanding 99.9%. Our inventory shrinkage is almost nil, and both employee morale and customer satisfaction is greatly improved. My only regret is that we didn't do it sooner. [edited by: WiseWebDude at 4:48 pm (utc) on April 6, 2007] We designed and wrote our system 4 years ago. Our warehouse and # of employees have grown and we are in the process of specing out V2. A few questions for you, if you don't mind. You said: When an item is scanned by the picker, it is "grayed out" on their pick list. When the assigned group of orders is completed, they carry the picked items to a packing station. We only show pickers one item at a time and have a "packed" and a "previous" button. We're using Symbol MC9000s [symbol.com...] I can't picture your UI. Can you elaborate?! You require a scan at pick time, correct? Do you require a product scan at pack time and do you require a box scan at pack time? Thanks! <<I can't picture your UI. Can you elaborate? >> The scanners we are using look very similar to the ones you posted a link to. They have a color screen and run a browser window over Windows CE. When a picker is assigned a group of orders, a pick list is presented on screen. I think the list can contain around 10-15 items before a "next" or "previous" button is needed. <<Are you labeling on a case or product level?>> We label down to the product level. Our sales rarely involve case quantity, so we are unable to get by with just labeling the cases. <<Do you require a product scan at pack time and do you require a box scan at pack time?>> The packing station must also scan each item. This is a form of double-check against the pickers and it also insures the packers do their job correctly when assembling the order. We have 19" flat screen monitors recessed into the packing tables at each packing station. A piece of plexiglass over the monitor protects it from abuse. When a packer scans an order to begin the packing process, the monitor displays the items to be packed and each item is "grayed out" from the list after being scanned into the box. When the list is complete, the packer inputs how many boxes were needed for the shipment and then a "completed order" barcode label(s) is automatically generated to be placed on the outside of the sealed box or boxes. The order then moves to the shipping station where the "completed order" barcode is scanned. It then populates the shipping software with customer shipping information. They have a color screen and run a browser window over Windows CE. We do a single picker/packer. The system spits out a list of boxes to make and a sticker for each box. The handheld routes the picker and tells him what item to pick and what box to deposit it in. (items are picked directly into the box we will ship in). Verification is done via weightcheck at scan time. Unfortunately weight check doesn't catch errors in color and often miss errors of one or two sizes and those now compose the majority of our errors. If we tighten up our error threshold we get too many false positives because are items do vary a few percent in weight. We label down to the product level. Our sales rarely involve case quantity, so we are unable to get by with just labeling the cases. We ship at a product level as well. We don't label at that level because we often receive by the container but don't open all the boxes until they are moved from overstock to picking stock. We currently only scan at pick time so we can get away with it. We originally considered using a picker and packer system with the same fundamentals as yours and we again are considering it. It certainly is the more prevalent method. Can I bug you on the phone at some point about the issues you've had and best practices you've determined? How do you all manage your warehouse/shipping operations? Outsourcing would be another option. We do quite a bit with pick and pack operations and we've kept some of it in our warehouses and then we've contracted out the rest of it. Overhead can get quite hefty in a pick and pack operation if you don't have all of your ducks in a row. Its almost better to alleviate that stress and let a third party who specializes in it deal with it. I've found that "everything" has to be labeled, everything. If it isn't, you leave the door open for assumptions and thats when things go wrong. 1) Get your software to print batch pick tickets, grouping similar locations where possible. We picked 16-20 orders at a time using a wheeled cart with shelves and a plastic basket for each order. This was MUCH more efficient than sending a picker after each order, and was even faster when high volume in one item allowed 20 orders to be picked from a single location in a few seconds. The picker would take the baskets to the packing line after completing the pick run. Obviously, this won't work for very bulky merchandise. 2) Put complementary items next to each other in the warehouse, e.g., print cartridges near printers. This makes for faster picking on many orders. 3) Put very similar-looking items in DIFFERENT warehouse locations. It seems intuitive to put all the items from one manufacturer next to each other, but when the products look the same and have only a few characters different in their description, it's easy for the picker to grab the wrong item. Of course, if you are scanning bar codes during the pick process you should catch the error anyway. All the technology in the world won't help you if you don't have accountability in your system - people need to help to account for their errors. Totally agree.. One thing to watch out for... This is how far an employee from hades will go. One of the picker/packers was forging the team leader's initials on the packing slip. Another suggestion... Reading comprehension tests. This really helped to identify employees that are predisposed to getting the order wrong.. We pay by the piece exclusively. Everyone logs on as themselves to ensure they get paid. We deduct from the packers paychecks for every mistake they make. They hate when they get hit by deductions but there is no issue with not caring about accuracy or output. It doesn't cure the problem, but it helps to make sure your employee can do the job properly in the beginning rather than find out in the middle and the end part. I was thinking about scanning the invoice to see what process the order is in for customer service reasons. For the products we sell only 30-40% have upc codes. We label the cases of inventory with our own barcodes when they come in. To pack orders, the pickers have handheld barcode scanners - they scan the pack slip, then each case they remove the product from - that gives us an electronic record of the pick/pack process for each pack slip. All- I think one common experience for us all is that as our volume goes up, our initial reaction is to create a pick/pack method that is fast and requires the fewest people. But, as you get bigger, you are forced to trade speed/efficiency for quality/accuracy. Quality/accuracy costs money and is slower. You have to be prepared to slow your process down for improved accuracy - that means more people or better automation. The second thing that needed to be fixed was warehouse culture. A new warehouse started with a "don't care" culture that caused too many mistakes. A new manager hired as a "firefighter2 moved things too far into a "blame culture" where mistakes were covered up and became difficult to rectify. We have oour own bespoke fulfilment system, producing pick lists, despatch notes, auto charging etc but would be cool to get the stuff scanned at the picking stage at least (would help eliminate sending very similar but wrong items!) I know SQL/VB/.Net etc but have never worked on mobile devices - what is the theory - are they just accessing a browser based intranet style system that is hooked direct into your back end databases? Or do they have local data storage and synchronise across? Any pointers on this gratefully received! We use ipaqs with an add on barcode scanner, wifi and battery pack from symbol. Hardwarewise, we need to replace the trigger switches on the ipaqs fairly regularly, but softwarewise it couldn't be easier. We just have a web interface set up on a local server and run that in a browser on the handheld. Something different we do that I haven't seen mentioned yet is that we have unique barcodes on each unit - even if they are the same item. This allows us to verify quantities properly (each unit needs to be scanned) and also track things like age and returns more accurately. Others have mentioned case qty. We stock and sell both individual and case quantities, but have associations set up so that if we sell more individual items that are in stock, the computer will order a case to be repackaged as individual items (our shopping cart also says in stock instead of oos for these items).
https://www.webmasterworld.com/ecommerce/3303200.htm
CC-MAIN-2017-30
refinedweb
3,003
73.17
You're enrolled in our new beta rewards program. Join our group to get the inside scoop and share your feedback.Join group Join the community to find out what other Atlassian users are discussing, debating and creating. We just upgraded Jira/Plugins and are now seeing the parameter map not being updated with the current action. We are using Scriptrunner and Bob Swift Create on Transition in our workflows. In our Project issue type we use the Create on Transition to create Epics and link them to the Project issue. This was working in production prior to upgrade. I can create an Epic from the create menu without issue. When creating from the Project it fails due to we use the parameters to validate the link is being created as part of the action. We are using the Action Context in our Epic workflow to validate a link has been created (or will be as part of the creation). def request = ActionContext.getRequest() if (request) { def params = request.getParameterMap() When Project issue is transitioned to Active, we create the Epics. When I view the parameter map from this creation it is showing the Project transition action parameters, not the Epic creation parameters. It appears that the create action from a post function is not updating the action context. I know this would be the case if the create was triggered from the REST API. So either the post function create was changed to use REST, or I am missing something entirely. ||Application||Previous Verison||New Version|| |Jira Software|7.3.8|7.6.2| |Bob Swift COT|5.8.0|6.1.0| |Scriptrunner|5.2.1|5.2.2| I have upgraded just the plugins in a test environment; everything works correctly (Epics are created from the postfunction) so it does not appear to be upgrade related. Either its Jira itself or something else - at a loss. Thanks! Jodi Hi Jodi Avery, As discussed in SUPPORT-459, please raise a request with Atlassian support who will be able to provide you the changes which have been performed in JIRA. You can also add us to the request which you are creating if in case the Atlassian needs any information from our side, we are happy to help you in this regard. Thanks, Vijay Ramamurthy.
https://community.atlassian.com/t5/Adaptavist-questions/Post-Function-create-issue-no-longer-creating-Action-Context/qaq-p/710187
CC-MAIN-2021-25
refinedweb
386
64.71
RAII guard for solver stack. This object implements a rudimentary form of SMT transactions. The constructor starts a new transaction by pushing a new level onto the specified solver (if the solver is non-null). The destructor pops one level from the solver unless this object is in the isCommitted state (see commit). This guard object makes no attempt to ensure that the level popped is the same as the one that was initially pushed by the constructor. Definition at line 111 of file BinarySmtSolver.h. #include <BinarySmtSolver.h> Constructor pushes level if solver is non-null. It is safe to call this with a null solver. Definition at line 118 of file BinarySmtSolver.h. Destructor pops level unless canceled. Definition at line 125 of file BinarySmtSolver.h. Cancel the popping during the destructor. Definition at line 136 of file BinarySmtSolver.h. Whether the guard is canceled. Definition at line 141 of file BinarySmtSolver.h. Solver being protected. Definition at line 146 of file BinarySmtSolver.h.
http://rosecompiler.org/ROSE_HTML_Reference/classRose_1_1BinaryAnalysis_1_1SmtSolver_1_1Transaction.html
CC-MAIN-2019-26
refinedweb
166
62.14
Overcoming Fear of package.json — Building Server-Side JavaScript Apps You can Follow me on Twitter to get tutorials, JavaScript tips, etc. Setting Up Development Environment Setting up a Development Environment makes server-side applications distinct from their front-end counterpart. It’s easy to get lost especially if you’re working with libraries such as React for the first time. We learned that in post-ES2015 era even JavaScript, a language that was primarily invented as a front-end development tool, is moving to the server-side. I’d say that this is the prevalent bias in the industry that started to become evident around 2016. We must understand how server-side JavaScript works. I know this creates a bit of a hassle, but it’s sort of a necessary step. Because this is the future of JavaScript application development. Most likely that future is right now. Build Environment We can refer to development environment as “build” environment interchangeably. Because essentially a development environment is a system whose ultimate purpose is to provide the means for building your application. Some programmers simply say things like “How did you build your application?” or “What are your favorite dependencies?” referring to your custom build. You can use node, yarn and webpack packages to build your app. But we’ll take a look at how to use them a bit later in this tutorial. Because with node and npm we are now working on server-side of things you will use these tools to install and uninstall various packages on demand. This conglomerate of various packages is what determines the essence of your build. And this “how” is what many JavaScript developers who came from traditional pre-Millennial background are not familiar with. Thankfully after parsing through the previous tutorials on my Medium account we now understand the process at least at its basic. It’s not so hard after all is it? The next natural step that completes setting up a development environment for working with React (or other server-side JavaScript libraries and/or frameworks) is setting up its configuration. Build configuration drastically varies from one person to another. At one company things are configured are a certain way. Others prefer a different setup. These decisions can be often made mutually by an entire development team. However, when working with React understanding package.json configuration file is a must at the very least. There is no way around it. So let’s take a look. Configuring Your Build Environment With <package.json> If you’ve been struggling with setting up React and gave up at configuration file this might be the place at which you and many JavaScript programmers turn to Vue.js framework. Because it is easier to set up. But don’t give up so easily! Once you understand package.json, choose and set up the right packages for your application building React projects will become second nature. In the olden days we typed JavaScript in a text file and it just worked. But it is so much worth it walking the extra mile to figure this out now and ease into the world of React. This guide here will help you get started. Again, I cannot possibly describe every nook and cranny of this process. In reality the only way to truly understand and get into server-side builds is to spend many hours actually working with the command line. In fact, a lot of the time when being introduced to a build configuration on a project you’ve never worked on before, you may feel slightly disoriented. What are all those packages? What do they do? What concrete functionality or features they add to the application? To determine a list of all packages you want to use in your project there is a package.json file. This file shows a list of nested dependencies. Why are they called this way? Well, every single library you add to your application (usually not written by you) will literally make your own application depend on it. That might sound worrying at first, just by reading that word. And yes, in many cases it is. What if the version of the installed dependency changes? What if it breaks core functionality that your code already depends on? It will break your build. For this reason keeping an old version of a library is a common strategy among developers as tempting as it may be to always upgrade to latest. Which, in my personal opinion is what you should be doing. We’ll see how yarn solves this problem a bit later on in the book. But for now, let’s take a look at how to properly set up package.json file for your development environment. Dependencies can be frightening. Because ultimately these packages often continue to change with each and every new release. And yes you can write your own code that accomplishes the same task and stop worrying! But reality is that most developers download about 80% of their base code from Node package repository. With so many great and well-established libraries (axiom for working with relational database) already written all you have to do is include one and start using it. Of course all of this means that choosing the best packages is essential. And as you dive deeper into the world of professional web development you might just find out what they are. Example of <package.json> Configuration File In this section we’ll take a look at package.json file and break it down into understandable parts. It follows the JSON format notation, which means every key/value pair must be specified in quotation marks, and separated by a colon. Below is an example of one possible build configuration. The major differences between different package.json configuration files for different builds is in what’s specified under “scripts” and “dependencies” keys. Each build is different. The example shown here is by no means the absolute way of setting up your project. It’s only somewhat of a bare minimum config. You may or may not need other dependencies. Treat it as a mere first time example. Let’s take a look at one potential scenario. Basic details are stored first: your project name, version number and description. You can also specify license of your module. Do not use spaces in “name”. You can use either dash or underscore to separate multiple words. { “name” : “module-name”, “version” : “1.0.0”, “description” : “Amazing project.”, “license” : “MIT”, Next, branch out into a nested JSON to specify author of the project: “author” : { “name” : “Amazing Programmer”, }, In package.json file “keywords” are used for helping people find your package. Unfortunately at the moment of this writing keywords are case-sensitive. For example React is not the same as react. Most packages are specified using lower-case characters. “keywords”: [ “react”, “redux”, “example” ], Main JavaScript file for this project. When calling require({ module-name }); in node, this is the actual file that will be included: “main” : “index.js”, Homepage of your project: Specify your repository type and URL address: “repository”: { “type” : “git”, “url” : “" }, The “dependencies” key is perhaps the most important value in entire package.json file. It includes dependencies. Other packages your module relies on. Each dependency must also specify version number. There are a few different version specifiers you can use: I’m not saying your project will need all of the dependencies listed in this example. But it’s not uncommon to have at least most of the babel packages installed. If your project depends on redux and router, then you might want to add them as well: “dependencies”: { “axios” : “0.16.1”, “babel-core” : “6.24.1”, “babel-loader” : “6.4.1”, “babel-polyfill” : “6.23.0”, “babel-preset-es2015” : “6.24.1”, “babel-preset-react” : “6.24.1”, “babel-preset-stage-3” : “6.24.1”, “babel-runtime” : “6.23.0”, “clean-webpack-plugin” : “0.1.15”, “concurrently” : “3.4.0”, “css-loader” : “0.28.0”, “dotenv” : “4.0.0”, “prop-types” : “15.5.8”, “react” : “15.5.4”, “react-dom” : “15.5.4”, “react-redux” : “5.0.5”, “react-router” : “3.0.1”, “redux” : “3.6.0”, “redux-thunk” : “2.2.0”, “webpack” : “2.4.1”, }, The more packages your module depends on the more potentially unstable it might be. Simply because there is no control over changes introduced by developers of those packages at a later time. For this reason ^ is the safest option for specifying version number, limiting it to minor version upgrades only. You can “yarn” all dependencies together. Just run yarn install from the root directory of your project. Yarn will install all dependencies from this list automatically. So you never have to do it by hand for each one. Next, we will explore the “scripts” key which includes instructions for which scripts to run in which situation. Not all of them are required or even needed. Each case is explained by a unique key. For example on start you can run node server.js. But there are a few other cases: “scripts”: { “start” : “node server.js”, “test” : “”, “dev” : “”, “node-dev” : “”, “node-prod” : “”, “build-dev” : “webpack — config webpack.dev.config.js”, “build-prod” : “webpack -p — config webpack.prod.config.js”, “test-watch” : “yarn test — — watch”, }, Finally, we will explore one key. Babel has a special keyword reserved for itself. Here you can specify its presets. “babel”: { “presets”: [ “es2015”, “react”, “stage-3” ] }, } If you don’t need to use Babel in your project, you can skip this key altogether. It looks like our configuration file is ready. When you yarn all packages in package.json file are downloaded, installed and linked automatically. You never have to worry about installing each one by hand. Just make sure to include them here. There are a few other keys in package.json file you can use, but at this time we will not go into those details. We’ve just created a basic configuration that should serve as a starting point for creating your build environment. After all, it’s not so complicated. When I started programming in React, I was hesitant to even think about what these configuration files are used for. I took them for granted, called yarn command to bundle them all together, and it still worked. You can hide this way but not for long. Many web developers do the same thing. If it works why understand it? But working on a real project you will eventually run out of excuses and will have to understand what each part does. Hopefully this chapter shed some light on package.json file and helped you become more comfortable with building server-side applications. We created our package config. Now what? You can import and export packages into other projects. In the following section we will learn how to do it. Importing And Exporting Local Packages You can think of jQuery as a dependency in earlier JavaScript programs. Here, it’s the same thing. We’re just importing and exporting packages in a different way. Only we’re no longer using the <script> tag as before. To exactly the same effect. The JavaScript code is “included” much like it was with the script tag. It’s just the inclusion has been moved directly into your JavaScript application. Which is a really great idea. And not only that, it is possible to import into your main program from multiple .js files. This not only makes your code look cleaner but forces you to think about building your application in a modular way (consisting of many separate modules.) This tactic is especially common of large projects usually where many people work on the same application. But from the point of keeping your project organized it is an excellent idea. Even if you’re working on your project alone. There are thousands of libraries written by open source developers all over the world. So you don’t have to reinvent the wheel. Once installed they must be imported into your project. You can pull any one of the existing packages as long as you have Node installed. It’s that simple. There is nothing to download manually. You just execute node/npm commands. Add its filename to the list of dependencies in package.json file and you’re ready to start. The yarn package can also help you tie all of your dependencies together without much grief. Packages like yarn, however are used globally on the server. And local packages must be imported into your project using the import keyword. We’ve already installed yarn globally in one of the examples prior to this section. Let’s now take a look at how include/export keywords work. We’ve already established that Instead of using the proverbial <script> tag local packages are added via your main JavaScript file using import directive. This is the new keyword in EcmaScript 6. It helps us organize our application in a modular way. But the package containing the classes or functions that define functionality of that package must also export that class from your main script file. Let’s take a look at this pattern. For example, I was working on a <GutterPane/> component in my React application. At first, I wrote it into my main application file as a JavaScript class. But, in obedience to global modular design in my application, I refactored GutterPane into a separate file called <gutterpane.js>. The following example also provides a few other common cases of using import keyword in a basic React application. index.js — main application file now imports my GutterPane component: import React from “react”; import { connect } from “react-redux”; import { Link } from “react-router”; import { push } from “react-router-redux”; import GutterPane from “gutterpane”;// You can now use the imported <GutterPane/> component // in your React application Here, gutterpane is a reference to gutterpane.js file. The <.js> extension is optional in import directive. And finally in my GutterPane file (gutterpane.js) I need to make sure to export the class. Skipping this step will not make this class available in my application. It’s just as important: gutterpane.js file containing <GutterPane/> component definition: export default class GutterPane extends React.Component() { render() { return ( <div className = “GutterContainer”> Sidebar gutter container </div> ) } } Here I am also using default keyword. It lets my app know that this is the only class being exported from this <.js> file. You can create your own custom components or download and export packages created by the web development community. You don’t always have to write your own code. Chances are that somewhere out there a package already exists that accomplishes a particular task. We now know how to install and include packages in our project. Well, that’s great. But let’s continue setting up our development environment. We’re just one step away from starting to write our first React application. Finishing Setting Up Development Environment There are plenty of ways in which a development environment can be configured. This is somewhat of a habit you develop over a long period of time working with different tools. For this reason there isn’t any one single solution. In this section, one potential setup will be shown that worked for me while developing a web application for one of my employer’s clients: the “GoodYear” tire company. Our built consisted of node, babel, jsx, yarn and webpack. I know it’s a handful, and it probably makes no sense trying to grasp them all in one moment if you’ve never worked with them before. Understanding what each one does can only come from experience when you’re actually using them. This section demonstrates several server-side commands you can use that will guide you toward getting one step closer to setting up a development environment. But it is still up to you to get familiar with alternative builds and commands in the Node toolset. Just remember that there is no perfect formula. Some commands will overlap. For example, packages installed using yarn from package.json file may overlap packages installed manually by typing in commands into bash or command prompt. All this is part of a normal process. If you need to install a new version of a package, you can do it by hand. The same goes for uninstalling. What I am saying is that your build is a live ecosystem of packages and dependencies. Things change. They always do. The following is a potential set of commands typed in progression for installing various packages. I don’t know if you will or will not need them in your project. This log demonstrates what you might find yourself typing into the console during your casual setup procedure: npm install yarn — global npm install webpack@2.1.0-beta.22 — save-dev npm install extract-text-webpack-plugin npm install clean-webpack-plugin npm install dotenv npm install babel-polyfill npm install webpack-dev-server npm install -jsx npm install -S react-router npm install -S history@1 npm install prop-types npm install -g bundle-js npm install npm install yarn yarn install npm info webpack webpack — config webpack.dev.config.js Of course there isn’t a reasonable way to describe and explain every single package and configuration preference. Getting familiar with what packages you need for your project depends on making choices pertaining to your particular application needs. Building server-side applications isn’t a trivial process. And it is tempting to just go back to writing front-end code and forget any of this happened. But this is exactly the difference between back-end and front-end programming. Having said all this if you’re looking to grow your web development career, these types of things are an absolute must. In the industry, it is assumed that you have dedicated enough time on learning the command line tools and know installation process for some of the most common packages by heart. Yarn Yarn, yarn.lock and package.json are the files you will inevitably bump into while building your environment. Some packages automatically install yarn. In some cases, you have to install it manually. Let’s take a look at a real-world situation where we want to install TypeScript support together with a React app. Assuming Node.js and npm are already present on your local machine here’s an example of what a React and TypeScript installation might look like: Navigate to your project folder, for example: On Windows: C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\ On Mac/Linux, it could be: /Users/username/GitHub/ Or an equivalent folder currently linked up to your localhost environment via a web server like Apache, for example. Create a new project folder. In this case I’ll use: “react.typescript”. Navigate to this folder and execute the following command: npm install create-react-app This will add node_modules directory and all of its modules to our newly created “react.typescript” project folder. Alternatively, you can do a global installation using -g flag: npm install -g create-react-app On Windows, this will install node_modules to a folder similar to: C:\Users\Name\AppData\Roaming\npm\node_modules\create-react-app\… Creating the app We have just installed create-react-app package using Node package manager “npm”. We now need to use react-scripts-ts to create an application capable of compiling TypeScript. In the following example, replace “appname” with whatever you want to name your app: create-react-app appname — scripts-version=react-scripts-ts Installing packages. This might take a couple minutes. Installing react, react-dom, and react-scripts… Yarn will be automatically deployed to “yarn up” dependencies from your “package.json” file. yarn add v0.24.5 info No lockfile found. [1/4] Resolving packages… [2/4] Fetching packages… warning fsevents@1.0.17: The platform “win32” is incompatible with this module. info “fsevents@1.0.17” is an optional dependency and failed compatibility check. Excluding it from installation. [3/4] Linking dependencies… [4/4] ......followed by a long list of packages installed… Wait for a minute or so, while watching an ASCII loading bar going through [4/4] processes outlined above, until this message with additional tips is received: Success! Created appname at C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\react.typescript\appname Inside that directory, you can run several commands: yarn start Starts the development server. yarn build Bundles the app into static files for production. yarn eject Removes this tool and copies build dependencies, configuration files and scripts into the app directory. If you do this, you can’t go back! We suggest that you begin by typing: cd appname yarn startHappy hacking! Congratulations. You have just installed React with TypeScript support. Just one possible way to set up a development environment for a particular build flavor. Again, you can install yarn manually via npm at any time. But in this example create-react-app has already taken care of that for us. Babel Few command line commands to add babel to your build: npm install babel-core npm install babel-loader npm install babel-polyfill npm install babel-preset-es2015 npm install babel-preset-react npm install babel-preset-stage-3 npm install babel-runtime After running these commands you can be sure that Babel is installed on your local machine. As you may know, Babel is what provides transpilation from EcmaScript 6 back to EcmaScript 5. Your project is bundled into a single file in ES5 that modern browser can compile, even though the application was built using latest specification. Webpack and bundle.js A whole book can be written about Webpack alone. But basically it is one of the common ways server-side the application can be built on the server. It can even transpile your ES6 code to ES5 You can use webpack to bundle your project into a bundle.js file. This single file will contain source code of your entire application, regardless how many separate <.js> modules were used to create it. It is done this way because Babel will often produce EcmaScript 6 code not yet supported by all browsers. For example, as of this writing the ES6 import keyword wasn’t even supported in Chrome. Babel package “transpiles” that code back into ES5. Something that most browsers won’t choke on. But that won’t always be this way. Eventually Chrome and other browsers will have native support for import keyword and the rest of standardized EcmaScript 6+ features. In the near future you may not even have to transpile your project anymore. Until then your project files (JavaScript modules) will need to be bundled into one long file containing your entire source code. WebPack as many packages have configuration files. For WebPack it is usually webpack.config.js. You can create alternative builds. webpack --config webpack.config.js This command will build your entire application. The file bundle.js produced by this operation is then plugged into your front-end page. var path = require(‘path’);module.exports = { entry: ‘./es6/main.js’, output: { path: dirname, filename: ‘bundle.js’ },module: { loaders: [ { test: path.join(dirname, ‘es6’), loader: ‘babel-loader’ } ] } }; As you can see webpack defines babel loader in its configuration file webpack.config.js So when you actually build with webpack, it will use a babel loader to transpile ES6 code to ES5. Creating a React Native App Just to demonstrate an example of how easy it is to create new scaffolding for various applications with npm let’s create a React Native application. Navigate to your server’s htdocs (or a folder mapped to your server root) and execute the following command to create a new directory AwesomeProject for your React Native project: create-react-native-app AwesomeProject After running this command you will need to wait for a couple of minutes according to output: Installing packages. This might take a couple minutes. Installing react-native-scripts…yarn add v0.24.5Info No lockfile found.[1/4] Resolving packages… [2/4] Fetching packages… [3/4] Linking dependencies…...followed by a long list of packages (probably hundreds) ...not shown here...xtend@4.0.1 yallist@2.1.2 yesno@0.0.1Done in 224.75s.Installing dependencies using yarnpkg…yarn install v0.24.5 [1/4] Resolving packages… [2/4] Fetching packages… [3/4] Linking dependencies… [4/4] Buildingsuccess Saved lockfile.Done in 264.47s. Success! Created AwesomeProject at C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\AwesomeProject Or if you’re on Linux, it could have been /User/amazinguser/GitHub/AwesomeProject This will be followed by just a few more convenience notes from for using yarn: Normally, you wouldn’t even need to install Apache server. Node alone can get your localhost folder link up with a project directory on your computer. But in this example, it’s installed via existing Apache folder structure. If you want to create your projects elsewhere, that’s fine too! At this point, if you open your project folder in your browser you will see this: Index of /AwesomeProject - Parent Directory - .babelrc - .flowconfig - .gitignore - .watchmanconfig - App.js - App.test.js - README.md - app.json - node_modules/ - package.json - yarn.lock And just like the command line suggested, Let’s cd to AwesomeProject and run yarn start. The following log demonstrates what would happen: cd AwesomeProject yarn start yarn start v0.24.5 $ react-native-scripts start 11:53:39 PM: Starting packager… Packager started! To view your app with live reloading, point the Expo app to this QR code. You’ll find the QR scanner on the projects tab of the app. Or enter this address in the Expo app’s search bar: exp://192/168.0.2:19000 Your phone will need to be on the same local network as this computer. For links to install the Expo app, please visit. Logs from serving your app will appear here. Press Ctrl+C at any time to stop. Congratulations! We’ve successfully prepared a clean React Native build.
https://medium.com/@js_tut/overcoming-fear-of-package-json-building-server-side-javascript-1c63f4bdf8e0
CC-MAIN-2020-24
refinedweb
4,359
59.3
You are browsing the Symfony 4 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4 yet, browse the Symfony 3.4 documentation. How: You can also render each of the four parts of the field individually:: The remainder of this recipe will explain how every part of the form's markup can be modified at several different levels. For more information about form rendering in general, see How to Control the Rendering of a Form. some built-in form themes that define each and every fragment needed to render every part of a form: - form_div_layout.html.twig, wraps each form field inside a <div>element. - form_table_layout.html.twig, wraps the entire form inside a <table>element and each form field inside a <tr>element. - bootstrap_3_layout.html.twig, wraps each form field inside a <div>element with the appropriate CSS classes to apply the default Bootstrap 3 CSS framework styles. - bootstrap_3_horizontal_layout.html.twig, it's similar to the previous theme, but the CSS classes applied are the ones used to display the forms horizontally (i.e. the label and the widget in the same row). - bootstrap_4_layout.html.twig, same as bootstrap_3_layout.html.twig, but updated for Bootstrap 4 CSS framework styles. - bootstrap_4_horizontal_layout.html.twig, same as bootstrap_3_horizontal_layout.html.twigbut updated for Bootstrap 4 styles. - foundation_5_layout.html.twig, wraps each form field inside a <div>element with the appropriate CSS classes to apply the default Foundation CSS framework styles. Caution When you use the Bootstrap form themes and render the fields manually, calling form_label() for a checkbox/radio field doesn't show anything. Due to Bootstrap internals, the label is already shown by form_widget(). Tip Read more about the Bootstrap 4 form theme. In the next section you will learn how to customize a theme by overriding some or all of its fragments. For example, when the widget of an integer type field is rendered, an input number field is generated: As you can see, this fragment itself renders another fragment - form_widget_simple: also be located in different bundles, use the Twig namespaced path to reference these templates, e.g. @AcmeFormExtra/form/fields.html.twig. Disabling usage of globally defined themes¶ Sometimes you may want to disable the use of the globally defined form themes in order to have more control over rendering of a form. You might want this, for example, when creating an admin interface for a bundle which can be installed on a wide range of Symfony apps (and so you can't control what themes are defined globally). You can do this by including the only keyword after the list form themes: Caution When using the only keyword, none of Symfony's built-in form themes ( form_div_layout.html.twig, etc.) will be applied. In order to render your forms correctly, you need to either provide a fully-featured form theme yourself, or extend one of the built-in form themes with Twig's use keyword instead of extends to re-use the original theme contents. Referencing base Form Blocks¶ blocks inside the resource to use such a layout: - YAML - XML - PHP If you only want to make the change in one template, add the following line to your template file rather than adding the template as a resource: Note that the form variable in the above code is the form view variable that you passed to your template.: How to Customize a Collection Prototype¶ When using a collection of forms, the prototype can be overridden with a completely custom prototype by overriding a block. For example, if your form field is named tasks, you will be able to change the widget for each task as follows: Not only can you override the rendered widget, but you can also change the complete form row or the label as well. For the tasks field given above, the block names would be the following: article on validation. There are many different ways to customize how errors are rendered when a form is submitted with errors. The error messages for a field are rendered when you use the form_errors() helper: By default, the errors are rendered inside an unordered list: To override how errors are rendered for all fields, simply copy, paste and customize the form_errors fragment.: Adding a "Required" Asterisk to Field Labels¶ If you want to denote all of your required fields with a required asterisk ( *), you can do this by customizing the form_label fragment. If you're making the form customization inside the same template as your form, modify the use tag and add the following: If you're making the form customization inside a separate template, use the following: Adding "help" Messages¶ You can also customize your form widgets to have an optional "help" message. If you're making the form customization inside the same template as your form, modify the use tag and add the following: If you're making the form customization inside a separate template, use the following: To render a help message below a field, pass in a help variable: Using Form Variables¶ Most of the functions available for rendering different parts of a form (e.g. the form widget, form label, form errors, etc.) also allow you to make certain customizations directly. Look at the following example: The array passed as the second argument contains form "variables". For more details about this concept in Twig, see More about Form Variables. This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
https://symfony.com/doc/current/form/form_customization.html
CC-MAIN-2018-43
refinedweb
920
57.4
Not to self about mapM. Is it lazy? Sort of. Literate source is here:. First, some imports: > {-# LANGUAGE OverloadedStrings, InstanceSigs #-} > > import Control.Applicative > import Control.Monad > import qualified Data.ByteString as B > import Data.ByteString.Internal (w2c) > import Data.Either I recently wrote some code using wreq that seemed to use much more memory than I thought it should. The problem turned out not to be with wreq but with the way that I was using mapM. An equivalent snippet of code is: > main1 = do > firstFile <- head mapM B.readFile (take 100000 $ repeat "MapM.lhs") > print $ B.length firstFile I reasoned that mapM would construct its result lazily, then head would force evaluation of just the first element of the list. This isn’t the case, as explained here. The function mapM is basically equivalent to this: > mapM' :: Monad m => (a -> m b) -> [a] -> m [b] > mapM' m [] = return [] > mapM' m (x:xs) = do > x' xs' return (x':xs') So the monadic action m is evaluated to build up the list elements. One of the answers on the StackOverflow page says to use a step by step series to only evaluate the bits that are required: > data Stream m a = Nil | Stream a (m (Stream m a)) GHC 7.8.3 comes with Stream defined as: > -- In GHC 7.8.3: > newtype Stream m a b = Stream { runStream :: m (Either b (a, Stream m a b)) } The idea is that it represents a sequence of monadic actions. A Left is a final value of type b, while Right (a, Stream m a b) represents an intermediate value of type a along with the remaining stream. The Monad instance is fairly straightforward. The return function turns a plain value into a final value (hence the Left), and the bind either stops with the final value or produces the new value along with the next stream. > instance Monad m => Monad (Stream m a) where > return a = Stream $ return $ Left a > Stream m >>= k = Stream $ do > r case r of > Left b -> runStream $ k b > Right (a, str) -> return $ Right (a, str >>= k) There are also instances for Functor and Applicative but we don’t need them here. A handy function is liftIO which turns a normal monadic action into a stream: > liftIO :: IO a -> Stream IO b a > liftIO io = Stream $ io >>= return . Left It just runs the io action, and pipes it to a Left and then returns it in a Stream. > readFileS :: FilePath -> Stream IO b B.ByteString > readFileS f = liftIO $ B.readFile f To use readFileS we wrap it with runStream: *Main> Left x print $ B.length x 4243 So we can produce final values, but what about intermediate ones? This is what yield does: > yield :: Monad m => a -> Stream m a () > yield a = Stream $ return $ Right $ (a, return ()) At this point we have no idea about the remaining stream, so we return the unit (). For testing the code here we’ll take the definition of collect from Stream as well. It just walks through the entire Stream and collects the values, ignoring the final unit value. > collect :: Monad m => Stream m a () -> m [a] > collect str = go str [] > where > go str acc = do > r case r of > Left () -> return (reverse acc) > Right (a, str') -> go str' (a:acc) Now we can try out yield using monadic notation: > yield123 :: Stream IO Int () > yield123 = do > yield 1 > yield 2 > yield 3 *Main> collect yield123 [1,2,3] We can mix normal Haskell control structures like if/then/else into the monadic notation: > yieldEvens :: Int -> Stream IO Int () > yieldEvens n = if n > 10 > then return () > else do yield n > yieldEvens $ n + 2 *Main> collect $ yieldEvens 0 [0,2,4,6,8,10] We could read some files using our readFileS function and yield the results: > readAFewFiles :: Stream IO B.ByteString () > readAFewFiles = do > readFileS "MapM.lhs" >>= yield > readFileS "MapM.lhs" >>= yield > readFileS "MapM.lhs" >>= yield > readFileS "MapM.lhs" >>= yield > readFileS "MapM.lhs" >>= yield *Main> length collect readAFewFiles 5 We can generalise this to apply a monadic function to a list of arguments, which is basically what mapM does: > streamMapM :: (String -> IO B.ByteString) -> [String] -> Stream IO B.ByteString () > streamMapM _ [] = return () > streamMapM f (a:as) = do > (liftIO $ f a) >>= yield > streamMapM f as And we can even make an infinite stream: > readForever :: Stream IO B.ByteString () > readForever = streamMapM B.readFile (repeat "MapM.lhs") Take from a stream and a definition of head for a stream: > takeStream :: Integer -> Stream IO a () -> IO [a] > takeStream n str = go str [] n > where > go str acc n = do > if n else do r case r of > Left () -> return (reverse acc) > Right (a, str') -> go str' (a:acc) (n - 1) > > headStream :: Stream IO a () -> IO (Maybe a) > headStream str = do > h return $ case h of > [h'] -> Just h' > _ -> Nothing So we can efficiently take the head of the stream without evaluating the entire thing: *Main> (fmap B.length) headStream readForever Just 5917 I should point out that the example of reading a file a bunch of times could be achieved without Stream just by storing a list of the monadic actions, and then evaluating the one that we want: > listOfActions :: [IO B.ByteString] > listOfActions = repeat $ B.readFile "MapM.lhs" which can be used as follows: *Main> B.length (head $ listOfActions) 6455 The difference is that the list is somewhat static, in that we can’t mix control structures into it as we can do with Stream. Interestingly, the definition for Stream looks very similar to the definition for Free, which I used in an earlier post about free monads: > data Stream m a = Nil | Stream a (m (Stream m a)) > data Free f r = MkPure r | MkFree (f (Free f r)) Here’s one way to encode Stream-like behaviour using free monads. I define two actions, yield and final. The yield action stores an input value of type a, a monadic function a -> IO b, and the rest of the structure, which turns out to be conveniently represented as a function b -> k. Being a function of b lets the rest of the structure depend on the result at the current node in the structure. The final action just stores the value and monadic action, and is a terminal node in the free monad. > data StreamF a b k = Yield a (a -> IO b) (b -> k) > | Final a (a -> IO b) For convenience, Command is a simpler type signature: > type Command a b k = Free (StreamF a b) k As in my earlier post, we need instances for Functor and Monad. They are fairly straightforward: > instance Functor (StreamF a b) where > fmap f (Yield a io k) = Yield a io (f . k) > fmap _ (Final a io) = Final a io > > instance (Functor f) => Monad (Free f) where > return :: a -> Free f a > return x = MkPure x > > (>>=) :: Free f a -> (a -> Free f b) -> Free f b > (MkFree x) >>= h = MkFree $ fmap (q -> q >>= h) x > (MkPure r) >>= f = f r Here are two helpers to make Command’s monadic usage easier: > -- Lift an IO action to a final Command. > finalF :: a -> (a -> IO b) -> Command a b r > finalF a io = MkFree $ Final a io > > -- Lift an IO action to a Command that yields the value > -- and continues. > yieldF :: a -> (a -> IO b) -> Command a b b > yieldF a io = MkFree $ Yield a io (b -> MkPure b) To run a Command we walk its structure recursively and run the IO actions as needed: > runCommand :: (Show a, Show b, Show r) => Command a b r -> IO () > > runCommand (MkFree (Final a io)) = do > putStrLn $ "Final " ++ show a > x putStrLn $ "Produced the value: " ++ show x > > runCommand (MkFree (Yield a io next)) = do > b putStrLn $ "Yield: computed value: " ++ show b > runCommand (next b) > > runCommand (MkPure x) = putStrLn $ "MkPure: " ++ show x As with Stream, we can mix control structures with the creation of the free monad: > exampleCommand :: Command FilePath String String > exampleCommand = do > x y then yieldF "hello2.txt" readFile > else finalF "hello3.txt" readFile > return y For example: Yield: computed value: "hello1n" Yield: computed value: "hello2n" MkPure: "hello2n" Taking the head of a Command is straightforward using the definition of runCommand: > headCommand :: Command a r r -> IO r > headCommand (MkFree (Final a io )) = io a > headCommand (MkFree (Yield a io _)) = io a > headCommand (MkPure x) = return x Here it is in action: *Main> :t headCommand exampleCommand headCommand exampleCommand :: IO String *Main> headCommand exampleCommand "hello1n" To finish things off, here are versions of take and mapM on Command: > runOneCommand :: Command t t () -> IO (Either () (t, Command t t ())) > > runOneCommand (MkFree (Final a io)) = do > x return $ Right (x, MkPure ()) > > runOneCommand (MkFree (Yield a io next)) = do > b return $ Right (b, next b) > > runOneCommand (MkPure ()) = Left return () > > takeCommand :: Integer -> Command t t () -> IO [t] > takeCommand n str = go str [] n > where > go str acc n = do > if n else do r case r of > Left () -> return $ reverse acc > Right (a, str') -> go str' (a:acc) (n - 1) > > commandMapM :: (a -> IO a) -> [a] -> Command a a () > commandMapM _ [] = MkPure () > commandMapM f (a:as) = do > yieldF a f > commandMapM f as It works like the Stream example: > takeCommandExample = (fmap B.length) (takeCommand 3 $ commandMapM readFileBB (take 100000 $ repeat "MapM.lhs")) >>= print > where > -- Since B.readFile :: String -> B.ByteString > -- we have to write this wrapper so that the input > -- and result types match, as required by the > -- restriction "Command t t ()" in the signature > -- for takeCommand. > readFileBB :: B.ByteString -> IO B.ByteString > readFileBB = B.readFile . (map w2c) . B.unpack There we go: *Main> takeCommandExample [11241,11241,11241]
https://carlo-hamalainen.net/2014/10/
CC-MAIN-2017-51
refinedweb
1,594
73.71
28 January 2011 02:14 [Source: ICIS news] ORLANDO (ICIS)--Surfactant producers Cognis and Evonik Goldschmidt expect to see further price hikes in the US and Europe in the next six months as fatty alcohol and fatty acid prices continue to soar, company officials said on Thursday. Surfactants are major chemical ingredients for detergent and other cleaning products. Consumer product companies are slower to react in passing on product price increases to consumers, which put surfactant manufacturers in a tight squeeze, said Steve Turner, director, household care at Evonik Goldschmidt, on the sidelines of the American Cleaning Institute (ACI) annual meeting in ?xml:namespace> “Fats and oils prices have gone up by 50-60% in the last three months, which are unsustainable. There is no doubt surfactant producers have to pass on these price increases,” added Turner. According to Evonik, most of their raw material feedstock are based on oleochemicals that uses animal fats. Cognis, which is now part of BASF, is also a major animal fats and palm kernel oil consumer. The company still produces and markets fatty alcohols in Europe and the “Being vertically integrated into fatty alcohol production is an added leverage at times like these but there is no doubt that with such high fats and oils prices, there is a need to pass on these increases,” said Bungel. In the US,, according to ICIS. In Europe, tallow prices reached record highs with €800-850/tonne FD (free delivered) NWE (northwest Europe) in Crude palm kernel oil, meanwhile, rose to Malaysian Ringgit (M$)405 per pikul (close to $2,200/tonne) FOB (free on board) Malaysia on Tuesday, sending shock waves into the industry as prices had reached yet another historical high, reported ICIS. Crude coconut oil values also touched $2,260/tonne CIF (cost, insurance and freight) The ACI meeting ends Saturday. (
http://www.icis.com/Articles/2011/01/28/9430215/surfactant-firms-see-price-hikes-on-high-oleochemical.html
CC-MAIN-2014-52
refinedweb
307
52.63
429 summary says it all. Example: var watcher1 = new System.IO.FileSystemWatcher("somefilepath.txt"); var watcher2 = new System.IO.FileSystemWatcher(); Both throw a NotImplementedException. Hello, Please can you provide the exact version of the runtime? The easiest way to get exact version information is to use the "Xamarin Studio" menu, "About Xamarin Studio" item, "Show Details" button and copy/paste the version informations (you can use the "Copy Information" button). Apart from the above, can you give use a little more context, for example, what type of project were you trying to build? (iOS, Console app, etc..) Regards, Manuel PS: I cannot reproduce your issue with the following version: === Xamarin Studio Business === Version 6.1 (build 4373) Installation UUID: 01060673-5bee-4cf4-a4c2-5e36a18d39a2 Runtime: Mono 4.4.1 (mono-4.4.0-branch-c7sr0/4747417) (64-bit) GTK+ 2.24.23 (Raleigh theme) Package version: 404010000 === Xamarin.Profiler === Not Installed === Xamarin.Android === Version: 6.1.1.1 (Xamarin Business).11.2.44 (Xamarin Business) === Xamarin.iOS === Version: 9.11.0.44 (Xamarin Business) Hash: 6e41b65 Branch: core-data-issues Build date: 2016-07-26 18:15:15+0200 === Build Information === Release ID: 601004373 Git revision: 852a87304bbbd9c26e81bbb2428dafc6145f1601 Build date: 2016-05-31 01:09:06-04 Xamarin addins: d6b49aee9d3b2f75a1eea84b8ad3b2d1d4fd77c0 Build lane: monodevelop-lion-master === Operating System === Mac OS X 10.11.6 Darwin Mandels-Pro-Work.local 15.6.0 Darwin Kernel Version 15.6.0 Thu Jun 23 18:25:34 PDT 2016 root:xnu-3248.60.10~1/RELEASE_X86_64 x86_64 === Enabled user installed addins === Addin Maker 1.3.2 StyleCop Support 1.0.1.9 Manifest.addin 0.0.0.0 This is an iOS project that is recording videos and the intent was to have FileWatcher watch for the creation of the video file. My runtime version is as follows: === Xamarin Studio Enterprise === Version 6.0.2 (build 70) Installation UUID: 0c5e86ef-77a3-4ba5-b020-2588dc44e162 Runtime: Mono 4.4.2 (mono-4.4.0-branch-c7sr1/b430435) (64-bit) GTK+ 2.24.23 (Raleigh theme) Package version: 404020008 === Xamarin.Profiler === Not Installed === Xamarin.Android === Version: 6.1.2.20 (Visual Studio Enterprise Trial) Android SDK: /Users/atarr Inspector === Version: 0.9.0.14 Hash: 4d868da Branch: master Build date: Mon Jun 13 19:14:13 UTC 2016 === Apple Developer Tools === Xcode 7.3.1 (10188.1) Build 7D1014 === Xamarin.iOS === Version: 9.8.2.19 (Visual Studio Enterprise Trial) Hash: a5ae61c Branch: cycle7-sr1 Build date: 2016-07-20 23:23:58-0400 === Xamarin.Mac === Version: 2.8.2.19 (Visual Studio Enterprise Trial) === Build Information === Release ID: 600020070 Git revision: 30f7c18e8acbca2124c88a2ba9014123097c53ab Build date: 2016-07-21 16:55:52-04 Xamarin addins: 451cc4c4640551a72356d8a85a4f15ff55fcb661 Build lane: monodevelop-lion-cycle7-sr1 === Operating System === Mac OS X 10.11.6 Darwin andrews-mbp-2 15.6.0 Darwin Kernel Version 15.6.0 Thu Jun 23 18:25:34 PDT 2016 root:xnu-3248.60.10~1/RELEASE_X86_64 x86_64 === Enabled user installed addins === Xamarin Inspector 0.9.0.14 Thanks, I'll downgrade and will try to reproduce the issue. I can confirm this happens in an iOS project (while it won't happen in a terminal one) due to this: Also getting this within a MacOS project. Is there a work around? Here is a workaround, from this, I’m assuming that this is strictly a compilation problem on how the libraries for Mac are compiled: 1) From this location:, you will need to following files: - DefaultWatcher.cs - FAMWatcher.cs - FileAction.cs - FileSystemWatcher.cs - IFileWatcher.cs - InotifyWatcher.cs - KeventWatcher.cs - NullFileWatcher.cs - SearchPattern.cs - WindowsWatcher.cs 2) You will need to change the namespace of the FileSystemWatcher.cs to something other than System.IO, so that you can tell away the two classes. 3) Fix up compilation problems: - In the above files for all FileSystemWatcher references insert your namespace in front of it. - for all Consts.Assembly… press F12 to browse into the assembly and copy out the string constant - the value of the constant is internal, so you will not have access to it in the source code, but copy pasting it will make sure you reference the same DLLs. - Add missing namespaces. 4) in FileSystemWatcher.cs around line:120, change mode = InternalSupportsFSW() to mode = 3 that seems to work on macOS Sierra. Unfortunately, since not all files are with the same copyright headers, I have no time to figure out if I could redistribute a modified binary as a compiled DLL from a separate project, so somebody at Xamarin will have to fix this up during the compilation or whoever wishes to use it can apply the workaround. Please note: the sources are from the same location as the problematic FileSystemWatcher_mobile.cs. I am experiencing this when creating an OSX Cocoa project with Target Framework Xamarin.Mac Modern. I assume this is because Modern is more aimed at iOS/Android. Unfortunately, I need to use Modern as it supports netstandard 2.0, while Full doesn't. Will the work around above help me? Is there anyway to make a Xamarin.Mac Modern project recognize that it is not just a mobile project? ctclements: I'm using the workaround since I've posted it in a project and seems to work fine. The only thing that sometimes annoys me, is that I had to duplicate non-related code too to replace the FileSystemWatcher with the custom included one, but that is more a code organization issue, not anything related to the workaround itself. Attila: Could you explain your work around a little more to me? I'm afraid I'm lost around step 3. I downloaded the necessary files, and then changed all of their namespaces away from System.IO to a custom one. I'm a little lost on how to complete the steps after that, specifically I'm not familiar with "Consts.Assembly and how to browse into the assembly code. Step 3 is actually editing the downloaded code, Consts."Assembly" is inside the code. For example, FileSystemWatcher.cs:228, [TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)] If you open the source code with a Visual IDE those usually have the F12 key bound to go to definition, so you go to the definition of Consts.AssemblySystem_Design in this case and replace it textually to "System.Design, Version=2.0.5.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a". Keep in mind that the above Assembly information is for the version that I've built together 3 months ago, the assembly name could have been changed and I also typed the text so I could even mistype it - especially the PublicKeyToken. Point is that this is just making the code compile without actually changing it. At the end your line should look something like this: [TypeConverter("System.Diagnostics.Design.StringValueConverter, " + "System.Design, Version=2.0.5.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] I've pinged @chamos to take a look since he is the mac os x team lead. I'm taking a look at this, but I want to post one correction: "Unfortunately, I need to use Modern as it supports netstandard 2.0, while Full doesn't." This is incorrect. I wrote up a long description here () but the short answer is that you can add: <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion> in your top property group and things should just work. If you are on the d15-3 release, you may need to add <Reference Include=”netstandard” /> in your reference section manually as well. Chris: I tried this, but unfortunately it didn't get me too far. After I added those lines and retargeted my packages, my Mac App instantly crashes on NSApplication.Init(); with error "Could not load file or assembly 'System.Data.Common' or one of its dependencies". Please create a forum post () or a separate XM bug for that specific issue, with the full build log (preferably a sample showing the issue). I don't want to pile on... originally the bug was reported for iOS and then workarounds were noted for Mac. This is still happening on iOS. Would it be helpful if I opened a new bugzilla or provided updated info on the specifics here? Matt: I don't know anything about if this is fixable on iOS or if it is a good idea to implement a file system watcher on a mobile device, but the problem is actually a FileSystemWatcher.cs vs. FileSystemWatcher_mobile.cs, so I think the fact of macOS vs. iOS is part of the problem. Thanks for the quick reply Attila - I had a feeling that FileSystemWatcher didn't make sense to implement on a mobile device. I will go back to the author of the library I am trying to use in order to see if they can do anything. Appreciate the help.
https://bugzilla.xamarin.com/42/42935/bug.html
CC-MAIN-2021-25
refinedweb
1,468
59.19
Details Description I have a template that references a List returned by a method on an Enum. The method is defined as an abstract member of the enum. This used to work on 1.4, but doesn't work on 1.6.1 I'm able to get it to work on 1.6.1 by changing the abstract method to a regular method of the Enum, which is then overridden by each instance of the enum. Here's the code that doesn't work. Again, it seems to be the abstract modifier, becuase if I change that method to something like public List getMyList(){ return new ArrayList(); } And then just override it in my enum instances, everything works fine. public enum Thing { NUMBER_ONE( ){ public List<String> getInnerThings() { //initialize innerThings if this is first time if ( this.innerThings == null ) return innerThings; } }, NUMBER_TWO( ){ public List<String> getinnerThings() { //initialize innerThings if this is first time if ( this.innerThings == null ) { innerThings = new ArrayList<String>(); innerThings.add( "blah blah" ); innerThings.add("blah blah" ); } return innerThings; } }, NUMBER_THREE( ){ public List<String> getinnerThings() { if ( this.innerThings == null ) return innerThings; } }; List<String> innerThings; //This was an abstract method, but Velocity 1.6 quite working with it. public abstract List<String> getinnerThings(); } Activity - All - Work Log - History - Activity - Transitions scratch that. ClassMap explicitly skipping abstract methods, ostensibly because their implementations would be found, forgetting that the implementing class might not be public. easy fix. Fixed in all revisions. Er... i meant "versions". The trouble seems to be with abstract public methods declared in abstract classes and implemented in non-public classes. An enum class with an abstract public method shows this, but it also happens with things like: public abstract Foo{ public abstract String getBar(); } Foo foo = new Foo() { public String getBar(){ return "bar"; } }; I think this worked in Velocity 1.4 because the ClassMap implementation was based off of Class.getMethods, whereas it was changed to Class.getDeclaredMethods in 1.5 to speed things up. Calling getDeclaredMethods on Foo doesn't return getBar, which is surprising as the declaration is right there. I haven't yet figured out how i want to fix this.
https://issues.apache.org/jira/browse/VELOCITY-701
CC-MAIN-2015-48
refinedweb
356
67.65
Docs | Forums | Lists | Bugs | Planet | Store | GMN | Get Gentoo! Not eligible to see or edit group visibility for this bug. View Bug Activity | Format For Printing | XML | Clone This Bug I see STLport 5.x is marked as ~ppc, but this version is completly not compatible without some patchings. First broken thing is endianese detection in STLport/stlport/stl/_config.h it can be fixed by a simple patch, but there is also many other compilation failures later on. I try to fix that but I simply give up :( Ping ? The only version of STLport that I can install is 4.6.2 on ~ppc system. I get the same can't determine endianness error. Ech ... this bug was enough time here now. I did a small investigation of this problem using STLport 5.0.2 and I was able to compile it on my machine. Created an attachment (id=90222) [edit] endianese detect fix This one solved endianese detection problems for me. I am not completly sure is endian.h header is present on all systems, but I belive it is for all archs supported by Gentoo ATM.: __std_alias::llabs has not been declared ../stlport/cstdlib:90: error: __std_alias::lldiv_t has not been declared ../stlport/cstdlib:91: error: __std_alias::lldiv has not been declared ../stlport/cstdlib: In function long long int abs(long long int): ../stlport/cstdlib:133: error: llabs is not a member of __std_alias ../stlport/cstdlib: In function lldiv_t div(long long int, long long int): ../stlport/cstdlib:134: error: lldiv is not a member of __std_alias It seems llabs/lldiv aren't exported to std namespace at last not on my system (Glibc 2.4-r3 && GCC 4.1.1) Looking at cstdlib from my system gives me this solution. Not perfect, but working. Created an attachment (id=90224) [edit] ebuild with both patches Adding maintainers. Created an attachment (id=98615) [edit] openoffice build fails without the patch, not sure of the connection. The sal portion of openoffice-2.0.4 fails with xml2cmp errors without patch. From . Just wondering if STLport-5.1.0 solves this issue? See bug #158981 for ebuild. Reassigning this bug to coordinate the keywording. Ok, I've committed a version bump to 5.1.0 a couple of minutes ago and I dropped ~ppc and ~ppc64 for that reason. Dear arch-team members: Please test this package on your platform and re-add your keywords when the unittests succeed. Thanks in advance! thanks! ~ppc64 added. Marked ~ppc and closing since we're the last arch team CC'd. Thanks!
http://bugs.gentoo.org/132054
crawl-002
refinedweb
429
69.99
Basically I am attempting a HW assignment for questions that a frequently asked in interviews. I am not sure if I am having problems with the coding or actually understanding what they question is asking for. Basically I am asked to find an element in a sorted array and that is it. The element I am assuming is the pivot point? I am more so needing help with the understanding than the coding itself but advice on either is welcomed. Keep in mind this is entry level C work I am doing so any advanced explanations will most likely be over my understanding. Here is what I have so far. #include <stdio.h> #define size 5 int main() { int array[size] = {4, 8, 0, 1, 3}, pivot, i, j, high, low, mid; high=4; low=0; while ( low <= high ) { mid=(high + low)/2; if (array[low] < array[mid]) low = mid+1; else if (array[mid] < array[high]) high = mid-1; else printf("%d is pivot", mid);
https://www.daniweb.com/programming/software-development/threads/434282/interview-questions-finding-element-in-rotated-array
CC-MAIN-2017-09
refinedweb
166
69.01
Save variable to use it in next script execution I search for a way to save a variable so that I can recall it in the next execution of the script. I want to use it like a counter. Or is there a way to interact with some kind of database? Any hints? Read/write to a file, json, pickle, marshal, sqlite3, there are a million ways to do this but... import contextlib, shelve file_name = 'my_shelve' # Pythonista will create '.bak', '.dat', and '.dir' files with contextlib.closing(shelve.open(file_name)) as d: print(d.setdefault('counter', 0)) d['counter'] += 1 Or pretend it is a password and use keychain. Thanks for the information!
https://forum.omz-software.com/topic/569/save-variable-to-use-it-in-next-script-execution
CC-MAIN-2018-13
refinedweb
113
76.62
I. For me, it's a bug. It's a totally unexpected behavior.ST2 must filter the first line used as filename to remove forbidden chars and trunc it to filename size limit. I for one really like the new icon. It feels much more professional than the previous version (as well as many of the user contributed icons). It's simple (like the software) and not overly techie/nerdy. It also fits right in with other great web development software icons I use everyday. See attached pic. Great work!!! Could we please have the "indent_to_bracket" ignore brackets it's immediately following: def foo(asd, |) but: def bar( |) baz = { | }] The icon is better except: 1 the color on the S 2 the font used on the S3 it could indeed use less inclination (not as important).
https://forum.sublimetext.com/t/dev-build-2178/4406/60
CC-MAIN-2017-09
refinedweb
136
73.88
Dear all, seems an often named problem, but it is very complicated to get it running: I have SPSS 21 64bit installed on WIN 7 Enterprise 64bit SP 1, also R 2.14.0 I installed R Essentials for 64bit as administrator, it seemed that it installed everything needed (given no error message) Then startet SPSS 21 again (as administrator or not, did not make a difference) Neither the additional menu items came (I need quantile regression especially) nor could I install extensions or use RASCH etc. Always the message:" you have to install R Essentials..." But I did install or at least I think so given no error messages.. Is there an easier way for example via "File -> Repository"? But then I need access to that and do not know how. Any help is greately welcome! Answer by JonPeck (4671) | Sep 06, 2013 at 12:54 PM Sorry that you are having trouble. Here are some things to check. First, can you start Rgui from the Start menu? That should show that R is actually installed and the version and whether it is 32 or 64 bit. Next, in the syntax window enter and run this code. begin program r. print(sessionInfo()) end program. If the R plugin is actually installed, you should see something like this: R version 2.14.2 (2012-02-29) at [1] stats graphics grDevices utils datasets methods base loaded via a namespace (and not attached): [1] tools_2.14.2 Look in your Statistics installation directory. You should see files named InvokeR.dll and InvokeX.dll Look also at the spssdxcfg.ini file in that directory. It should look like this (ignore the Python references) SpssdxVersion=21.0.0.1 SpssdxVersionMajor=21 SpssdxVersionMinor=0 SpssdxVersionPatch=0 SpssdxFixPack=1 [SUPPORTED_LANG] X=PYTHON;R [Python] HOME=C:\Python2764\ LIB_NAME=InvokePython [R] HOME=C:\R2.14.2 LIB_NAME=InvokeR In a syntax window run SHOW EXTPATHS. That shows where Statistics is looking for the files for extension commands and their dialogs. Look in those locations to see what files are actually present. For SPSSINC QUANTREG, e.g., you should see SPSSINC_QUANTREG.R and SPSSINC_QUANTREG.xml There should also be files for the dialog boxes, but let's deal with that later. Answer by Biltroller (0) | Sep 11, 2013 at 12:50 PM Dear Jon, thank you very much for your answer which helped me to find my fault: I installed R 2.14.0 instead of R 2.14.2, what a difference a minor version makes... Now I works with SPSS. However, not a very user-friendly way to get it running, I must say. I did not plan to be an expert in computer technology as I started to work on research in social science... Thank you very much and best wishes Answer by JonPeck (4671) | Sep 11, 2013 at 12:58 PM We wish that there were fewer steps to getting this all set up, but because of the way R is licensed, we have to keep the R installation separate and place the R Essentials on a different site from most of the rest of our materials. In Statistics 22, we have made the process of installing and working with programmability a bit easier, but there are limits to what we can do. Regards, Jon Answer by JakeSTL (0) | Nov 11, 2013 at 06:58 PM Dear Jon, To follow up on your post with Bitroller, I wanted to ask how to deal with an "x11 display" error message in SPSS 21. Similarly, I have the SPSS 21.0 version installed, with R 2.14.2 When I run the print command, I get the locale and attached base packages output, but also an error that reads: "in redirection (): Unable to open connection to x11 display" I was wondering if you have any suggestions on how to trouble shoot this. Thank you! Best, Jake Answer by JonPeck (4671) | Nov 11, 2013 at 09:41 PM If you Google for this error message, which is coming from R and which seems to occur only on Unix/Linux systems, there are a lot of hits and various suggestions. These are not specific to the SPSS integration. One easy thing to try would be to put this at the top of your code. Sys.setenv("DISPLAY"=":0.0") You might also want to run capabilities() in the R code. You shouldn't need an x11 server. If setting the DISPLAY variable works you might want to set that variable in your environment. 46 people are following this question. Welcome to the R forum 0 Answers Error 53e - downloading v19 plug-in 5 Answers Path definition for spssRGraphics.Submit 1 Answer multiple plotting in R 0 Answers How do I install the R ltm packages in SPSS (24)? 1 Answer
https://developer.ibm.com/answers/questions/217600/spss-21-and-r-essentials-not-working.html
CC-MAIN-2019-26
refinedweb
803
73.47
Mark Seemann's thoughts about whatever .NET development topic he's currently immersed in. These days, I seem to be encountering a lot of entities. Not in the sense of non-corporeal beings as usually depicted in certain science fiction TV shows, but in the sense of data structures. Sometimes, they are called business entities. Although the concept of entities differ from project to project, I think I have identified at least one common trait of all the entities I come across: They contain (structured) data, but no behavior. Usually, these entities are being consumed and manipulated by something called the business logic. In some cases, entities are even used to transfer data from one layer of an application to the next layer (some people then call them data transfer objects). Since architecture diagrams with vertical columns adjacent to layers appear to be much in vogue these days, I'll use one as an example: The idea here is to have a single definition for data that spans multiple levels so that you only have to write the data structure implementation once. The code in the different layers interact with the entities: The data access layer creates and stores the entities, the business logic layer modifies the data, and the UI layer presents the data. Pretty clean architecture, right? No. So what's wrong with it? First of all, what does the name entity tell us? Nothing, really. Entity is a synonym for object, but surely, the term business objects is so last year that any self-respecting architect would never use such a term. On the other hand, an object with structure but no behavior sounds awfully familiar. Your code takes one or more structures of data as input, operate on them and outputs other structures. Fowler calls this pattern a Transaction Script; I call it procedural programming, and since I have had my experiences with this programming style early in my career, I never want to go back. Domain Model is where it's at. In Patterns of Enterprise Application Architecture, Fowler wrote that "a Data Transfer Object is one of those objects our mothers told us never to write." While the pattern itself is valid, it's only supposed to be used for communication across process boundaries, not across layers in the same process. If you are still not convinced about my arguments, let's take a look at an example. Imagine that you want to model a product catalog. Since we are modeling with entities, we create Product and Category classes. Both are just dumb classes with default constructors, read/write properties, and no behavior. To decouple data access, we also define a data access interface: public interface ICatalogDataAccess { Category ReadCategory(int categoryId); Product ReadProduct(int productId); } Implementing this interface is fairly straightforward, and goes something like this: using (IDataReader r = this.GetProductReader(productId)) if (!r.Read()) { throw new ArgumentException("No such product.", "productId"); } Product p = new Product(); p.ProductId = (int)r["ProductId"]; p.Name = (string)r["Name"]; p.ListPrice = (decimal)r["ListPrice"]; p.Discount = (decimal)r["Discount"]; p.InventoryCount = (int)r["InventoryCount"]; return p; This code is actually fairly benign - trouble only starts to appear in the business logic layer. Imagine that we need the business logic to implement the calculation of the discounted price, and whether the product is in stock (yes, rather inane business logic, I know). Since the Product entity is just a structure without behavior, it's necessary to create another class to implement this business logic: public class ProductOperator private Product product_; public ProductOperator(Product p) this.product_ = p; public decimal DiscountedPrice get { return this.product_.ListPrice - this.product_.Discount; } public bool InStock get { return this.product_.InventoryCount > 0; } Now you are left with the problem of how to pass this information on to the next layer. One alternative is to create an abstraction of ProductOperator (say; IProductOperator) and pass that to the next layer together with the Product entity. That approach can quickly grow quite unpleasant, since each layer adding content to the entity needs to define yet another auxiliary class to be passed along with the ProductOperator and the Product entity. Another alternative is to model the Product entity to include properties for this information from the start. That would mean that the data access component would fill in only the properties of the Product entity that comes from the database, and a variant of ProductOperator would then fill in the DiscountedPrice and InStock properties in the business logic layer: public partial class ProductOperator public ProductOperator() public void UpdateDiscountedPrice(Product p) p.DiscountedPrice = p.ListPrice - p.Discount; public void UpdateInStock(Product p) p.InStock = p.InventoryCount > 0; Beware: Here be dragons. One problem with this approach is that you'd end up with a lot of properties whose values may or may not be null (DiscountedPrice and InStock, in this case), so you always need to check for null before reading and using a property value. The other problem with this design is that it railroads your components into a particular usage scenario. In the end, you model the entity in order to communicate it across your process boundary (via a UI, service interface, etc.). This boundary has a particular usage scenario; e.g. you need to show product information in a UI. Such a usage scenario then becomes the driver for the entity structure: You need to show the discounted price, so you need a property for that, etc. If you need to display product information in another screen, you include properties for this screen as well. In the end, you end up with a data structure that carries around a lot of data that may or may not be used in any particular scenario. There are lots of nicer ways to pass data between layers in extensible ways, and in a future post, I'll describe one such approach. If you would like to receive an email when updates are made to this post, please register here RSS While I hope that my previous post made it clear that Data Transfer Objects are not my first choice for I think in the case of DTO the best option would be to use extended methods (.NET v3.5). There are two primary benefits, one, extended methods would/can be contextual to the layer. Also, because all we need are derived properties (which are/should be read-only), they don't need to be stored - saving memory. Cheers Agreed. My post on Layered Architecture problems centers on exactly the same point. One solution is to define the entity interfaces in the lowest layer, however that doesn't (by itself) solve the issue of how the UI Layer can create a new entity. This leads us to the creational aspects of Dependency Injection (DI), which I wrote about in Careful how you inject those dependencies. I think that its just fine to use (DI) with entities / domain objects. I've done it so as to allow custom fetching strategies for getting them from the database. In short: +1 Hi Rishi Thank you for your comment. Although extension methods are nice, I don't agree that they fit in this scenario. If you wrote an extension method to, say, implement DiscountedPrice, you'd essentially be writing business logic into your extension method. The point about this exercise is decoupling, so you don't want your business logic invading the next layer up. This means that you can't use the (business logic) extension methods in your UIP layer, but then you don't have any interface to extract the DiscountedPrice any more. Using extension methods only in the business logic layer would not be very meaningful either, as the implementation would be entirely transient and the data would not be available to the next layer - not even in abstract form. Hi Udi Thank you for your comment. Your post on layering mirrors mine very nicely :) As you probably know, there are lots of better ways to model the abstractions between layers. For the fun of it, my next post outlined a better approach, but when you really think about it, there should be no correlation between the objects in each layer. If you have a Product class that you share between the DAL and the BLL, extending that Product class to be shared between the BLL and the UIP layer ties all three layers together. You will not be able to modify the Product abstraction without impacting the UIP layer, and that may not be what you want to do. Ideally, you should be able to vary abstractions independently between layers, which means that the Product abstraction used between the DAL and the BLL should have no relation to the Product abstraction used between the BLL and the UIP layer.
http://blogs.msdn.com/ploeh/archive/2007/06/18/WhatIsAnEntityAnyway.aspx
crawl-002
refinedweb
1,470
51.58
Ram wrote:> Under the premise that bind mounts across namespace should be allowed;> any insight why the "founding fathers" :) allowed only bind> and not recursive bind? What issue would that create?Recursive bind traverses the subtree of vfsmnts rooted at the sourcemount (following mnt->mnt_mounts, see copy_tree()). That requires thesource mount's namespace semaphore to be held.> One can easily workaround that restriction by manually binding> recursively.Yes, if you know which mounts they are.> I remember Miklos saying its not a security issue but a> implementation/locking issue. That can be fixed aswell.Yes, by taking the source namespace semaphore while traversing thesubtree. That involves taking _two_ semaphores, so they have to beordered to avoid deadlock (see double-locking elsewhere in the kernel).- Jamie-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
https://lkml.org/lkml/2005/5/16/292
CC-MAIN-2016-50
refinedweb
153
51.04
A simple package for crawling bol.com Project description bolcom_crawler This is a really simple crawler that makes use of Scrapy to crawl bol.com. Usage The Crawler instance has two functions you can use, crawl_products and crawl_category. See an example below. from bol_crawler.crawler import Crawler crawler = Crawler() # to crawl products products = crawler.crawl_products( [ '', ] ) # to crawl a category products = crawler.crawl_category( [ '', 0 # the 0 value is how often you want to go to the next page. 0 is just crawling the first page ] ) 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/bol-crawler/
CC-MAIN-2019-51
refinedweb
111
68.06
Description Farmer John recently bought another bookshelf for the cow library, but the shelf is getting filled up quite quickly, and now the only available space is at the top. FJ has N cows (1 ≤ N ≤ 20) each with some height of Hi (1 ≤ Hi ≤ 1,000,000 - these are very tall cows). The bookshelf has a height of B (1 ≤ B ≤ S, where S is the sum of the heights of all cows). To reach the top of the bookshelf, one or more of the cows can stand on top of each other in a stack, so that their total height is the sum of each of their individual heights. This total height must be no less than the height of the bookshelf in order for the cows to reach the top. Since a taller stack of cows than necessary can be dangerous, your job is to find the set of cows that produces a stack of the smallest height possible such that the stack can reach the bookshelf. Your program should print the minimal 'excess' height between the optimal stack of cows and the bookshelf. Input * Line 1: Two space-separated integers: N and B * Lines 2..N+1: Line i+1 contains a single integer: Hi Output * Line 1: A single integer representing the (non-negative) difference between the total height of the optimal set of cows and the height of the shelf. Sample Input 5 16 3 1 3 5 6 Sample Output 1 Source #include <iostream> #define maxv 1000005 using namespace std; int ans[maxv],n,v,c[21],sum; int main() { cin>>n>>v; for(int i=1; i<=n; i++){ cin>>c[i]; sum += c[i]; } for(int i=1; i<=n; i++){ for(int j=sum; j>=c[i]; j--){ if(ans[j]<ans[j-c[i]]+c[i]) ans[j]=ans[j-c[i]]+c[i]; } } for(int i=v; i<=sum; i++){ if(i==ans[i]){ cout<<ans[i]-v<<endl; break; } } return 0; } /* Author : yan * Question : POJ 3628 Bookshelf 2 * Data && Time : Wednesday, December 22 2010 11:34 PM */ #include<stdio.h> using namespace std; int cow[20]; int b; int n; int ans=99999999; void DFS(int num,int sum) { if(sum>=ans) return; if(num==n) { if(sum>=b) ans=sum; return; } DFS(num+1,sum); DFS(num+1,sum+cow[num]); } int main() { //freopen("input","r",stdin); int i,j,cnt,tmp; int sum; scanf("%d %d",&n,&b); for(i=0;i<n;i++) scanf("%d",&cow[i]); DFS(0,0); printf("%d",ans-b); return 0; }
https://blog.csdn.net/u011558005/article/details/17080755
CC-MAIN-2018-30
refinedweb
432
57.44
28 February 2012 07:36 [Source: ICIS news] SINGAPORE (ICIS)--Major paraxylene (PX) end-users have counter-bid the March PX Asian Contract Price (ACP) at $1,550-1,580/tonne (€1,163-1,185/tonne) – atleast $140/tonne below what producers are seeking - citing a bleak outlook for the downstream polyster yarn and filament sector. The counter-bids are against nominations made by JX Nippon Oil & Energy at $1,690/tonne CFR (cost and freight) ?xml:namespace> “We see continued poor demand for purified terephthalic acid (PTA) all the way to end-March or early-April as inventory levels are high in the downstream polyester sectors,” said a major PTA maker. Demand for polyester farms and filaments have remained weak since end-January with most weavers and spinners still digesting pre-Lunar New Year inventory stockpiles. Polyester inventory levels in Some PX traders are predicting a $1,620-1,650/tonne CFR Asia settlement for the March PX ACP. “These are the prices at which end-users have bought March shipments, they should be able to accept contract prices at such levels as well,” they said. The February PX ACP was fully settled at $1,590/tonne CFR Asia while the March PX ACP will be settled on 29 February. Additional reporting by Judith W
http://www.icis.com/Articles/2012/02/28/9536342/major-end-users-counter-march-px-acp-at-1550-1580tonne.html
CC-MAIN-2014-52
refinedweb
216
56.08
0 Thanks in advance for any one who helps me. Code is in C using unix system calls. I am writing a code that forks a process and that forked process gets worked on by a function, in my case its called processone. I had a similar program, in which i passed a int value to processone and it worked, however, when i passed a char value to processone it went all buggy and my debugger says that the statement "else if ( forkedpid == 0 )" was useless. Then when I run it, the else if statement is totally ignored, even a print statement would not work with that else if statement. Am i not allowed to pass a char or string into process one? I don't see how that wold effect the statement. Below is my code #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdlib.h> void processone(int delay); void processtwo(); int main(int ac, char* av[]){ pid_t forkedpid; if ( (forkedpid = fork()) == -1 ) perror("fork problem"); else if ( forkedpid == 0 ) /*the problem is here*/ processone(av[1]);/*av[1] is a user input, char*/ else processtwo(forkedpid); return 0; } void processone(char avinput){ printf("processone does soemthing with %s",avinput); exit(10); } void processtwo(){ printf("processtwo does soemthing"); }
https://www.daniweb.com/programming/software-development/threads/213506/weird-forking-problem
CC-MAIN-2018-43
refinedweb
217
73.07
So there is a shared memory problem. We are using the REST template and a few solutions come to mind. Perhaps it is time to not rule out statics. The Controller component is established as a Singleton whose methods are called by every connection. It is possible to include a static synchronized static object to avoid. Java’s concurrent classes have a few of these. Synchronized classes and maps of locks are way more complicated and likely to slow things down. Synchronized methods in fact lock all Class level methods and attributes (e.g. synchronize(this)). As a warning though, the CopyOnWriteArrayList is thread safe but slow for writing to. The example below is of a ConcurrentHashMap<String,Integer> but the types are sometimes not showing, sorry. @RestController public class RESTClass{ private static ConcurrentHashMap<String,Integer> mp = new ConcurrentHashMap<String,Ingeter>(); }
https://dadruid5.com/2016/01/28/a-neat-little-rest-trick/
CC-MAIN-2020-34
refinedweb
141
59.3
For instance, the real price of the house with size of 1330 is 6,500,000 €. In contrast, the predicted house price of the trained target function is 7,032,478 €: a gap (or error) of 532,478 €. You can also find this gap in the chart above. The gap (or error) is shown as a vertical dotted red line for each training price-size pair. To compute the cost of the trained target function, you must summarize the squared error for each house in the example and calculate the mean value. The smaller the cost value of J(θ), the more precise the target function's predictions will be. In Listing 3, the simple Java implementation of the cost function takes as input the target function, the list of training records, and their associated labels. The predicted value will be computed in a loop, and the error will be calculated by subtracting the real label value. Afterward, the squared error will be summarized and the mean error will be calculated. The cost will be returned as a double value: public static double cost(Function<Double[], Double> targetFunction, List<Double[]> dataset, List<Double> labels) { int m = dataset.size(); double sumSquaredErrors = 0; // calculate the squared error ("gap") for each training example and add it to the total sum for (int i = 0; i < m; i++) { // get the feature vector of the current example Double[] featureVector = dataset.get(i); // predict the value and compute the error based on the real value (label) double predicted = targetFunction.apply(featureVector); double label = labels.get(i); double gap = predicted - label; sumSquaredErrors += Math.pow(gap, 2); } // calculate and return the mean value of the errors (the smaller the better) return (1.0 / (2 * m)) * sumSquaredErrors; } Training the target function Although the cost function helps to evaluate the quality of the target function and theta parameters, respectively, you still need to compute the best-fitting theta parameters. You can use the gradient descent algorithm for this calculation. Gradient descent Gradient descent minimizes the cost function, meaning that it's used to find the theta combinations that produces the lowest cost (J(θ)) based on the training data. Here is a simplified algorithm to compute new, better fitting thetas: Within each iteration a new, better value will be computed for each individual θ parameter of the theta vector. The learning rate α controls the size of the computing step within each iteration. This computation will be repeated until you reach a theta values combination that fits well. As an example, the linear regression function below has three theta parameters: Within each iteration a new value will be computed for each theta parameter: θ0, θ1, and θ2 in parallel. After each iteration, you will be able to create a new, better-fitting instance of the LinearRegressionFunction by using the new theta vector of {θ0, θ1, θ2}. Listing 4 shows Java code for the gradient descent algorithm. The thetas of the regression function will be trained using the training data, data labels, and the learning rate (α). The output of the function is an improved target function using the new theta parameters. The train() method will be called again and again, and fed the new target function and the new thetas from the previous calculation. These calls will be repeated until the tuned target function's cost reaches a minimal plateau:. In this case, although the cost will no longer decrease significantly after 500 to 600 iterations, the target function is still not optimal; it seems to underfit. In machine learning, the term underfitting is used to indicate that the learning algorithm does not capture the underlying trend of the data. Based on real-world experience, it is expected that the the price per square metre will decrease for larger properties. From this we conclude that the model used for the training process, the target function, does not fit the data well enough. Underfitting is often due to an excessively simple model. In this case, it's the result of our simple target function using a single house-size feature only. That data alone is not enough to accurately predict the cost of a house. Adding features and feature scaling If you discover that your target function doesn't fit the problem you are trying to solve, you can adjust it. A common way to correct underfitting is to add more features into the feature vector. In the housing-price example, you could add other house characteristics such as the number of rooms or age of the house. Rather than using the single domain-specific feature vector of { size } to describe a house instance, you could usea multi-valued feature vector such as { size, number-of-rooms, age }. In some cases, there aren't enough features in the available training data set. In this case, you can try adding polynomial features, which are computed by existing features. For instance, you could extend the house-price target function to include a computed squared-size feature (x2): Using multiple features requires feature scaling, which is used to standardize the range of different features. For instance, the value range of size2 feature is a magnitude larger than the range of the size feature. Without feature scaling, the size2 feature will dominate the cost function. The error value produced by the size2 feature will be much higher than the error value produced by the size feature. A simple algorithm for feature scaling is: This algorithm is implemented by the FeaturesScaling class in the example code below. The FeaturesScaling class provides a factory method to create a scaling function adjusted on the training data. Internally, instances of the training data are used to compute the average, minimum, and maximum constants. The resulting function consumes a feature vector and produces a new one with scaled features. The feature scaling is required for the training process, as well as for the prediction call, as shown below: // create the dataset List<Double[]> dataset = new ArrayList<>(); dataset.add(new Double[] { 1.0, 90.0, 8100.0 }); // feature vector of house#1 dataset.add(new Double[] { 1.0, 101.0, 10201.0 }); // feature vector of house#2 dataset.add(new Double[] { 1.0, 103.0, 10609.0 }); // ... //... // create the labels List<Double> labels = new ArrayList<>(); labels.add(249.0); // price label of house#1 labels.add(338.0); // price label of house#2 labels.add(304.0); // ... //... // scale the extended feature list Function<Double[], Double[]> scalingFunc = FeaturesScaling.createFunction(dataset); List<Double[]> scaledDataset = dataset.stream().map(scalingFunc).collect(Collectors.toList()); // create hypothesis function with initial thetas and train it with learning rate 0.1 LinearRegressionFunction targetFunction = new LinearRegressionFunction(new double[] { 1.0, 1.0, 1.0 }); for (int i = 0; i < 10000; i++) { targetFunction = Learner.train(targetFunction, scaledDataset, labels, 0.1); } // make a prediction of a house with size if 600 m2 Double[] scaledFeatureVector = scalingFunc.apply(new Double[] { 1.0, 600.0, 360000.0 }); double predictedPrice = targetFunction.apply(scaledFeatureVector); As you add more and more features, you may find that the target function fits better and better--but beware! If you go too far, and add too many features, you could end up with a target function that is overfitting. Overfitting and cross-validation Overfitting occurs when the target function or model fits the training data too well, by capturing noise or random fluctuations in the training data. A pattern of overfitting behavior is shown in the graph on the far-right side below: Although an overfitting model matches very well on the training data, it will perform badly when asked to solve for unknown, unseen data. There are a few ways to avoid overfitting. - Use a larger set of training data. - Use an improved machine learning algorithm by considering regularization. - Use fewer features, as shown in the middle diagram above. If your predictive model overfits, you should remove any features that do not contribute to its accuracy. The challenge here is to find the features that contribute most meaningfully to your prediction output. As shown in the diagrams, overfitting can be identified by visualizing graphs. Even though this works well using two dimensional or three dimensional graphs, it will become difficult if you use more than two domain-specific features. This is why cross-validation is often used to detect overfitting. In a cross-validation, you evaluate the trained models using an unseen validation data set after the learning process has completed. The available, labeled data set will be split into three parts: - The training data set. - The validation data set. - The test data set. In this case, 60 percent of the house example records may be used to train different variants of the target algorithm. After the learning process, half of the remaining, untouched example records will be used to validate that the trained target algorithms work well for unseen data. Typically, the best-fitting target algorithms will then be selected. The other half of untouched example data will be used to calculate error metrics for the final, selected model. While I won't introduce them here, there are other variations of this technique, such as k fold cross-validation. Machine learning tools and frameworks: Weka As you've seen, developing and testing a target function requires well-tuned configuration parameters, such as the proper learning rate or iteration count. The example code I've shown reflects a very small set of the possible configuration parameters, and the examples have been simplified to keep the code readable. In practice, you will likely rely on machine learning frameworks, libraries, and tools. Most frameworks or libraries implement an extensive collection of machine learning algorithms. Additionally, they provide convenient high-level APIs to train, validate, and process data models. Weka is one of the most popular frameworks for the JVM. Weka provides a Java library for programmatic usage, as well as a graphical workbench to train and validate data models. In the code below, the Weka library is used to create a training data set, which includes features and a label. The setClassIndex() method is used to mark the label column. In Weka, the label is defined as a class: // define.
https://www.javaworld.com/article/3224505/application-development/machine-learning-for-java-developers.html?page=2
CC-MAIN-2018-22
refinedweb
1,688
55.24
On 03/30/2011 07:42 PM, Justin P. Mattock wrote:> On 03/30/2011 10:17 AM, Avi Kivity wrote:>>?>>>> at the moment I see:> (keep in mind my reading skills only go so far!)>> grep -Re base_address kvm/* -n> kvm/ioapic.c:276: return ((addr >= ioapic->base_address &&> kvm/ioapic.c:277: (addr < ioapic->base_address + > IOAPIC_MEM_LENGTH)));> kvm/ioapic.c:371: ioapic->base_address = > IOAPIC_DEFAULT_BASE_ADDRESS;> kvm/ioapic.h:38: u64 base_address;>> so changing base_addresss; to base_address; gets kvm_ioapic_reset to > function correctly as well as ioapic_in_range?> (but could be wrong)>Can you explain how kvm_ioapic_reset() would be affected by the change?Really, you need to understand what you're doing before sending patches.-- error compiling committee.c: too many arguments to function
https://lkml.org/lkml/2011/3/31/116
CC-MAIN-2017-17
refinedweb
120
71.92
Welcome to the Parallax Discussion Forums, sign-up to participate. DavidZemon wrote: » No Linux offering? Also coming soon? Or was there a problem during compilation/packaging? What’s New? If you have used a previous version of SimpleIDE, this section explains what differences to expect with the new version of the software. SimpleIDE v1-0-0 to v1-1-0 Replaced loader subsystem (Propeller-Load) with new loader subsystem (PropLoader). Added wireless (Wi-Fi) support for programming/debugging via Parallax Wi-Fi Module (#32420). Wireless Propellers appear in port field when available; re-namable via Tools > Rename Port. Enhanced download speed (by 6x) for both wired (USB) and wireless (Wi-Fi) connections (requires on-board 5 MHz crystal). Mac installer now includes FTDI Driver and requires system restart as needed for proper FTDI driver operation. SimpleIDE relies on persistent storage of properties in all OSes. Updated SimpleIDE packages replace these properties during the SimpleIDE Library Install Workspace update. Improved terminal performance. Adjusted terminal to wrap to page by default. Fixed Find/Replace to include the first character of the search term it finds. Sets focus to editor after closing Find/Replace dialog to enable quicker manual replacements. Increased contrast on "found" item (in Find/Replace operations). Allows .spin object to be added to projects for library creation. Simplified memory model list to exclude XMM. Existing XMM applications may be compiled and downloaded with previous versions of SimpleIDE and Propeller GCC. #include "simpletools.h" #include "wifi.h" int main() { wifi_start(9, 8, 115200, USB_PGM_TERM); print("Leave a Network\r"); // Leaves network where it was a station and sets // the Wi-Fi module's mode to AP. wifi_leave(AP); // Verify mode after leaving the network. int mode = wifi_mode(CHECK); switch(mode) { case STA: //0xf4: print("mode=STA\r"); break; case AP: //0xf3 print("mode=AP\r"); break; case STA_AP: //0xf2 print("mode=STA+AP"); break; } } Wi-Fi Module Firmware Download + Propeller C tutorial activities. It can be downloaded and installed from. Parallax WX Wi-Fi Module for Prop C Connect WX Wi-Fi Module to Your Propeller Rsadeika wrote: » With the Parallax WiFi, does it have an LED that turns on or flashes when give it some power. While I am thinking about it, is the WiFi sip module a 5V or 3.3V unit? Ray The new libs that were added: datetime, display, light, social, and time, but did not see anything that was WiFi. I find it kind of strange, that it has datetime and time, which both contain the same libdatetime. Not sure where they are going with that. The social lib is for working with the Hackable Badge, while the light lib, not sure what that is for. I believe the display lib is for working with the OLED display. I am still a little disappointed that the IR Tx/Rx functions were not broken out from the Hackable Badge lib. It would be kind of nice if you had the IR setup on the Activity Bot, and you could have a couple of Bots or many Bots passing information between them. So, you would have a cluster of Bots talking to each other via the IR, and then you would be able to pick up some information on your browser program via the WiFi. Something like that could get me interested in working with a cluster of Activity Bots. So far, the new SimpleIDE 1.1.0, seems like it runs just like the previous version, no new major things to learn. Still not sure why WiFi lib was not made available from within SimpleIDE, but it took quite awhile before they added the badge lib. A .spin object to be added to a project, I will have to read or investigate further as to how that is accomplished. The last item, I guess there is no more support for using memory beyond 32K. Which kind of makes sense, since Parallax does not have any boards with that capacity, since they discontinued the C3. It has been mentioned that there is no Linux version, I also noticed that there is no Raspberry Pi version either. I am still trying to make an evaluation as to whether I will be using the WiFi capabilities or stick with the XBee; in either case I will be using the new SimpleIDE version. Ray I was going to wait a little longer until the Learn site had some better coverage and instructions as to how too best use the AB WX+Parallax WiFi, but I do have my own time line on this. I hope I am not making a big mistake, but what is $100, these days? By the time the package gets here, I will have played around with the new SimpleIDE, and become more familiar with its new stuff, so I will be able to make better informed comments about it. Ray I feel certain your budget will be well spent, as you'll be doing it "the easy way". Well- OK, maybe you'll still have a path of discovery to enjoy (or endure?)... but what I mean is that at least you won't be starting the adventure having to deal with hardware mismatches from what the published examples are based on. And hopefully a larger crowd with the same boards will be able to relate (even learn from) your development reports. Fantastic! ps. If you don't have spare male-to-male jumpers, it would be worth getting some of those also, for hooking the WiFi and AB-WX together. You need 4 or 5 as I recall.This sort of thing: Edit: Apologies- seems you won't need jumpers for wifi programming, although they are still jolly useful things! Highly recommend it. Note: I am using Windows 10 tablet. Thanks Jim- I've corrected my post. Users who wish to use SimpleIDE versions 1.1+ on these platforms can compile from the source of our Github Repository. View our Github Releases page for relevant links and version information. I was also thinking about switching over to Linux, but I guess I will have to stick with Windows. I am not going to get into compiling from source. Now that we have the Parallax WiFi, who needs a Raspberry Pi. Interesting times, interesting times indeed. PropWare: C++ HAL (Hardware Abstraction Layer) for PropGCC; Robust build system using CMake; Integrated Simple Library, libpropeller, and libPropelleruino (Arduino port); Instructions for Eclipse and JetBrain's CLion; Example projects; Doxygen documentation I was doing some look-see in the Learn site for the support of the WiFi for PropC, and the conclusion, the stuff is very scattered. You definitely must download the WiFi module firmware zip file, that contains the libwifi folder which is necessary to do things. It also contains some example files such as html, side, sh. Since Parallax is no longer offering pre-compiled installation downloads for Linux, I am not sure why the .sh stuff is in there. I think it will just confuse some people, like myself as to what you are supposed to do with them. Maybe a separate package would be a better attempt. As to the libwifi folder maybe some instruction as to how to get global access to it from within SimpleIDE would be nice. Some of the examples of the PropC variety, like using the IR, have some instructions as to where to go to find further instructions gets, a little confusing; not sure if I am ready for an Easter egg hunt type of instruction. Now I will probably have to find a good pdf tutorial for working with the html end of things. Plus, I have to start looking into some kind of tablet for using some of the html files, and/or control of the project(s) that the new AB WX will contain. I sure hope that the Learn site starts to get a little easier to use. Ray Perhaps you were looking in the wrong place on Learn. There is currently only one location for Prop C wifi tutorials: It is all available in one book, accessible from the front page of Learn or by accessing the Propeller C tutorial list. Ray Sounds like you're expecting more polish, maybe like a Boe-Bot kit? When we first released that product, its documentation and support was very different from what is today. We are still uploading tutorial pages with step-by-step instructions. There are nineteen pages so far. A 20th should come online today, and there's more in the queue. After the first group is posted, they'll receive lots of corrections, additions, adjustments, and enhancements. If you have any questions, edits, or suggestions, please send them to learn@parallax.com. The Wi-Fi module's documentation, firmware, examples and library are all designed to evolve with input from Parallax and the community. That is one of the reasons we are not bundling it with SimpleIDE yet. Instead, the firmware, examples and library are bundled together so that if firmware changes necessitate library and/or example changes, it's all in sync. If it were in the Simple Libraries, the examples might be out of sync with a newer firmware revision. "Documentation wifi Libary.html" lives in the libwifi folder. Perhaps it would be better to bring it up to Examples when it's not bundled with SimpleIDE. Andy First item at the bottom of the page, WiFi Module Firmware, then once you click on that, you get the following page: So once you download and unzip the file, there is an examples folder, I guess that is not part tutorial, OK I will not read that, who needs examples anyway.:-) Need I go any further? Ray I used the USPS delivery system, and I did notice that my package was squashed. It looks like the items were still in one piece, but I will not be sure if they work until I use them. I think you need more bubble stuff on the inside, just too make sure. Since I got an AB WX, WiFi dip and sip, I am not sure which one to start with, the dip or the sip. I was thinking since I have an original AB, maybe I should do a test run with that and the sip WiFi, just in case I mess something up. With that train of thought, if the WiFi module gets corrupted, is there a way to burn replacement firmware, or is it SOL? I know that when I was working with my ESP8266 module something did go wrong, but luckily there are readily available ways to burn the firmware again. A general note about the Learn tutorial, you may want to consider isolating and simplifying the instructions for first time users. I was looking for a simple plug and play method. On the second page of the tutorial you list about five different ways of connecting. That would be useful after you figure what you are doing, but a total distraction for somebody that is expecting a plug and play. Now to figure out what my next step will be. Ray When I want to switch to all Wi-Fi (programming, debugging and Wi-Fi app data), I just switch the SEL jumper to 3.3 V, and change the wifi_start to wifi_start(31, 30, 115200, WX_ALL_COM); Even when I'm routine everything through Wi-Fi, I leave the P9-DO and P8-DI jumpers in place for when I want to switch back. Just make sure your program isn't setting either P9 or P8 high or low. I know that with the ESP8266 NodeMCU module that I have, you plug into the USB port, and access it with a terminal program, you know very quickly if everything is in order. With the Parallax WiFi, does it have an LED that turns on or flashes when give it some power. While I am thinking about it, is the WiFi sip module a 5V or 3.3V unit? Ray Yes, on your Activity Board WX, look straight down on the top of the WX module and you'll see power, assoc, and do/di lights. The Activity Board, also has di, do, and assoc lights. With the WX module, there is a web page you go to. Keep going through the tutorials and you'll see it. Andy We currently have documentation for the SIP module on a Board of Education + BS2. We didn't expect anybody trying to use the SIP module with an Activity Board since there's already a socket. There is a schematic in the BS2 tutorials. You can probably use that.
http://forums.parallax.com/discussion/165928/simpleide-wifi
CC-MAIN-2017-22
refinedweb
2,116
71.24
. List of Integer to int array in Java import java.util.Arrays; import java.util.List; import org.apache.commons.lang.ArrayUtils; /** * Java program to convert List of Integers into int array using Apache commons ArrayUtils class. * * @author Javin Paul */ public class IntegerListToIntArray { public static void main(String args[]) { List<Integer> numbers = Arrays.asList(1,2,3,4,5,6); System.out.println("List of Integers : " + numbers); // toArray() can return Integer array but not int array Integer[] integers = numbers.toArray(new Integer[numbers.size()]); // ArrayUtils of Apache Commons can change an Object array to primitive array int[] primitives = ArrayUtils.toPrimitive(integers); // Let's see what does this int array contains System.out.println("Array with primitive int : " + Arrays.toString(primitives)); } } Output List of Integers : [1, 2, 3, 4, 5, 6] Array with primitive int : [1, 2, 3, 4, 5, 6] As you can see, It's pretty straight forward to convert List of Integers to int array, though it requires more than one method call to do that. It would have been much better, if toArray() can return primitive arrays as well. On similar note, conversion of Arrays are bit tricky in Java as int[] != Integer[] , so keep that in mind while writing Java API. Prefer List over Array for public methods, if you had to accept arrays, try to minimize scope of those method by making them private or package-private. 2 comments : Hi, Thanks for posting yet another article. I usually read most of the new ones. I have one comment regarding the format of code you write. It is not readable with black background. Is it in your control to change it? This is what I don't like, there is no direct generic way to convert Collections to array, since array doesn't support Generics, you can not create T[], which means you have to rely on overloaded method to convert list of integers to int array, list of Float to float array, List of Double to double array and so on....
http://javarevisited.blogspot.com/2013/05/how-to-convert-list-of-integers-to-int-array-java-example-tips.html
CC-MAIN-2014-10
refinedweb
336
56.25
Hello Paul, Bob and others listening, > > · even though the C compiler might be able to deal with 64-bit integer > > values, > > this must *not* be the case with the C pre-processor: > > > > #define ULLONG_MAX 18446744073709551615ULL > > > > the C compiler (gcc v2.7.2.1) *is* able to deal with that value, but the > > cpp can't > > Ouch. Thanks for reporting the problem; this is due, I think, to a > change installed in January. Can you please try the following private > snapshot instead? > > THX, I've downloaded it during the past 40 minutes and tried it out. Your fix solves this specific problem without further patching. But there's a new problem, although it falls into the same category, inside file lib/gethrxtime.c at line 70: the header file xtime.h defines: # if HAVE_LONG_LONG typedef long long int xtime_t; # define XTIME_PRECISION 1000000000LL # else ... #endif Again cpp groks about the `LL' modifier. --- > > · lib/getdate.y: > > I'm using bison v1.28 - and for me it's unacceptable, that this grammar > > can't be processed corrrectly with this older version, > > You shouldn't need to process it at all, since getdate.c is present in > the source distribution. Perhaps the time stamps on your files were > corrupted? No, I always reproduce every generated files... > > it should also be processed by stock berkeley yacc > > But that wouldn't support reentrant parsers. getdate needs to be > reentrant, for other projects. It should not be a problem anyway; > you shouldn't need to run either Bison or Yacc. O.K., reentrancy is an argument, but IMHO v1.28 does support pure parsers, although it might not be stated inside the info-pages. The specific point I meant was the directives %parse-param and %lex-param. This older version doesn't know about those directives, although there are defines for declaring them a little bit different, e.g. YYPARSE_PARAM and YYLEX_PARAM, if I remember it right - but you should know better, as I now know, where I heard your name from, as you're hacking on bison too. > > BTW, is anyone able to guarantee me, that bison v2.0 has not even one > > problem with processing older (and oldest - I'm using software packages > > dated in the early 80's) grammar files? > > Someone could guarantee you that, yes, if you paid them enough. :-) Yeah. :-) In the meanwhile I tried out bison v2.1, but wasn't successful with some grammar files, where I had to stuff together three SQL-select parsers using one flex-scanner and therefore had to, maybe misuse the C pre-processor, so I'll stick to my old version locally. > > · --disable-nls: > > IMHO there is no need, if I decide to configure *wihtout* NLS support, > > which I usually do, to setup a specific locale, > > --disable-nls affects only diagnostics and the like: it does not > disable all usages of locales. For example, LC_CTYPE still affects > whether something is considered to be a letter. Alright, so I am definitely wrong here. > > the man-page should *always* reflect the various options, for which a > > command was configured for > > The dd man page has changed in the latest CVS version; perhaps the > point is moot now. To be honest I didn't fully follow your comments. > "info coreutils dd" works on my host and that is what the man page suggests. All pre-processed man-pages refer to the info-pages as: info <cmd>, but that should be named: info coreutils <cmd>. To fix this problem for *all* man-pages inside the coreutils package you should extent the specific rule somewhat: # snipped from man/Makefile .x.1: @rm -f $@ @echo "Updating man page $@"; \ mkdir $t; \ (cd $t && $(LN_S) ../../src/$(mapped_name) $*); \ $(PERL) -- $(srcdir)/help2man \ --include=$(srcdir)/$*.x \ --output=$t/$@ $t/$* \ --info-page="coreutils $*" @sed 's|$*\.td/||g' $t/$@ > $@ @chmod a-w $@ @rm -rf $t The neccessary parameter is: --info-page="coreutils $*" That way the man-page clearly state the command to type as: info coreutils <cmd> without the need to name each command inside the info/dir file explicitely. E.g.: my info entry looks like this: * Coreutils: (coreutils). Core GNU utilities (v5.2.1). But there is *no* entry like that: * dd: (coreutils)dd invocation. Copy and convert a file. Typing `info dd' results in an error message, that info can't find an entry for `dd', but calling it `info coreutils dd' info knows to open the coreutils info file and looking up the dd command there, which succeeds. > > · factor: > > it's increddible - your factor command is *not* able to factorize negative > > values > > Patches would we welcome here. #include <limits.h> void factor( signed int num, ...) { switch ( num) { case 0: printf( "0:\n"); return ; case 1: case -1: printf( "%d: %d\n", num, num); return ; case INT_MIN: printf( "%d: -1 2 ", num); /* INT_MIN is *always* even */ num= 1 << ( sizeof( num)* CHAR_BIT- 2); break; default: printf( "%d: ", num); if ( num < 0) { printf( "-1 "); num= -num; } break; } /* factorize as usual */ ... } BTW, wouldn't it be correct to write 1: 1 instead of 1: as 1 can be factorized by itself? > > ·. IMHO it's an important user-visible bugfix, if the stat command doesn't state success if it fails to stat a file, e.g. I found this problem while extending my shell-script for burning CD's and I had to check the size for pre-built ISO-images instead of creating them on the fly: fsize="`stat -c '%s' \"$fname\"`" || fail "unable to stat file \´$fname'" But as the stat command delivers success the value of fsize is not a number, so I had to work around this problem by prepending: [ ! -e "$fname" ] && fail "unable to stat \`$fname'" fsize="`stat -c '%s' \"$fname\"`" But even here there is a chance, that the stat command may fail - so I'm sure you'll see the user-visiblity of this specific bugfix now? > > · performance of the dd command: > > the execution speed of dd sucks heavily, > > Can you give a specific example of the problem? A shell transcript > would help. #!/bin/bash -f # mstart -> mend == msize mstart=70628 mend=57910964 msize=$[ $mend- $mstart] fname=The-Chubb-Chubbs.352x288.mpeg.avi echo "dd bs=1c count=$mstart if=$fname of=z.0" dd bs=1c count=$mstart if=$fname of=z.0 echo "dd bs=1c skip=$mend if=$fname of=z.N" dd bs=1c skip=$mend if=$fname of=z.N # dd: 2:45 minutes (v5.2.1) # dd: 2:50 minutes (v5.3.0) echo "dd ibs=1c obs=32k skip=$mstart count=$msize if=$fname of=z.mpeg" dd ibs=1c obs=32k skip=$mstart count=$msize if=$fname of=z.mpeg # sdd: 1:03 minutes echo "sdd ibs=1 obs=32k iseek=$mstart count=$msize if=$fname of=z.mpeg" sdd ibs=1 obs=32k iseek=$mstart count=$msize if=$fname of=z.mpeg The above file is an award winning short movie in 2003 taken from Sony's home-page, although I don't know the actual link anymore - sorry for that. The offsets are only true for the german version of this movie. The AVI file is in CD-XA format and the task is to extract the mpeg movie stream out of this container. Even though sdd is slow too in this case, it's faster than dd. To give you a clue - a quick and dirty C hack needs less than 4 seconds to extract the 57 MB mpeg stream (the last dd invocation), working with 32 kB buffers (this size performs best for my old SCSI drives). At least for me there are several tasks, where I need to extract some portions out of the middle of some bigger file and especially in this case dd (and even sdd) is very slow, as there is no other way - at least I see no combination of options, which does the same - to perform this task with dd. The time-consuming task for dd is, that the input stream will be fetched one byte at a time, although it could be fetched in larger chunks, after the initial seek into file (if it's seekable, of course) has been done. A solution might be to classify the input stream in order to detect, if it's a special device, where it must be fetched one byte at a time, and otherwise larger chunks could be read to speed this common case up? > Thanks again for your comments. (Though we don't really need to know > about your sex life....) Yeah I know... ;-) But it's my way to tell people, that there are many other pleasurable things to me like re-compling my complete system again and again... I'm sure you know exactly, what I want to say. BTW, before I forget - I'd like to suggest an extention to the expr command: it would be nice, if expr could handle the C shifting operators `<<' and `>>' as well as the ternary opertor `? :'... But there might be a chance, that POSIX says something different... THX for listening. CU Tom. (Thomas M.Ott) Germany
http://lists.gnu.org/archive/html/bug-coreutils/2005-09/msg00213.html
CC-MAIN-2017-04
refinedweb
1,513
71.44
Michael Foord (Fuzzyman) I have been developing with Python for nearly four years, and have been working with IronPython for around eighteen months now. I am the author of the following Python projects: I'm particularly grateful to IronPython. Because of it I'm now able to earn a living programming with Python, for Resolver Systems. I've written several articles and tutorials on Python, and I'm currently writing a book, IronPython in Action, for Manning publications. Resolver Systems is a small company (6 developers but looking to hire) based in London. Resolver Systems was created to develop a new business application, aimed at the financial services market. It is currently in use with our first few customers and a small number of people in our private beta test program. We hope to move to a wider beta test phase soon. Resolver the company started in late 2005, and I joined in April 2006. At this stage IronPython was still in alpha. Resolver is a Rapid Application Development tool with a spreadsheet interface. There is both a desktop version and a fledgling Resolver Web Server. around thirty thousand lines of production plus eighty thousand lines of test code. About 1% of the production code is in C# and the rest is IronPython. IronPython in Action is a book that I and a colleague are writing on IronPython. It was started earlier in the year, and just as I finished the first part I had to rewrite it because Microsoft released Silverlight and IronPython 2! The first five chapters are now available via Manning's 'early access program', where you get to access the book as it is written. The first five chapters are an introduction to IronPython, Python and the .NET framework. It goes through creating an example structured IronPython application. The rest of the book will be more 'recipe focussed' covering a range of topics like testing, ASP, databases and web services, embedding and extending IronPython and of course a lot more. This talk is inspired by the talk on dynamic languages by John Lam and Jim Hugunin from Mix 07. You can watch the video. To inspire you as to what is possible with Silverlight and give you enough details to start experimenting. Why use IronPython? Microsoft are serious about IronPython and dynamic languages for the .NET framework. Microsoft have built IronPython support into the following. Silverlight is a sandboxed browser plugin for creating rich client-side web applications. It runs on Windows and Mac OS, supporting Firefox, IE and Safari (with support for more browsers on the way).. Version 1.0 is just out and focuses on the streaming media capabilities. Version 1.1 is still in alpha and ships with a cut down version of the CLR (the core of the .NET framework). It can be programmed with C# or any of the DLR languages which includes IronPython. All the examples I show here require Silverlight 1.1 Alpha Refresh Visit the Showcase for some of the funky things that Silverlight can do. There is also a set of examples using IronPython at codeplex.com/dynamicsilverlight. Silverlight separates presentation from code (design from development), through XAML. This is an XML markup for creating user interfaces, including hooking up events and defining animations. This is intended to be created by tools like Expression Blend (currently in free beta). There is also a version for Mono called 'Lunar Eclipse' under development. What Silverlight doesn't come with yet is very many 'controls' for building user interfaces. You have to create everything yourself. There is already quite a range of 'third party' interface components being created (including someone implementing the Windows Forms API for both Silverlight and Flash!) and there will be controls included in the final version of Silverlight 1.1. Because of this (and because it is a shame to throw away everything we already know about clientside browser programming, and all the great libraries that are available), part of what we will be looking at is how to use Silverlight with the browser DOM and (normal) Javascript. The DLR: a dynamic language runtime that can run dynamic languages on .NET and in Silverlight. This means lots of dynamic languages - IronPython, Ruby, Visual Basic, Javascript. As well as IronPython Microsoft are developing IronRuby. Dynamic languages DLR languages already available, and under development, built on top of the DLR currently include:.: The XAML defines a tree of objects that represent the user interface. You can use this to create elements of the interface include animations and hook-up events. The XAML is actually compiled. Almost anything that can be done with XAML can be done from code (not yet animations). For example, TextBlock XAML elements have a corresponding TextBlock class. Although I am generally no fan of visual design tools, nor of writing XML by hand, it can be more verbose to do things in code than to use XAML. Dynamic languages are particularly good at manipulating test, and XAML is just text, so you can dynamically generate and consume XAML. Let's look at the five files you need for a minimal IronPython Silverlight application. <script type="text/javascript" src="Silverlight.js"></script> <script type="text/javascript" src="CreateSilverlight.js"></script> </head> <body> <div id="SilverlightControlHost"> <script type="text/javascript"> CreateSilverlight(); </script> </div> The webpage that embeds the Silverlight control. It references the two Javascript files and calls the CreateSilverlight function. parent_element = document.getElementById('SilverlightControlHost'); control_id = "SilverlightControl"; function CreateSilverlight() { Silverlight.createObject( "minimal.xaml", parent_element, control_id, {width: '640', height: '480', version: '1.1'}, {onError: null, onLoad: null}, null ); } Silverlight.js is provided by Microsoft is the code that actually sets up the control, and presents a download button if Silverlight isn't installed. CreateSilverlight.js is where you initialize the control. Silverlight.createObject initializes the control (you can alternatively use createObjectEx which takes a single object with named members). You can configure the size of the Silverlight control, specify the XAML file to use, and provide Javascript functions to call once the control has been created or in case of an error (onError and onLoad). <Canvas x: <x:Code <Canvas x: <TextBlock x: Hello World from XAML </TextBlock> </Canvas> The XAML file defines a root canvas that will be loaded when the Silverlight control is created. The Python file is loaded using <x:Code. In order to hook up the Python code to our XAML we use a 'helper loader' canvas that calls the Python function OnLoad when it is loaded. This slightly different from how you create C# projects (where the Canvas is associated with a class in an assembly that extends the Canvas object). This XAML also has a TextBlock with a name and some text. We will manipulate this from the IronPython file. It gets a reference to the TextBlock created from XAML and changes the text on it. As with the normal IronPython we can use the clr module to add references to assemblies and we can import Python files which will be fetched from the server. To experiment with IronPython we'll use a simple tool I've created - the IronPython Web IDE. This is available online and you can also download it as a project... To illustrate using Silverlight with Javascript libraries to create a web application I've created an example 'Resolver in the Browser'. It is based on an early prototype of Resolver that was used to evaluate grids for suitability. This is a talk for Developers, not for Designers - so uhmm... it's probably not the best looking web application you've seen, but it all runs in the browser - with no server side activity. This is a minimal spreadsheet engine in around 400 lines of Python code. The view layer is done in Javascript, using the EditArea Javascript syntax highlighting code editor and the ExtJS Javascript grid. The data model, spreadsheet engine and a controller layer are all written in IronPython using Silverlight. The spreadsheet works by generating and executing Python code for the values and formulae in cells. You can also insert arbitrary Python code to be executed before the spreadsheet code (including setting cells). This is similar to the way that Resolver works. Formulae can be any valid Python expression. There is no extra syntax, so we can't work with cell ranges like we would be able to in a full spreadsheet. To understand what is going on we'll first need a quick lesson on spreadsheets. When we enter values in cells, corresponding Python code is generated and then executed to produce the results. This means that if we have a formula that references another cell (like =A1), then we must have already evaluated A1 before we evaluate this formula. We also need to know if there are any cyclic chains that can't be resolved sensibly (like cells that reference themselves). This is called dependency analysis, and determines the order that code for cells should be generated in. To work out what the dependencies are (which cells are referenced in a formula) we need to parse the expression (the full Resolver has its own formula langauge, based on Python expressions, and its own parser). Fortunately the IronPython parser is exposed, so there is come code in this spreadsheet that uses the IronPython parser to parse the expression into an AST (Abstract Syntax Tree). I then subclass one of the IronPython classes called the PythonWalker, which walks the AST and pulls out all of the Name nodes that match a regular expression for cell names. We then order the cells based on the resulting dependency graph (a topological sort) and execute them in order - generating errors for any cycles we find. The algorithm that does all that is actually very simple, a few lines of Python code. This spreadsheet does a full recalculation each time (in Resolver it is done on a background thread), this means that pre-formula code is executed every time - the spreadsheet is represented as a Python program. You can see in Excel that if you have functions in VBA, they aren't executed every time and results can get out of sync until you force a full recalculation. So when we enter a value or a formula in a cell, we need to trigger a recalculation in IronPython. Editting one cell may change the displayed value in several cells (any cells that depend on that cell will change), so we need to push the updated values back from IronPython to the Javascript grid. This means that we need to be able to call between Silveright and Javascript and vice versa. One thing that is worth noting. The ExtJS grid wasn't designed as a spreadsheet grid. The grid needs to display the values, but when in edit mode be editing the underlying formula rather than editing the displayed value. The grid just stores the displayed values, the formulae (the values to edit) are stored in the data model and need to be fetched when we enter edit mode. The details of all the hoops I needed to jump through to get this to work are on my blog. We use one technique to call into Silverlight from Javascript using one technique, and a slightly different one for calling from Silverlight into Javascript. Both of them are based on marking the class and or method that we are using with the .NET Scriptable attribute. Unfortunately we can't set attributes from IronPython, so we have to use a bit of C#. Fortunately we can just create a stub class, and override a method in a subclass in an IronPython subclass. The C# is simple enough that, even if you have never seen C# before, you should be able to understand it. The Scriptable attribute lives in the Ssytem.Browser.Net namespace. C# can be compiled using the Visual Studio 2008 Beta, which is currently available as a free beta. You will also need Visual Studio tools for Silverlight installed. XXX The Visual Studio Beta is a big download, and can be slow to startup. Fortunately you don't need this installed to compile assemblies for Silverlight - we'll see how in a few moments. You can download an example Visual Studio 2008 project containing the example C#: ScriptableProject.zip. using System; using System.Windows.Browser; [Scriptable] public class ScriptableForString { [Scriptable] public string method(string value) { return this._method(value); } public virtual string _method(string value) { return "override me"; } } C# for a Scriptable class with a Scriptable method that takes and returns a string look like: We need a Scriptable class with a Scriptable method. This should call down to virtual method that we can override in an IronPython subclass. If we want to pass and return arguments they need to be strongly typed, and can only be a primitive like a string or an integer. This isn't really a problem though because we can pass or return JSON as a string. There is a JSON serializer and deserializer available in Silverlight, and using it from Javascript is easy of course! To use this from IronPython we need to import the class from the assembly we have compiled. To add a reference from the assembly, we have to use the full name: Registering the scriptable object with the Silverlight control: One we have registered the scriptable object, it is then available on the control to be called from Javascript. We need to get hold of the Silverlight control (using the name set in the CreateSilverlight function): using System; using System.Windows.Browser; [Scriptable] public class ScriptableEvent { [Scriptable] public event EventHandler Event; public virtual void OnEvent(ScriptableEventArgs e) { Event(this, e); } } [Scriptable] public class ScriptableEventArgs : EventArgs { private string _val; [Scriptable] public string val { get { return _val; } set { _val = value; } } } This is the other side of the coin. To call into Javascript from IronPython (to set values in cells from the Spreadsheet engine), we need to register a ScriptableEvent. Arguments are passed by setting scriptable attributes on a scriptable event args. No need to subclass this time. In order to use this event, we have to assign a Javscript, the javascript function (some_function) is called and receives the arguments sender and our event args. The Javascript can modify the attributes on the event to return values. After the call returns, IronPython can look at the attributes on the event args to retrieve any return values. set sl=C:\Program Files\Microsoft Silverlight set csc=C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe %csc% /out:SilverlightApp.dll /t:library /nostdlib+ /noconfig /r:"%sl%\system.dll" /r:"%sl%\agclr.dll" /r:"%sl%\mscorlib.dll" /r:"%sl%\System.Core.dll" /r:"%sl%\System.Silverlight.dll" /r:"%sl%\System.Xml.Core.dll" *.cs pause See blog entry by Michael Schwarz. Actually you need two things installed, Silverlight and the .NET framework SDK. The SDK comes with a C# compiler (csc.exe), and we will create a batch file that tells csc to compile with references to the Sivlerlight DLLs instead of the standard framework ones. This batch file assumes the standard locations for your Silverlight and framework installs. The line starting with %csc% needs the arguments that follow all on one line. It tells csc not to use the standard .NET DLLs, but use the Silverlight ones instead. It compiles all the C# files in the directory (*.cs) into an assembly specified by the /out argument (/out:SilverlightApp.dll). You can download an example that will compile the C# scriptable examples: CompilingCSharp.zip.
http://www.voidspace.org.uk/ironpython/silverlight/pycon.html
CC-MAIN-2016-07
refinedweb
2,590
63.49
Previous Chapter: Formatted output Next Chapter: Sequential Data Types Next Chapter: Sequential Data Types IntroductionThere are hardly any computer programs and of course hardly any Python programs, which don't communicate with the outside world. Above all a program has to deliver its result in some way. One form of output goes to the standard output by using the print statement in Python. 1 >>> print "Hello User" Hello User >>> answer = 42 >>> print "The answer is: " + str(answer) The answer is: 42 >>>It's possible to put the arguments inside of parentheses: >>> print("Hallo") Hallo >>> print("Hallo","Python") ('Hallo', 'Python') >>> print "Hallo","Python" Hallo Python >>>We can see that the output behaviour changes as well. But more importantly: The output behaviour of version 2.x and version 3.x is different as well, as we can see in the following: $ python3 Python 3.2.3 (default, Apr 10 2013, 05:03:36) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print("Hello") Hello >>> print("Hello","Python") Hello Python >>>If you want the same output behaviour as in Python 3, you should use an import from the "future": Import from future: print_functionSome Python programs contain the following line: from __future__ import print_functionThis is sometimes a source of ambiguity. It looks as if we are importing a function called "print_function". What we are doing instead is that we set a flag. If this flag is set, the interpreter makes the print function available. We strongly recommend that you use this import, so that your programs will be compatible to the version 3 of Python. So you can go on to our version 3 introduction into the print function of our Python tutorial. Anmerkungen: 1 Starting with version 3.0, Python doesn't provide a print statement anymore, there is only a print function. Previous Chapter: Formatted output Next Chapter: Sequential Data Types Next Chapter: Sequential Data Types
http://python-course.eu/print.php
CC-MAIN-2017-09
refinedweb
321
54.52
P1. Implementing a simple classIn this lab, you will implement a vending machine. The vending machine holds cans of soda. To buy a can of soda, the customer needs to insert a token into the machine. When the token is inserted, a can drops from the can reservoir into the product delivery slot. The vending machine can be filled with more cans. The goal is to determine how many cans and tokens are in the machine at any given time.What methods would you supply for a VendingMachine class? Describe them informally. Now translate those informal descriptions into Java method signatures, such asvoid fillUp(int cans)Give the names, parameters, and return types of the methods. Do not implement them yet. What instance variables would you supply? Hint: You need to track the number of cans and tokens. P2. Implementing MethodsConsider what happens when a user inserts a token into the vending machine. The number of tokens is increased, and the number of cans is decreased. Implement a methodvoid insertToken() { instructions for updating the token and can counts}You need to use the instance variables that you defined in the previous problem.Do not worry about the case where there are no more cans in the vending machine. You will learn how to program a decision "if can count is > 0" later in this course. For now, assume that the insertToken method will not be called if the vending machine is empty. Now supply a method fillUp(int cans) to add more cans to the machine. Simply add the number of new cans to the can count. Next, supply two methods getCanCount and getTokenCount that return the current values of the can and token counts. (You may want to look at the getBalance method of the BankAccount class for guidance.) P3. Putting It All TogetherYou have implemented all methods of the VendingMachine class.Put them together into a class, like this:class VendingMachine { public your first method public your second method . . . private your first instance variable private your second instance variable } Now test your class with the following test program.public class VendingMachineTest { public static void main(String[] args) { VendingMachine machine = new VendingMachine(); machine.fillUp(10); // fill up with ten cans machine.insertToken(); machine.insertToken(); System.out.println("Token count = " + machine.getTokenCount()); System.out.println("Can count = " + machine.getCanCount()); } }What is the output of the test program? P4. ConstructorsThe VendingMachine class in the preceding example does not have any constructors. Instances of a class with no constructor are always constructed with all instance variables set to zero (or null if they are object references). It is always a good idea to provide an explicit constructor.In this lab, you should provide two constructors for the VendingMachine class: - a default constructor that initializes the vending machine with 10 soda cans - a constructor VendingMachine(int cans)that initializes the vending machine with the given number of cans Both constructors should initialize the token count to 0.</P>Place the code for your constructors here: P5. Discovering ClassesConsider the following task: You are on vacation and want to send postcards to your friends. A typical postcard might look like this:Dear Sue: I am having a great time on Sue Wetheridge the island of Java. The weather 1157 West Moreland Ave is great. Wish you were here! Sunnyvale, CA 95105 Love, USA Janice This is a task that lends itself to automation. You decide to write a computer program that sends postcards to various addresses, each of them with the same message, except that the first name is substituted to match each recipient.Using the rule stated in your textbook that certain nouns in the problem description are good candidates for classes, suggest some classes that you might implement in a postcard writing program:Your job is to identify the classes, not to actually implement them in Java. Now implement one of the classes in more detail. The left-hand side of the postcard is a message. Implement this as a Message class. A message has three essential properties: the sender ("Janice"), the recipient ( "Sue"), and the message text ("I am having...Wish you were here!").Implement a Message class with the following methods: - a constructor that takes two strings, the sender and the message text - a method setRecipient that sets the recipient - a method print that prints the message Try out your class with the following test code:public class MessageTest { public static void main(String[] args) { String text = "I am having a great time on " + "the island of Java. Weather's great." + "Wish you were here!"; Message msg = new Message("Janice", text); msg.setRecipient("Sue"); msg.print(); msg.setRecipient("Tim"); msg.print(); } }What is the output of your program? R1. Object ReferencesYou should be able to answer the following two questions without writing programs. If you like, you can write small test programs to double-check your answers.Recall that the translate method of the Rectangle class moves a rectangle by a certain amount. For example,Rectangle r = new Rectangle(5, 10, 20, 30); r.translate(10, 15);System.out.println(r); // prints Rectangle[x=15,y=25,width=20,height=30]When you copy an object variable, the copy is simply a second reference to the same object.Consider this program segment:Rectangle square = new Rectangle(0, 0, 100, 100);Rectangle r2 = square;r2.translate(10, 15);System.out.println(r2); System.out.println(square);What is the output of this code? A null reference is used to indicate that an object variable does not refer to any object. You cannot invoke methods on a null reference since there is no object to which the method would apply.Consider this program segment:Rectangle r3 = null; System.out.println(r3); r3.translate(10, 15); System.out.println(r3); Do the statements output anything beyond an error message? If so, what?
http://www.horstmann.com/bigj/labs/lab02.html
crawl-002
refinedweb
979
57.37
for connected embedded systems Programming Photon without PhAB We strongly recommend that you use PhAB to develop Photon applications-this chapter is for those who insist on not using PhAB.This chapter discusses the following: - Basic steps - Compiling and linking a non-PhAB application - Sample application - Connecting application code to widgets - Complete sample application Basic steps All applications using the Photon widget library follow the same basic sequence: - Include <Pt.h>, the standard header file for the widget library. - Initialize the Photon widget toolkit and create the main window using a call to PtAppInit(). - Create the widgets that make up the UI. The function PtCreateWidget() is used to create the widget and make it a child of a widget that has already been created, such as the main window. - Register any callback functions in the application with the appropriate widgets using PtAddCallback() or PtAddCallbacks(). - Realize the widgets by calling PtRealizeWidget(). This function needs to be called only once by the application. The realize step actually creates any Photon regions that are required and maps them to the screen. Until this step is performed, no regions exist, and nothing is displayed on the screen. - Begin processing photon events by calling PtMainLoop(). At this point, the Photon widget toolkit takes control over the application and manages the widgets. If any widgets are to call functions in your application, they must have been registered as callbacks before this. Compiling and linking a non-PhAB application To compile and run an application that uses the Photon widget library, you must link against the library. There are both static and shared versions of this library. The names depend on whether you're running under QNX 4 or QNX Neutrino: We recommended that you always link against the shared library. This lets you keep your applications smaller and allows them to inherit new features that are added to the widget library when new releases of the shared library are installed. The Photon library includes most of the function and widget definitions. If your application uses Px (extended) functions or realtime widgets, you'll also need to link with the following: Linking under QNX 4 To link against the shared library, specify the following link option for the cc command: -lphoton_s To link against the static library, specify the following link option: -lphoton For example, if we have an application called hello.c, the command to compile and link is: cc -o hello hello.c -lphoton_s Linking under QNX Neutrino Under Neutrino, the names of the shared and static libraries are the same. By default, qcc links against the shared library; to link against the static library, specify the -Bstatic option for qcc. For example, if we have an application called hello.c, the command to compile and link against the shared libraries is: qcc -o hello hello.c -lphoton -lm To link against the static libraries, the command is: qcc -o hello hello.c -Bstatic -lphoton -lm Sample application The following example illustrates a very simple application using the widget library. The program creates a window that contains a single pushbutton. /* * File: hello.c */ #include <Pt.h> int main( int argc, char *argv[] ) { PtWidget_t *window; PtArg_t args[1]; if ((window = PtAppInit(NULL, &argc, argv, 0, NULL)) == NULL) exit(1); PtSetArg(&args[0], Pt_ARG_TEXT_STRING, "Press to exit", 0); PtCreateWidget(PtButton, window, 1, args); PtRealizeWidget(window); PtMainLoop(); return (EXIT_SUCCESS); } What's going on Although this is a simple application, a lot of work is being done by each of these calls. PtAppInit() This PtAppInit() call: - reads any standard toolkit arguments from the command line - attaches a channel to the Photon server using PhAttach() - creates a window widget that is designed to interact with the window manager and serve as the parent for other widgets created in the application. The first argument to this function passes the address of PtAppContext_t, which is a pointer to a structure that manages all the data associated with this application. For Photon 1.1x, this must be specified as NULL, so that the default values are used. The second and third arguments are the common argc and argv. The toolkit parses these for standard toolkit options. The final two arguments are an argument list, preceded by the number of elements in the list. They're used to provide initial values for resources of the top-level window widget when it's created. A pointer to this widget is returned by PtAppInit(). This top-level widget will become the parent of subsequent widgets created in the application. See the Widget Reference for more information on this widget and its available resources. PtSetArg() The PtSetArg() macro is used to set up an argument list that will be used to initialize the button's resources when it's created. For more information, see the Manipulating Resources in Application Code chapter. PtCreateWidget() The call to PtCreateWidget() creates a push-button widget as a child of the window widget, using the argument list to initialize the button's resources. All the widgets in the application - except the top-level shell window - have a container widget as a parent. Container widgets may have other containers within them. Creating the widgets in the application produces a structure called the widget family. PtRealizeWidget() The function PtRealizeWidget() realizes the widget and all its descendants in the widget family. Realizing a widget causes it to be displayed. In our sample application, PtRealizeWidget() is called on the top-level shell window (which is the ancestor of all the widgets in the application), so all the widgets in the application are displayed when this routine is called. When the widget is realized, it uses the values of its resources to determine how big it must be to display its contents. Before realizing a widget, you should set any of the resources that may affect its size. You may change some of the resources after the widget has been realized, but it's up to the widget to determine if it can or will resize to accommodate the change in the resource's value. You can set flags that the widget will consult to determine whether or not to adjust its size in response to such changes, but note that if the widget exceeds the dimensions allocated to it by its parent, it will be clipped to the parent's size. There's no mechanism for the widget to negotiate with its parent to obtain more space. See the Geometry Management chapter for more information. If a Photon region is required to display the widget correctly, it's created each time the widget is realized. A region is required under any of the following conditions: - the widget sets a cursor - the widget needs to get events that aren't redirected to it by its parent container (e.g. boundary, pointer-motion events) - the Pt_REGION flag is set for the widget You can unrealize a widget by calling the PtUnrealizeWidget() function. This affects the visibility of the widget and its descendants, but not the rest of the widget family hierarchy. You can then redisplay the widget later by calling PtRealizeWidget() again. You can prevent a widget and its descendants from being realized when the widget's ancestor is realized. To do this, set Pt_DELAY_REALIZE in the widget's Pt_ARG_FLAGS resource. If you set this flag, it's the application's responsibility to call PtRealizeWidget() on the widget when the widget is to appear. PtMainLoop() Calling PtMainLoop() transfers control of the application to the Photon widget library. The widget library waits for Photon events and passes them on to the widgets to handle them. Application code is executed only when callback functions that the application has registered with a widget are invoked as a result of some event. Connecting application code to widgets If you compile, link, and run the sample application, you'll see that a window appears with a button in it. If you push the button, nothing happens because no application code has been associated with it. The Photon widget library is designed so that the UI code can be kept distinctly separate from the application code. The UI is composed of the code to create and manipulate the widget family hierarchy, and must call the application code in response to particular events or user actions. The connection between the application code and the UI that allows it to use the application code is the single point where these two parts have intimate knowledge of each other. Connections are made between the UI and the application code using callbacks and event handlers. A callback is a special type of widget resource that allows the application to take advantage of existing widget features. Using a callback, the application can register a function to be called by the widget library later in response to a particular occurrence within the widget. Event handlers are normally used to add capabilities to a widget. For example, you could add behavior to a button press inside a widget that has no callbacks associated with button-press events. Callbacks A callback resource is a special form of resource used to notify the application that a specific action has occurred for a widget (e.g. the user selects a button). Every callback resource for the widget represents some particular user behavior that the widget's author anticipated would be of interest to the application. As with all resources, a widget has its callbacks defined by its widget class, and it inherits the callbacks defined by all the ancestors of its class. This means that a widget may have several user actions that it can notify the application about. The value of a callback resource is a callback list. Each element of the list is an application function to be called in response to the behavior and client data associated with the callback. Client data is a pointer to any arbitrary application data the application may need to provide to the callback function for it to work correctly. For information about callbacks, see "Manipulating callbacks in your code" in the Creating Widgets in Application Code chapter. Event handling The writer of a widget class can't possibly anticipate every need of the application. The application may want to be notified of some occurrence on a widget that doesn't have an associated callback resource. In such cases, the application may use event handling functions. For information about event handlers, see "Manipulating event handlers in your code" in the Creating Widgets in Application Code chapter. Complete sample application We can now use our newly acquired knowledge of resources and callbacks to create a more functional version of the sample application given earlier. Using resources, we can give the pushbutton widget the same dimensions as the window, and specify which font to display the label in. We can also define the callback to be executed when the pushbutton is pressed. We'll make the callback function display a simple message and exit. Here's the complete source code for our sample program with these changes: #include <stdio.h> #include <stdlib.h> #include <Pt.h> int main( int argc, char *argv[] ) { PtArg_t args[3]; PtWidget_t *window; int push_button_cb( PtWidget_t *, void *, PtCallbackInfo_t *); PtCallback_t callbacks[] = {{push_button_cb, NULL}}; if ((window = PtAppInit(NULL, &argc, argv, 0, NULL)) == NULL) exit(EXIT_FAILURE); PtSetArg(&args[0], Pt_ARG_TEXT_STRING, "Press to exit", 0); PtSetArg(&args[1], Pt_ARG_TEXT_FONT, "helv14b", 0); PtSetArg(&args[2], Pt_CB_ACTIVATE, callbacks, sizeof(callbacks)/sizeof(callbacks[0])); PtCreateWidget(PtButton, window, 3, args); PtRealizeWidget(window); PtMainLoop(); return (EXIT_SUCCESS); } int push_button_cb(PtWidget_t *w, void *data, PtCallbackInfo_t *cbinfo) { printf( "I was pushed\n" ); exit( EXIT_SUCCESS ); /* This line won't be reached, but it keeps the compiler happy. */ return( Pt_CONTINUE ); }
http://www.qnx.com/developers/docs/qnx_4.25_docs/photon114/prog_guide/nonphab.html
crawl-003
refinedweb
1,942
52.09
SYNOPSIS #include <time.h> int nanosleep(const struct timespec *req, struct timespec *rem); feature test macro requirements for glibc (see feature_test_macros(7)):. non-blocked signal that was delivered to the thread.. lematic abso- lute time value. POSIX.1 specifies that nanosleep() should measure time against the CLOCK_REALTIME clock. However, Linux measures the time using the CLOCK_MONOTONIC clock. This probably does not matter, since the POSIX.1 specification for clock_settime() says that discontinuous changes in CLOCK_REALTIME should not affect nanosleep(): Setting the value of the CLOCK_REALTIME clock via clock_set- time(). SEE ALSO clock_nanosleep(2), sched_setscheduler(2), sleep(3), timer_create(2), usleep(3), time(7) COLOPHON This page is part of release 3.23 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://www.linux-directory.com/man2/nanosleep.shtml
crawl-003
refinedweb
132
60.61
auto Denotative, locally stateful programming DSL & platform See all snapshots auto appears in auto-0.4.3.1@sha256:329f9e7a34357953da943b881f64cc6dd1c9b7fd09a14637a3581bfc3f0d71f7,4960 Module documentation for 0.4.3.1 Auto $ cabal install auto Check it out! -- Let's implement consecutive -- proc syntax; see tutorial -- the output of this all is the value of the response id -< response What is it? Auto is a Haskell DSL and platform providing an API with declarative, compositional, denotative semantics for discrete-step, locally stateful, interactive programs, games, and automations, with implicitly derived serialization. It is suited for any domain where your program’s input or output is a stream of values, input events, or output views. At the high-level, it allows you to describe your interactive program or simulation as a value stream transformer, by composition and transformation of other stream transformers. So, things like: - Chat bots - Turn-based games - GUIs - Numerical simulations - Process controllers - Text-based interfaces - (Value) stream transformers, filters, mergers, processors It’s been called “FRP for discrete time contexts”. Intrigued? Excited? Start at the tutorial! It’s a part of this package directory and also on github at the above link. The current development documentation server is found at. From there, you can check out my All About Auto series on my blog, where I break sample projects and show to approach projects in real life. You can also find examples and demonstrations in the auto-examples repo on github. Buzzwords explained! other;”. Support The official support and discussion channel is #haskell-auto on freenode. You can also usually find me (the maintainer and developer) as jle` on #haskell-game or #haskell. There’s also a gitter channel if IRC is not your cup of tea.. You can “fake” it by faking continuous time with discrete sampling…but FRP is a much, much more powerful and safe. In other words, Auto handles “value streams”, while pipes/conduit handle “effect streams” Relation to FRP Auto borrows a lot of concepts from Functional Reactive Programming — especially arrowized, locally stateful libraries like netwire. At best, Auto can be said to bring a lot of API ideas and borrows certain aspects of the semantic model of FRP and incorporates them as a part of a broader semantic model more suitable for discrete-time discrete-stel contexts. But,. That is, you can “fake” it, but you then lose almost all of the benefits of FRP in the first place. A chatbot import qualified Data.Map as M import Data.Map (Map) import Control.Auto import Prelude hiding ((.), id) -- Let's build a big chat bot by combining small chat bots. -- A "ChatBot" is going to be an `Auto` taking in a stream of tuples of -- incoming nick, message, and timestamps; -- proc syntax; see tutorial --. In principle very little of your program should be over IOas a monad…but sometimes, it becomes quite convenient for abstraction purposes. Handling IO errors in a robust way isn’t quite my strong point, and so while almost all auto idioms avoid IOand runtime, for some applications it might be unavoidable. auto is not and will never be about streaming IO effects…but knowing what parts of IO fit into the semantic model of value stream transformers would yield a lot of insight. Also, most of the Auto“runners” (the functions that translate an Autointo IOthat executes it) might be able to benefit from a more rigorous look too. Tests; tests aren’t really done yet, sorry! Working on those :).
https://www.stackage.org/lts-13.11/package/auto-0.4.3.1
CC-MAIN-2021-31
refinedweb
580
54.22
When my app starts, I need to populate my Vuex store from my backend serve with some configuration data. What is the “best practice” for doing this? I will be calling a Vuex action to get the data from the server. Should I do it in a boot file located in the boot folder? In the store/index.js file? Use a life cycle hook(created) in the App.vue file? Some other recommend method? Thanks. - metalsadman last edited by I went with adding a boot file. I also had to make changes to the Vuex store directory to make the store available to the boot file. I made changes to the vuex index.js file located in the store folder. src\store\index.js import Vue from "vue"; import Vuex from "vuex"; import devices from "./devices"; import channels from "./channels"; import settings from "./settings"; import recordings from "./recordings"; import video from "./video"; import guide from "./guide" import schedule from "./schedule" Vue.use(Vuex); /* * If not building with SSR mode, you can * directly export the Store instantiation */ let store = null //added export default function ({ store/*store, ssrContext */ }) { //modified const Store = new Vuex.Store({ modules: { devices, channels, settings, recordings, video, guide, schedule }, // enable strict mode (adds overhead!) // for dev mode only strict: process.env.DEV }); store = Store // added return Store; } Then in the boot directory I added a file called init.js. src\boot\init.js // import something here // "async" is optional; export default async ({ app, router, Vue, store }) => { console.info('boot: init entered', store) await store.dispatch('settings/getNPVRConfig') console.info('boot: init exited') } @metalsadman @rhscjohn i have seen this solution before. but I don’t understand why the default export in store index.js would not work in boot and .js files ( because vuex exports a function instead of a variable?). Could you explain? why is this necessary: let store = null //added ... store = Store // added for example this works in my boot file( vuex-router-sync setup): import { sync } from 'vuex-router-sync' export default async ({ app, router, store }) => { const unsync = sync(store, router) // done. Returns an unsync callback fn } without the extra code in store/index.js: - metalsadman last edited by metalsadman @dobbel yes because it’s a function, in the boot is different, the store instance is passed as a parameter it’s the same store instance in your src/store/index.js, you’ll get more context if you check .quasar/client-entry.jsfile (if I’m not wrong), to see how those are initialized, you’ll also see there why $router instance is accessible in your stores via this.$router (if you are using functioninstead of arrows). I suggest you check that folder out in your project.
https://forum.quasar-framework.org/topic/6605/where-to-initialize-vuex-store-at-app-start-up
CC-MAIN-2022-05
refinedweb
452
68.77
Lab Assignment (in C): SPI Flash Interface The objective is to learn how to create a thread-safe driver for Synchronous Serial Port and to communicate with an external SPI Flash device. This lab will utilize: - SPI(SSP) driver - Code interface for the SPI flash - Basic knowledge of data structures - Mutex strategy to access the SPI flash safely across multiple tasks (or threads) - Logic Analyzer capture Part 0: SPI Driver) Implement ssp2.h and ssp2 status register } Code Block 1. ssp2.h and ssp2.c Part 1: SPI Flash Interface Get the code below to work and validate that you are able to read SPI flash memory's manufacture id and compare with the SPI flash datasheet to ensure that this is correct. #include "FreeRTOS.h" #include "task.h" #include "ssp2; } // TODO: Read Adesto flash datasheet to read its 'STATUS' register uint8_t adesto_read_status(void) { } void spi_task(void *p) {(); } Code Block 2. SPI flash interface test.h" void spi_id_verification_task(void *p) { while (1) { const adesto_flash_id_s id = ssp2__adesto_read_signature(); // When we read a manufacturer ID we do not expect, we will kill this task if (id.manufacturer_id != 0x1F) {()function such that two tasks will not be able to run this function at the same time. - If implemented correctly, you will not see the error printf Requirements What to turn in - Include all the code you developed in this lab - Turn in the screenshots of terminal output. - Include Manufacturer ID - Include bit-by-bit print-out of the Adesto STATUS register - Revision #12 Created 1 month ago by Preet Kang Updated 1 month ago by Preet Kang
http://books.socialledge.com/books/embedded-drivers-real-time-operating-systems/page/lab-assignment-%28in-c%29-spi-flash-interface/export/html
CC-MAIN-2019-47
refinedweb
263
59.03
readblock() Read blocks of data from a file Synopsis: #include <unistd.h> int readblock( int fd, size_t blksize, unsigned block, int numblks, void *buff ); Since: BlackBerry 10.0.0 Arguments: - fd - The file descriptor for the file you want to read from. - blksize - The number of bytes in each block of data. - block - The block number from which to start reading. - numblks - The number of blocks to read. - buff - A pointer to a buffer where the function can store the data that it reads. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The readblock() function reads numblks blocks of data from the file associated with the open file descriptor fd, into the buffer pointed to by buff, starting at block number block (blocks are numbered starting at 0). The blksize argument specifies the size of a block, in bytes. This function is() function's limit of INT_MAX bytes at a time.) If numblks is zero, readblock() returns zero and has no other results. On successful completion, readblock() returns the number of blocks actually read and placed in the buffer. This number is never greater than numblks. The value returned may be less than numblks if one of the following occurs: - The number of blocks left before the end-of-file is less than numblks. - The process requests more blocks than implementation limits allow to be read in a single atomic operation. - A read error occurred after reading at least one block. If a read error occurs on the first block, readblock() returns -1 and sets errno to EIO. Returns: The number of blocks actually read. If an error occurs, it returns -1, sets errno to indicate the error, and the contents of the buffer pointer to by buff are left unchanged. Errors: - EBADF - The fd argument isn't a valid file descriptor open for reading a block-oriented device. - EIO - A physical read error occurred on the first block. - EINVAL - The starting position is invalid (0 or negative) or beyond the end of the disk. Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/r/readblock.html
CC-MAIN-2019-35
refinedweb
370
66.44
cxmlcxml NOTE: the master branch of the source repo for this project did not compile. It also did not support xpath queries. This fork updates the code so that master compiles, augments the testing and adds xpath support. cxml aims to be the most advanced schema-aware streaming XML parser for JavaScript and TypeScript. It fully supports namespaces, derived types and substitution groups. It can handle pretty hairy schema such as GML, WFS and extensions to them defined by INSPIRE. Output is fully typed and structured according to the actual meaning of input data, as defined in the schema. IntroductionIntroduction For example this XML: medata can become this JSON (run npm test to see it happen): Note the following: "123"can be a string or a number depending on the context. - The nameattribute and ownerchild element are represented in the same way. - A dirhas a single owner but can contain many files, so fileis an array but owneris not. - Output data types are as simple as possible while correctly representing the input. See the example schema that makes it happen. Schemas for formats like GML and SVG are nastier, but you don't have to look at them to use them through cxml. Relevant schema files should be downloaded and compiled using cxsd before using them to parse documents. Check out the example schema converted to TypeScript. There's much more. What if we parse an empty dir: ;;;; Now we can print the result and try some magical features: result.then; Unseen in the JSON output, every object is an instance of a constructor for the appropriate XSD schema type. Its prototype also contains placeholders for valid children, which means you can refer to a.b.c.d._exists even if a.b doesn't exist. This saves irrelevant checks when only the existence of a deeply nested item is interesting. The magical _exists flag is true in the prototypes and false in the placeholder instances, so it consumes no memory per object. We can also process data as soon as the parser sees it in the incoming stream: parser.attach; The best part: your code is fully typed with comments pulled from the schema! See the screenshot at the top. Related projectsRelated projects - node-xml4js uses schema information to read XML into nicely structured objects. LicenseLicense
https://preview.npmjs.com/package/@wikipathways/cxml
CC-MAIN-2020-29
refinedweb
387
65.83
This blog entry will go through setting up a completely newly installed Ubuntu 14.04 server, and creating an example ASP.NET core web application in visual studio on windows, and deploying to the Linux server. Okay here goes something new for me... Blogging about software development. Microsoft has released ASP.NET Core RC2 a week ago, which is an open-source cross platform version of the c# web framework. And what's even cooler, is that there is an open source database connector for entity framework and postgresql! My setup is a macbook pro running two virtual machines. I run windows with visual studio in one, and ubuntu on the other one. Download and install Virtual Box: Download Ubuntu 14 Server 64bit: Install Ubuntu 14.04 using Virtual Box. Change network settings inside virtual box for ubuntu virtual machine use the 'Attached To' drop down to select the 'Bridged Adapter' option. This will allow us to easily get an ip address for our virtual machine and access it via ssh, ftp, and http. Once ubuntu is setup, we begin by installing ssh. Ssh will allow connecting to the ubuntu server via a more user friendly remote terminal. The following commands will install the ssh server, and show the IP address information. sudo apt-get update sudo apt-get install openssh-server ifconfig Take note of IP address, it will be needed. Minimize the ubuntu virtual machine, open terminal inside of mac, and login to virtual machine via ssh using the following command: ssh *ubuntu-setup-username*@*ubuntu-ipaddress* There will then be a prompt for the ubuntu setup username's password, enter it and login. Now to install postgresql9.5(the latest version as of this blog... skipping this step we would install 9.3) we need to add the repository location, get the cpg key and update our repository, and finally install postgresql 9.5, using the following commands: sudo sh -c 'echo "deb `lsb_release -cs`-pgdg main" >> /etc/apt/sources.list.d/pgdg.list' wget -q -O - | sudo apt-key add - sudo apt-get update sudo apt-get install postgresql postgresql-contrib Once this completes postgresql will be installed. Now we need a database user for our application to use to access the postgresql database. To create a new user, execute the following commands: sudo su postgres (become the 'postgres' user) psql (start the psql shell) Inside the psql shell postgresql statments can be executed. But for now, let's log out and create a user. \q (quit the psql shell) createuser --interactive This will create a prompt for a role (user) name and if they should be a super user. I always select 'y' for yes they should be a super user. Then a password will need to be created for the user. This is done by using the psql shell. Type the following commands: psql ALTER USER *username* WITH PASSWORD '*password*'; \q su *ubuntu-setup-user* (switch back to the ubuntu setup user) There are two configuration files we need to modify in order to open postgresql to outside connections. The first one can be opened and modifed using the following command: sudo nano /etc/postgresql/9.5/main/pg_hba.conf This file controls the ability to connect to the postgres server from various ip addresses. For our purposes, I just open the database to any ip address. This is again not something you would want in a real production server, this is just for getting started. We will add two lines to open to all ipv4 and ipv6 ip addresses. host all all 0.0.0.0/0 md5 host all all ::0/0 md5 Once that file is saved there is one more configuration file for enabling external connections. Type the following command to access it: sudo nano /etc/postgresql/9.5/main/postgresql.conf This file has a line: #localhost='localhost' this needs to be changed to: localhost = '*' Make sure to remove the comment mark '#' at the beginning of the line. (that darn commenting pound sign got me spinning my tires for atleast an hour). Now just restart the postgresql server to use the new configuration. Type the following command to do restart it: sudo service postgresql restart Now you can connect to the database from a remote host. Hurray! (You can test this with pg-admin on the windows development machine, which is a handly visual tool for windows to access the postgresql database. It's basically the equivalent of ms-sql server managment tools for postgresql). If we can connect using this application on the windows development machine, then we know visual studio along with entity framework will have connectivity. Download pgAdmin here: . Let's finish setting up ubuntu) To install and configure ftp we need to do a few steps. First we need to install the service vsftpd. Use the following command to do so: sudo apt-get install vsftpd Now we need to modify the configuration file sudo nano /etc/vsftpd.conf we must remove the '#' sign in the configuration file so we can upload the files. Uncomment the line: write_enable=YES Save the configuration, and restart the vsftpd server: sudo service vsftpd restart Now the ftp server is setup to allow files to be copied to the home directory of the ubuntu user. We need to install and configure nginx sudo apt-get install nginx sudo rm /etc/nginx/sites-enabled/default sudo nano /etc/nginx/sites-enabled/default type the following into empty nginx configuration file: server { listen 80; location / { proxy_pass; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection keep-alive; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } Save the configuration file, and then restart the nginx server: sudo service nginx restart Finally for setting up ubuntu we install dotnet core RC2 we need to execute the following commands: sudo sh -c 'echo "deb [arch=amd64] trusty main" > /etc/apt/sources.list.d/dotnetdev.list' sudo apt-key adv --keyserver apt-mo.trafficmanager.net --recv-keys 417A0893 sudo apt-get updatesudo apt-get install dotnet-dev-1.0.0-preview1-002702 Once the linux virtual machine is all setup, it's time to get the windows virtual machine's development environment setup. Once windows is installed, you'll need to install visual studio, and the web tools for RC2. Install Visual Studio 2015 Community (FREE!): Install Microsoft ASP.NET and Web Tools Preview 1 tooling for Microsoft .NET Core 1.0.0.0 RC2: For the next part of this entry I go over the steps inside of visual studio to setup a basic CRUD app. The source code that should result from following steps proceeding can be found at Open up a new project in visual studio name it 'unape', which stands for ubuntu, nginx, asp.net core, postgresql, entity framework. Select .NetCore -> ASP.NET Core Web Application Select the web application template, and leave the authentication method as Indvidual User Accounts At this point, the packages have to restore which will also add folders and stuff that aren't immediately available until all the packages have restored... so basically go check your email or get a cup of coffee cause this will take about 30-60 seconds... i'm guessing this is also dependent on your internet speed, so results may vary. The restoration process is indicated by an icon next to the references in the solution explorer. In order to connect entity framework to postgresql we use a package called npgsql. It's an open source project. Inside Visual Studio open up the Package manager console and run the following command:Install-Package Npgsql.EntityFrameworkCore.PostgreSQL -Pre This will cause visual studio to download and restore the references for npgsql for RC2, which again the progress of this downloading process will be indicated by the icon next to the references in the solution explorer. Change the default connection information inside the appsettings.json file. Change the line from: "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-unape-1a240cd2-788a-41a2-a6b9-ef2e02774e98;Trusted_Connection=True;MultipleActiveResultSets=true" to: "DefaultConnection": "User ID=*pgsql-user*;Password=*pgsql-user-pass*;Server=192.168.1.131;Port=5432;Database=unapeDB;" Use the name and password of the postgresql user we created previously. Now we will create a plain old object in the models folder. For this example purpose, this simple Item object will work: namespace unape.Models { public class Item { public int Id { get; set; } public string Name { get; set; } public float Price { get; set; } } } Inside the Data folder we will create a new database context. The only difference between the traditional method of EF code first in the Database context file is the addition of the additional constructor which takes in options and passes them down to the base constructor. Here is the way my file looked: using Microsoft.EntityFrameworkCore; using unape.Models; namespace unape.Data { public class unapeDbContext : DbContext { public unapeDbContext(DbContextOptions<unapeDbContext> options) : base(options) { } public DbSet<Item> Items { get; set; } } } Alright, now we must modify the configuration to use postgres instead of the default ms-sql. This is done inside the Status authentication database context to use the postgres database we have setup, we also need to add a line to this method to allow our unapeDbContext to be configured. That is done pretty intuitively like this: services.AddDbContext<unapeDbContext>(options => options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"))); Build the solution to make sure we don't have any typos or anything unexpected. Now let's create a migration for our unapeDbContext, and after we have created a migration, we will update the database with both the unapeDbContext as well as the ApplicationDbContext. Open Cmd.Exe on the windows machine, and navigate to the directory of the unape project's src folder. Then Type the following commands into the cmd.exe command prompt: dotnet ef migrations add firstMig -c unapeDbContext (this will create a folder named migrations inside the project along with two migration files) dotnet ef database update -c unapeDbContext (this will cause the migrations to be exectued on the postgres database, which will cause the database unapeDb to be created and have the Item table with the columns we gave to the Item object) dotnet ef database update -c ApplicationDbContext (this will cause the migrations which are for user name, password, and roles authentication to execute and corresponding tables to be created in the postgres database) Alrighty, at this point we should have the database ready to roll, now we just need to add the controller and views for the CRUD operations on the Item object. This can be done easily using scaffolding. Because we picked the individual account as our authentication the appropriate package has been added to allow us to do "right-click Add new controller" inside visual studio. So at this point it is the same scaffolding stuff as traditional entity framework. Right click inside of the controllers folder and select to add a new controller. Select MVC Controller with views using entity framework. Using the drop downs, or typing select the Model class: Item (unape.Models), and Data context class: unapeDbContext (unape.Data). Leave all the defaults selected, and the controller name should have auto populated with ItemsController. Click Add. This will generate 5 views and a controller with the corresponding action methods to access and populate those views. In order to make it easier to access the 'Items' screens, let's add a link to our Items index page inside the _Layout.cshtml file. Inside the navbar unordered list, add an additional list item: <li><a asp-Items</a></li> At this point, run the app inside of visual studio. The browser will open with our app, with the ability to navigate to the Items controller from the navbar link, and also create, view, update, and delete all the items. Everything should work just fine. At this point, we are ready to deploy our basic example app into Linux. To do this we will copy over our the folders that are created during the publish process. Stop the app running in visual studio. Right click the project name in the solution explorer, and select publish. Select the file system as the publish target, and give it some profile name. The default target location is inside the bin\release\publishoutput\ folder. this is fine.... click publish. Now we will ftp into our linux box via windows explorer, inside the windows explorer toolbar type in ftp://'ipaddress of server' for me that looks like: With another windows explorer folder navigate to the unape's project bin\release\publishoutput\ folder, and copy the contents to the ftp server with a drag and drop. Now once the files have copied over to the ubuntu server. We will hop back onto the terminal to navigate to the publish output folder that was copied over via ftp, and run the following command: dotnet unape.dll This will launch the app, and it will be listening on localhost:5000, we configured the nginx reverse proxy to take requests coming in from the outside on port 80 to be routed to localhost:5000, so now we can open up a web browser and type in the http://'ip-address of ubuntu server', Bam baby! We are now running the asp.net core with entity framework connected to postgresql database all on ubuntu linux! Great post! This is for a good information, It's very helpful for this blog. And great valu for these information.This is good work you and you are doing well. Dot Net Training in Chennai Wonderful bloggers like yourself who would positively reply encouraged me to be more open and engaging in commenting.So know it's helpful. Dot Net Training in Chennai
http://totaltechware.blogspot.com/2016/05/aspnet-core-rc2-with-entity-framework.html
CC-MAIN-2017-26
refinedweb
2,286
54.42