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
Hey I'm trying to teach myself java OO programming using BlueJ and some material from my university, so far it's gone smoothly but I've stumbled on a couple of questions I need help with. For question 12.1, I have a solution and it work but I'm not sure it's the most efficient or it does entireley what the question is asking as the 'while' condition doesn't seem to affect much going on. Can somebody check this for me?For question 12.1, I have a solution and it work but I'm not sure it's the most efficient or it does entireley what the question is asking as the 'while' condition doesn't seem to affect much going on. Can somebody check this for me? 12.1 a new project: Start a new project - call it looping. Add a new class to it - Loops. Start adding a single method to it - any sensible name. In this method, write a do-while loop which prints the numbers from 1 to 5. Then modify your code so that, instead of printing each value in turn, it prints the totals of the numbers from 1 up to that value. So it calculates: 1; 1+2; 1+2+3; 1+2+3+4; 1+2+3+4+5. This means that your solution needs a loop inside a loop. 12.2: project from qu 12.1, looping This question requires keyboard input so you need to make appropriate classes available. One way to do this is to include the InputReader class in your project whose complete code is provided below, though you could use the Scanner class directly, if you prefer. Whichever way you prefer, include code so your Loops class can use a Scanner object. import java.util.Scanner; /** * InputReader reads typed text input from the standard text terminal. * * @author Lisa Payne * @version Jan 2007 */ public class InputReader { private Scanner reader; /** * Create a new InputReader that reads text from the text terminal. */ public InputReader() { reader = new Scanner(System.in); } /** * Accesses a String typed in text terminal * * @returns String value input */ public String getString() { String input = reader.nextLine(); return input; } /** * Accesses a int typed on a single line in text terminal * * @returns int value input */ public int getInt() { int input = reader.nextInt(); reader.nextLine(); return input; } } Start a second method in your Loops class - any sensible name. In this method you need to write code similar to that in question 12.1 (indeed you may want to copy 'n paste that to give you a start). This method should total a series of positive integers which the user enters from the keyboard. The user will type in each value followed by an <Enter> keypress. After the last value the user will type a negative value: this is the terminal sentinel. (Of course this method requires only a single loop - not a loop inside a loop.) For 12.2 I have no idea how to incorporate what is being asked with a loop. Can somebody help?!
http://www.javaprogrammingforums.com/loops-control-statements/18502-help-summing-numbers-without-input.html
CC-MAIN-2014-10
refinedweb
509
73.37
NAME BUF_ISLOCKED - returns the state of the lock linked to the buffer SYNOPSIS #include <sys/param.h> #include <sys/systm.h> #include <sys/uio.h> #include <sys/bio.h> #include <sys/buf.h> int BUF_ISLOCKED(struct buf *bp); DESCRIPTION The BUF_ISLOCKED() function returns the status of the lock linked to the buffer in relation to curthread. It can return: LK_EXCLUSIVE An exclusive lock is held by curthread. LK_EXCLOTHER An exclusive lock is held by someone other than curthread LK_SHARED A shared lock is held. 0 The lock is not held by anyone. SEE ALSO lockstatus(9), buf(9), BUF_LOCK(9), BUF_UNLOCK(9), lockmgr(9) AUTHORS This manual page was written by Attilio Rao 〈attilio@FreeBSD.org〉.
http://manpages.ubuntu.com/manpages/lucid/man9/BUF_ISLOCKED.9freebsd.html
CC-MAIN-2015-18
refinedweb
116
69.99
Re: Migration to mod_perl 2.0: Problems with CGI.pm Expand Messages - Hi solved it by updating CGI from version 3.01 to version 3.10 (from cpan.org). Foo Ji-Haw schrieb: > What do you mean by manipulating the core perl modules? There was anYou're right - I didn't wanted to use 'use Apache::Response;' anymore. > earlier discussion on how to migrate from the Apache to Apache2 > namespace. Most of the work can be done in a simple search-and-replace > across all scripts/ libraries. You really don't want to continue using > 'use Apache::Response;' > But a simple search-and-replace didn't work for me, since there were calls like "Apache->request' which still caused trouble after the search-and-replace action ... Johannes Your message has been successfully submitted and would be delivered to recipients shortly.
https://groups.yahoo.com/neo/groups/modperl/conversations/topics/65378?o=1&d=-1
CC-MAIN-2015-48
refinedweb
140
68.77
On 2010/11/18 19:59:23, Neil Puttock wrote: Hi Valentin, Hi Carl, hi Neil, thank for stopping by! :-) Graham: that's the reason why I uploaded a new patch set, but it didn't succeed either. I'm having some kind of a WTF situation here. I'm afraid I share Carl's concerns here I think he's right too. I wanted to take this as a chance to "correct" the way grace-functions are defined now, which I don't really like (having to define startGrace and stopGrace as empty expressions? really?). And I was confident that this could be handled with a straightforward convert-ly rule. However, you're both right in pointing out that it might be an unnecessary risk. though to my mind the most pressing issue is how the slash is rendered. I don't think it's enough to simply use a stencil override, since it makes it too difficult for users to tweak the appearance. Hence the "workaround" part that I did mention in my description. I did see it as a temporary hack, or more appropriately, a proof-of-concept, until we could have a genuinely proper solution (see below). I think rendering the slash with support for tweaking its appearance in a consistent manner demands an implementation as a separate grob. Unfortunately, this is precisely where I'm out of my league. My secret hope was that something like the harp-pedal thing would happen, i.e. my initial "naive" effort could entice proper programmers into implementing something nicer in the future :-) That being said, I'd be happy to play ball and give this a go: if you were to implement such a grob (I'm guessing something like BeamedMultiAcciaccaturaInitialStemSlash, only shorter ;-), where would you start? Would it require a glyph, like what we're doing with non-beamed acciaccaturas, or would a simple line be enough? And how would you compute the angle of the slash? (Besides, I'm concerned with the overhead/bloat/namespace pollution/etc. Would this grob really need to be added to the Stem_engraver by default? It would be used quite rarely, I think.) Bonus question: if we were to have an AcciaccaturaSlash grob, then would we still need the current implementation for slashed single notes (e.g. combining a slash glyph with the flag glyph, etc.)? Or could we use the same grob in both cases for visual consistency? ... Duh. I thought I was out of my league before, but it's even worse now :( Cheers, Valentin.
http://lists.gnu.org/archive/html/lilypond-devel/2010-11/msg00426.html
CC-MAIN-2014-49
refinedweb
426
71.65
If youʼve heard good things about Puppet but donʼt know where to start, this is the best place tobegin. To help with this, we provide a free virtual machine with Puppet already installed. Experimentfearlessly! While it downloads, move on to the first chapter of Learning Puppet. If you have problems withgetting the VM running, see “VM Tips” below. The Learning Puppet VM is available in VMWare .vmx format and the cross-platform OVF format,and has been tested with VMWare Fusion and VirtualBox. Login Info The VM is configured to write its current IP address to the login screen about ten seconds after it boots. If you prefer to use SSH, wait for the IP address to print and ssh to root@<ip address>. To view the Puppet Enterprise web console, navigate to https://(your VMʼs IP address) in your web browser. Log in as puppet@example.com, with the password learningpuppet. Note: If you want to create new user accounts in the console, the confirmation emails will contain incorrect links. You can work around this by copy-pasting the links into a web browser and fixing the hostname before hitting enter, or you can make sure the console is available at a reliable hostname and follow the instructions for changing the authentication hostname. To begin with, you wonʼt need separate agent and master VMs; this VM can act in both roles. Whenyou reach the agent/master exercises, weʼll walk through duplicating the system into a new agentnode. Contents Part one: Serverless Puppet Resources and the RAL — Learn about the fundamental building blocks of system configuration. config files as flexible as your Puppet manifests. Parameterized Classes (Modules, Part Two) — Learn how to pass parameters to classes and make your modules more adaptable. Defined Types — Model repeatable chunks of configuration by grouping basic resources into super-resources.f file included with your download; alternately, you can drag the OVF file and drop it onto VirtualBoxʼs main window. If you find the system hanging during boot at a “registered protocol family 2” message, you may need to go to the VMʼs “System” settings and check the “Enable IO APIC” option. (Many users are able to leave the IO APIC option disabled; we do not currently know what causes this problem.) The VM should work without modification on 4.x versions of VirtualBox. However, on 3.x versions, it may fail to import, with an error like “Failed to import appliance. Error reading ʻfilename.ovfʼ: unknown resource type 1 in hardware item, line 95.” If you see this error, you can either upgrade your copy of VirtualBox, or work around it by editing the .ovf file and recalculating the sha1 hash, as described here. Thanks to Mattias for this workaround. Parallels Desktop 7 on OS X can import the VMX version of this VM, but it requires extra configuration before it can run: If you attempt to start the VM without changing the location of the disk, it will probably kernel panic. If you are using a VMware virtualization product, you can leave the VMʼs networking in its default NAT mode. This will let it contact your host computer, any other VMs being run in NAT mode, the local network, and the outside internet; the only restriction is that computers outside your host computer canʼt initiate connections with it. If you eventually need other computers to be able to contact your VM, you can change its networking mode to Bridged. WITH VIRTUALBOX VirtualBoxʼs NAT mode is severely limited, and will not work with the later agent/master lessons. You should change the VMʼs network mode to Bridged Adapter before starting the VM for the first time. See here for more information about VirtualBoxʼs networking modes, and see here for more about VirtualBoxʼs DHCP server. BeginLog into the Learning Puppet VM as root, and run the following command: service { 'NetworkManager': ensure => 'stopped', enable => 'false', } service { 'acpid': ensure => 'running', enable => 'true', } service { 'anacron': ensure => 'stopped', enable => 'true', } service { 'apmd': ensure => 'running', enable => 'true', } ... ... (etc.) puppet: Most of Puppetʼs functionality comes from a single puppet command, which has many subcommands. resource: The resource subcommand can inspect and modify resources interactively. service: The first argument to the puppet resource command must be a resource type, which youʼll learn more about below. A full list of types can be found at the Puppet type reference. Taken together, this command inspected every service on the system, whether running or stopped. ResourcesImagine a systemʼs configuration as a collection of many independent atomic units; call them“resources.” These pieces vary in size, complexity, and lifespan. Any of the following (and more) can be modeledas a single resource: A user account A specific file A directory of files A software package A running service A scheduled cron job An invocation of a shell command, when certain conditions are met The implementation might differ — for example, youʼd need a different command to start or stop aservice on Windows than you would on Linux, and even across Linux distributions thereʼs somevariety. But conceptually, youʼre still starting or stopping a service, regardless of what you type intothe console. AbstractionIf you think about resources in this way, there are two notable insights you can derive:Learning Puppet • Learning Puppet — Resources and the RAL 7/76 Similar resources can be grouped into types. Services will tend to look like services, and users will tend to look like users. The description of a resource type can be separated from its implementation. You can talk about whether a service is started without needing to know how to start it. With a good enough description of a resource type, itʼs possible to declare a desired state for a resource — instead of saying “run this command that starts a service,” say “ensure this service is running.” These three insights form Puppetʼs resource abstraction layer (RAL). The RAL consists of types(high-level models) and providers (platform-specific implementations) — by splitting the two, it letsyou describe desired resource states in a way that isnʼt tied to a specific OS. Anatomy of a ResourceIn Puppet, every resource is an instance of a resource type and is identified by a title; it has anumber of attributes (which are defined by the type), and each attribute has a value. user { 'dave': ensure => present, uid => '507', gid => 'admin', shell => '/bin/zsh', home => '/home/dave', managehome => true, } This syntax is called a resource declaration. You saw it earlier when you ran puppet resourceservice, and itʼs the heart of the Puppet language. It describes a desired state for a resource,without mentioning any steps that must be taken to reach that state. Try and identify all four parts of the resource declaration above: Type Title Attributes Values Resource TypesLearning Puppet • Learning Puppet — Resources and the RAL 8/76As mentioned above, every resource has a type. Puppet has many built-in resource types, and you can install even more as plugins. Each type canbehave a bit differently, and has a different set of attributes available. Not all resource types are equally common or useful, so weʼve made a printable cheat sheet thatexplains the eight most useful types. Download the core types cheat sheet here. Experienced Puppet users spend most of their time in the type reference. This page list all of Puppetʼs built-in resource types, in extreme detail. It can be a bit overwhelmingfor a new user, but it has most of the info youʼll need in a normal day of writing Puppet code. We generate a new type reference for every new version of Puppet, to help ensure that thedescriptions stay accurate. Puppet Describe The puppet describe subcommand can list info about the currently installed resource types on agiven machine. This is different from the type reference because it also catches plugins installed bya user, in addition to the built-in types. puppet describe -l — List all of the resource types available on the system. puppet describe -s <TYPE> — Print short information about a type, without describing every attribute puppet describe <TYPE> — Print long information, similar to what appears in the type reference. Puppet Enterprise includes a web console for controlling many of its features. One of the things itcan do is browse and inspect resources on any PE systems the console can reach. This supports alimited number of resource types, but has some useful comparison features for correlating dataacross a large number of nodes. LOGGING IN Once logged in, navigate to “Live Management” in the top menu bar, then click the “ManageResources” tab. You can then follow these instructions to find and inspect resources. Since youʼre only using a single node, you wonʼt see much in the way of comparisons, but you cansee the current states of packages, user accounts, etc. Puppet includes a command called puppet resource, which can interactively inspect and modifyresources on a single system. The first argument must be a resource type. If no other arguments are given, it will inspect every resource of that type it can find. The second argument (optional) is the name of a resource. If no other arguments are given, it will inspect that resource. After the name, you can optionally specify any number of attributes and values. This will sync those attributes to the desired state, then inspect the final state of the resource. Alternately, if you specify a resource name and use the --edit flag, you can change that resource in your text editor; after the buffer is saved and closed, Puppet will modify the resource to match your changes. EXERCISES user { 'root': ensure => 'present', comment => 'root', gid => '0', groups => ['root', 'bin', 'daemon', 'sys', 'adm', 'disk', 'wheel'], home => '/root', password => '$1$jrm5tnjw$h8JJ9mCZLmJvIxvDLjw1M/', password_max_age => '99999', password_min_age => '0', user { 'katie': ensure => 'present', home => '/home/katie', shell => '/bin/zsh' } NextNext Lesson: The puppet resource command can be useful for one-off jobs, but Puppet was born for greaterthings. Time to write some manifests. Off-Road: The LP VM is a tiny sandbox system, and it doesnʼt have much going on. If you have some devmachines that look more like your actual servers, why not download Puppet Enterprise for free andinspect them? Follow the quick start guide to get a small environment installed, then try using theconsole to inspect resources for many systems at once. In a text editor — vim, emacs, or nano — create a file with the following contents and filename: # /root/examples/user-absent.pp user {'katie': ensure => absent, } Cool: Youʼve just written and applied your first Puppet manifest. ManifestsPuppet programs are called “manifests,” and they use the .pp file extension. The core of the Puppet language is the resource declaration. A resource declaration describes adesired state for one resource. (Manifests can also use various kinds of logic: conditional statements, collections of resources,functions to generate text, etc. Weʼll get to these later.) Puppet ApplyLike resource in the last chapter, apply is a Puppet subcommand. It takes the name of a manifestfile as its argument, and enforces the desired state described in the manifest. Weʼll use it below to test small manifests, but it can be used for larger jobs too. In fact, it can donearly everything an agent/master Puppet environment can do. Resource DeclarationsLetʼs start by looking at a single resource: # /root/examples/file-1.pp file {'testfile': path => '/tmp/testfile', ensure => present, mode => 0640, content => "I'm a test file.", } The complete syntax and behavior of resource declarations are documented in the Puppet A colon ( :) A set of attribute => value pairs, with a comma after each pair ( path => '/tmp/testfile', etc.) This is just the reverse of what we saw above when we removed the user account: Puppet noticedthat the file didnʼt exist, and created it. It set the desired content and mode at the same time. # cat /tmp/testfile I'm a test file. # ls -lah /tmp/testfile -rw-r----- 1 root root 16 Feb 23 13:15 /tmp/testfile If we try changing the mode and applying the manifest again, Puppet will fix it: And if you run the manifest again, youʼll see that Puppet doesnʼt do anything — if a resource is inthe desired state already, Puppet will leave it alone. Exercise: Declare another file resource in a manifest and apply it. Try setting a new desired state for an existing file — for example, changing the login message by setting the content of /etc/motd. You can see the attributes available for the file type here. Syntax Hints Capitalization matters! The resource type and the attribute names should always be lowercase. The values used for titles and attribute values will usually be strings, which you should usually quote. Read more about Puppetʼs data types here. There are two kinds of quotes in Puppet: single ( ') and double ( "). The main difference is that double quotes let you interpolate $variables, which we cover in another lesson. Attribute names (like path, ensure, etc.) are special keywords, not strings. They shouldnʼt be quoted. Also, note that Puppet lets you use whatever whitespace makes your manifests more readable. Wesuggest visually lining up the => arrows, because it makes it easier to understand a manifest at aglance. (The Vim plugins on the Learning Puppet VM will do this automatically as you type.) # /root/examples/file-2.pp file {'/tmp/test1': ensure => file, content => "Hi.", } file {'/tmp/test2': ensure => directory, mode => 0644, } file {'/tmp/test3': ensure => link, target => '/tmp/test1', } user {'katie': ensure => absent, } Apply: The ensure attribute is somewhat special. Itʼs available on most (but not all) resource types, and itcontrols whether the resource exists, with the definition of “exists” being somewhat local. # ls -lah /tmp/test* -rw-r--r-- 1 root root 3 Feb 23 15:54 test1 lrwxrwxrwx 1 root root 10 Feb 23 15:54 test3 -> /tmp/test1 /tmp/test2: total 16K drwxr-xr-x 2 root root 4.0K Feb 23 16:02 . drwxrwxrwt 5 root root 4.0K Feb 23 16:02 .. # cat /tmp/test3 Hi. Notice how our original file resource had a path attribute, but our next three left it out? These attributes are called “namevars.” They are generally the attribute that corresponds to theresourceʼs identity, the one thing that should always be unique. If you leave out the namevar for a resource, Puppet will re-use the title as its value. If you do specifya value for the namevar, the title of the resource can be anything. So why even have a namevar, if Puppet can just re-use the title? Most of the time these are the same, but sometimes they arenʼt. For example, the NTP service has a different name on different platforms: on Red Hat-like systems, itʼs called ntpd, and on Debian-like systems, itʼs ntp. These are logically the same resource, but their identity on the target system isnʼt the same. Also, there are cases (usually exec resources) where the system identity has no particular meaning, and putting a more descriptive identity in the title can help tell your colleagues (or yourself in two months) what a resource is supposed to be doing. By allowing you to split the title and namevar, Puppet makes it easy to handle these cases. Weʼll cover this later when we get to conditional statements. UNIQUENESS Note that you canʼt declare the same resource twice: Puppet always disallows duplicate titles within a given type, and usually disallows duplicate namevar values within a type. This is because resource declarations represent desired final states, and itʼs not at all clear what should happen if you declare two conflicting states. So Puppet will fail with an error instead of accidentally doing something wrong to the system. On the /tmp/test1 file, we left off the mode and owner attributes, among others. When we omitattributes, Puppet doesnʼt manage them, and any value is assumed to be the desired state. If a file doesnʼt exist, Puppet will default to creating it with permissions mode 0644, but if youchange that mode, Puppet wonʼt change it back. We said /tmp/test2/ should have permissions mode 0644, but our ls -lah showed mode 0755.Thatʼs because Puppet groups the read bit and the traverse bit for directories. This helps with recursively managing directories (with recurse => true), so you can allow traversalwithout making all of the contents of the directory executable. If you were writing an explanation to another human of how to put a system into a desired state,using the OSʼs default tools, it would read something like “Check whether the mode of the sudoersfile is 0440, using ls -l. If itʼs already fine, move on to the next step; otherwise, run chmod 0440/etc/sudoers.” Under the hood, Puppet is actually doing the same thing, with some of the same OS tools. But itwraps the “check” step together with the “and fix if needed” step, and presents them as a singleinterface. The effect is that, instead of writing a bash script that looks like a step-by-step for a beginninguser, you can write Puppet manifests that look like shorthand notes for an expert user. Aside: Compilation Manifests donʼt get used directly when Puppet syncs resources. Instead, the flow of a Puppet run goes a little like this: With puppet apply, the distinction doesnʼt mean much. In a master/agent Puppet environment, though, it matters more, because agents only see the catalog: By using logic, manifests can be flexible and describe many systems at once. A catalog describes desired states for one system. By default, agent nodes can only retrieve their own catalog; they canʼt see information meant for any other node. This separation improves security. Since catalogs are so unambiguous, itʼs possible to simulate a catalog run without making any changes to the system. (This is usually done by running puppet agent --test -- noop.) You can even use special diff tools to compare two catalogs and see the differences. Puppet apply: Puppet agent/master: Puppet agent runs as a service, and triggers a Puppet run about every half hour (configurable). On your VM, which runs Puppet Enterprise, the agent service is named pe-puppet. (Puppet agent can also be configured to run from cron, instead of as a service.) Puppet agent does not have access to any manifests; instead, it requests a pre-compiled catalog The puppet master always reads one special manifest, called the “site manifest” or site.pp. It uses this to compile a catalog, which it sends back to the agent. On your VM, the site manifest is at /etc/puppetlabs/puppet/manifests/site.pp. This way, you can have many machines being configured by Puppet, while only maintaining yourmanifests on one (or a few) servers. This also gives some extra security, as described above under“Compilation.” Run puppet agent --test, which will trigger a single puppet agent run in the foreground so you can see what itʼs doing in real time. Check /tmp, and notice that the files are back to their desired state. Write and apply a manifest that uses the ssh_authorized_key type to let you log into the learning VM as root without a password. Bonus work: Try putting it directly into the site manifest, instead of using puppet apply. Use the console to trigger a puppet agent run, and check the reports in the console to see whether the manifest worked. Youʼll need to have an SSH key pair, a terminal application on your host system, and some basic understanding of how SSH works. You can get all of these with a little outside research. You know how to use the fundamental building blocks of Puppet code, so now itʼs time to learnhow those blocks fit together. You already know how to do a bit with Puppet, and managing file ownership and permissions isimportant. Are there any files on your systems that youʼve had a hard time keeping in sync? You already knowenough to lock them down. Download Puppet Enterprise for free, follow the quick start guide to geta small environment installed, then try putting some file resources at the bottom of the puppetmasterʼs site.pp file to manage those files on every machine. # /root/training-manifests/2.file.pp file {'/tmp/test1': ensure => present, content => "Hi.", } file {'/tmp/test2': ensure => directory, mode => 644, } Like we mentioned in the last chapter, Puppet combines “check the state” and “fix any problems”into a single declaration for each resource. Since each resource is represented by one atomicstatement, ordering within a file matters a lot less than it would for an equivalent script. Or rather, it matters less as long as the resources are independent and not related to each other.And most resources are! But some resources depend on other resources. Consider a service whichis installed by a package — itʼs impossible to get the service into its desired state if the package isnʼtinstalled yet. The service has a dependency on the package. So when dealing with related resources, Puppet has ways to express those relationships. You can embed relationship information in a resource with the before, require, notify, and subscribe metaparameters. You can also declare relationships outside a resource with the -> and ~> chaining arrows. Each resource type has its own set of attributes, but thereʼs another set of attributes, calledmetaparameters, which can be used on any resource. (Theyʼre “meta” because they donʼt describeany feature of the resource that you could observe on the system after Puppet finishes; they onlydescribe how Puppet should act.) before require notify subscribe All of them accept a resource reference (or an array of them) as their value. Resource referenceslook like this: Type['title'] The easy way to remember this is that you only use the lowercase type name when declaring a new resource. Any other situation will always call for a capitalized type name. before and require make simple dependency relationships, where one resource must be syncedbefore another. before is used in the earlier resource, and lists resources that depend on it;require is used in the later resource, and lists the resources that it depends on. These two metaparameters are just different ways of writing the same relationship — our exampleabove could just as easily be written like this: file {'/tmp/test1': ensure => present, content => "Hi.", before => Notify['/tmp/test1 has already been synced.'], } A few resource types ( service, exec, and mount) can be “refreshed” — that is, told to react tochanges in their environment. For a service, this usually means restarting when a config file hasbeen changed; for an exec resource, this could mean running its payload if any user accounts havebeen changed. (Note that refreshes are performed by Puppet, so they only occur during Puppetruns.) file { '/etc/ssh/sshd_config': ensure => file, mode => 600, source => 'puppet:///modules/ssh/sshd_config', } service { 'sshd': ensure => running, enable => true, subscribe => File['/etc/ssh/sshd_config'], } In this example, the sshd service will be restarted if Puppet has to edit its config file. Chaining ArrowsThereʼs one last way to declare relationships: chain resource references with the ordering ( ->) andnotification ( ~>; note the tilde) arrows. Think of them as representing the flow of time: the resourcebehind the arrow will be synced before the resource the arrow points at. This example causes the same dependency as the similar examples above: notify {'after': message => '/tmp/test1 has already been synced.', } Chaining arrows can take several things as their operands: this example uses resource references,but they can also take resource declarations and resource collectors. Since whitespace is freely adjustable in Puppet, and since chaining arrows can go between resourcedeclarations, itʼs easy to make a short run of resources be synced in the order theyʼre written — justput chaining arrows between them: file {'/tmp/test1': AutorequireSome of Puppetʼs resource types will notice when an instance is related to other resources, andtheyʼll set up automatic dependencies. The one youʼll use most often is between files and theirparent directories: if a given file and its parent directory are both being managed as resources,Puppet will make sure to sync the parent directory before the file. This never creates new resources;it only adds dependencies to resources that are already being managed. Donʼt sweat much about the details of autorequiring; itʼs fairly conservative and should generally dothe right thing without getting in your way. If you forget itʼs there and make explicit dependencies,your code will still work. Explicit dependencies will also override autorequires, if they conflict. Example: sshdHopefully thatʼs all pretty clear! But even if it is, itʼs rather abstract — making sure a notify fires aftera file is something of a “hello world” use case, and not very illustrative. Letʼs break something! Youʼve probably been using SSH and your favorite terminal app to interact with the Learning PuppetVM, so letʼs go straight for the most-annoying-case scenario: weʼll pretend someone accidentallygave the wrong person (i.e., us) sudo privileges, and they ruined rootʼs ability to SSH to this box. Prepare Letʼs get a copy of the current sshd config file; going forward, weʼll use our new copy as thecanonical source for that file. # cp /etc/ssh/sshd_config ~/examples/ # /root/examples/break_ssh.pp (incomplete) file { '/etc/ssh/sshd_config': ensure => file, mode => 600, source => '/root/examples/sshd_config', # And yes, that's the first time we've used the "source" attribute. It accepts This is only half of what we need, though. It will change the config file, but those changes will onlytake effect when the service restarts, which could be years from now. To make the service restart whenever we make changes to the config, we should tell Puppet tomanage the sshd service and have it subscribe to the config file: # /root/examples/break_ssh.pp file { '/etc/ssh/sshd_config': ensure => file, mode => 600, source => '/root/examples/sshd_config', } service { 'sshd': ensure => running, enable => true, subscribe => File['/etc/ssh/sshd_config'], } Manage Break Next, edit the original /etc/ssh/sshd_config file. Thereʼs a commented-out line in there that says#PermitRootLogin yes; find it, remove the comment, and change the yes to a no: PermitRootLogin no … and log out. You should no longer be able to log in as root over SSH; test it to make sure.(Although you can still log in via your virtualization softwareʼs console.) Fix Actually, now that youʼve added those resources to site.pp, Puppet will fix this automatically withinabout half an hour. But if youʼre impatient, you can log in to the Puppet Enterprise console, thentrigger a puppet agent run in the live management page. NO CHANGES? NO REFRESH Thereʼs an odd situation you can get into if you apply a manifest that makes config file changes before you finish writing it. Puppet only sends refresh events if it makes changes to the notifying resource in this run. So if you wrote a file resource with new desired content for a config file, applied the manifest, then edited the manifest again to create a refresh relationship with a service, the service would miss its refresh, since the file resource would already be in its desired state. This will generally only happen to you on the machines youʼre testing early versions of manifests on, rather than your production boxes. If it does bite you, you can restart the service manually with the “Advanced Tasks” section of the PE consoleʼs live management page — use the “restart” action in the “service tasks” section. Package/File/ServiceThe example we just saw was very close to a pattern youʼll see constantly in production Puppetcode, but it was missing a piece. Letʼs complete it: # /root/examples/break_ssh.pp package { 'openssh-server': ensure => present, before => File['/etc/ssh/sshd_config'], } file { '/etc/ssh/sshd_config': ensure => file, mode => 600, source => '/root/examples/sshd_config', } service { 'sshd': ensure => running, enable => true, subscribe => File['/etc/ssh/sshd_config'], } This is the package/file/service pattern, one of the most useful idioms in Puppet: the packageresource makes sure the software and its config file are installed, the config file depends on thepackage resource, and the service subscribes to changes in the config file. Itʼs hard to overstate the importance of this pattern! If you stopped here and only learned this, youcould still get a lot of work done. Write and apply a manifest that will install the Apache package, then make sure the Apache service is running. Prove that it worked by using a web browser on your host OS to view the Apache welcome page. Bonus work: Manage the httpd.conf file, and have it notify the service. Force Apache to be kept at a certain version (note that youʼll have to research the format of the version strings for your operating system, as well as which versions are available). Hints: On modern Red Hat-like (your VM) and Debian-like Linux systems, packages are installed from the operating systemʼs Apt or Yum repositories. Since the system tools know how to find and install a package (or even a specific version of a package), all Puppet needs to know is ensure => installed; it doesnʼt need to know where the package lives. The names of package and service resources depend on the OSʼs own naming conventions. This means you often need to do a bit of research before writing a manifest, to learn what the local name for, e.g., the Apache package and service are. On CentOS, which your VM runs, both the package and service are named httpd. Make sure youʼre using the right ensure values for each resource type; they arenʼt the same for package, file, and service. The core types cheat sheet and the type reference are your friends. Now that you can express dependencies between resources, itʼs time to make your manifests moreaware of the outside world with variables, facts, and conditionals. Now that you can manage a complete service from top to bottom, try managing an importantservice on your own test systems. Download Puppet Enterprise for free, follow the quick start guideto get a small environment installed, then try building a package/file/service pattern at the bottomof the puppet masterʼs /etc/puppetlabs/puppet/manifests/site.pp file. MySQL? Memcached?You decide. VariablesVariables! Youʼve almost definitely used variables before in some other programming or scriptinglanguage, so weʼll cover the basics very quickly. A more complete explanation of the syntax andbehavior of variables is available in the variables chapter of the Puppet reference manual. $variables always start with a dollar sign. You assign to variables with the = operator. Variables can hold strings, numbers, booleans, arrays, hashes, and the special undef value. See the data types chapter of the Puppet reference manual for more information. If youʼveʼt mandatory, but it is recommended. Fully qualified variables look like $scope::variable. Top scope variables are the same, but their scope is nameless. (For example: $::top_scope_variable.) If you reference a variable with its short name and it isnʼt present in the local scope, Puppet will also check the global top scope; this means you can almost always refer to global variables with just their short names. You can see more about this in the scope chapter of the Puppet reference manual: scope in Puppet Enterprise 2.x and Puppet 2.7, scope in Puppet 3 You can only assign the same variable once in a given scope. In this way, theyʼre more like constants from other programming languages. file {'authorized_keys': path => '/root/.ssh/authorized_keys', content => $longthing, } People who write manifests to share with the public often adopt the habit of always using the $::variable notation when referring to facts. As mentioned above, the double-colon prefix specifies that a given variable should be found at top scope. This isnʼt actually necessary, since variable lookup will always reach top scope anyway. (See the scope chapter of the Puppet reference manual.) However, explicitly asking for top scope helps work around two issues that can make public code behave unpredictably. One issue affects all versions of Puppet 2.x, and the other affected earlier versions of Puppet 2.7.x: In Puppet 2.x: if a user declares a class from a public module inside one of their own classes, and their personal class sets a variable whose name matches the name of a fact that the public class is trying to access, the public class will get the local variable instead of the fact. This will generally cause the public class to fail or do something really strange. In earlier versions of Puppet 2.7.x: the dynamic scope deprecation warnings would sometimes be improperly triggered when manifests accessed top scopes variables without the double-colon prefix. This was fixed in later versions, but was very annoying for a while. Neither of these issues are relevant as of Puppet 3, but not everyone is using Puppet 3 yet, and a Puppet 3-based version of Puppet Enterprise is still forthcoming later this year. Since a lot of people are still writing public code meant to be used with Puppet 2.7, you still see this idiom a lot. FactsPuppet flexible, with pretty much no real work on our part. Theyʼre “facts.” Puppet uses a tool called Facter, which discovers some system information,normalizes it into a set of variables, and passes them off to Puppet. Puppetʼs compiler then hasaccess to those facts when itʼs at the command line. You can also see all of the facts for any node in your Puppet Enterprise deployment by browsing to that nodeʼs page in the console and scrolling down to the inventory information. You can also add new custom facts to Puppet; see the custom facts guide for more information. In addition to the facts from Facter, Puppet has a few extra built-in variables. You can see a list ofthem in the variables chapter of the Puppet reference manual. Conditional StatementsPuppet has several kinds of conditional statements. You can see more complete info about them inthe conditional statements chapter of the Puppet reference manual.. By using facts as conditions, you can easily make Puppet do different things on different kinds of If if condition { block of code } elsif condition { block of code } else { block of code }'], } } The condition for an if statement has to resolve to a boolean true/false value. However, all facts are strings, and all non-empty strings — including the string "false" — are true. This means that facts that are “false” need to be transformed before Puppet will treat them as. The str2bool function fact has a value of true, and false otherwise. Case Another kind of conditional is the case statement. (Or switch, or whatever your language of choicecallsʼtresolve to a value; instead, it fails compilation immediately with an error message. CASE MATCHING Case matches can be simple strings (like above), regular expressions, or comma-separated lists ofeither. Hereʼs the example from above, rewritten to use comma-separated lists of strings: case $operatingsystem {Learning Puppet • Learning Puppet — Variables, Conditionals, and Facts 32/76 case $operatingsystem { centos, redhat: { $apache = "httpd" } debian, ubuntu: { $apache = "apache2" } default: { fail("Unrecognized operating system for webserver") } } case $ipaddress_eth0 { /^127[\d.]+$/: { notify {'misconfig': message => "Possible network misconfiguration: IP address of $0", } } } String matching is case-insensitive, like the == comparison operator. Regular expressions aredenoted with the slash-quoting used by Perl and Ruby; theyʼre case-sensitive by default, but youcan use the (?i) and (?-i) switches to turn case-insensitivity on and off inside the pattern. Regexmatches also assign captured subpatterns to $1, $2, etc. inside the associated code block, with $0containing the whole matching string. See the regular expressions section of the Puppet referencemanualʼs data types page for more details. Selectors Selectors might be less familiar; theyʼre kind of like the common ternary operator, and kind of likethe case statement. Instead of choosing between a set of code blocks, selectors choose between a group of possiblevalues. You canʼt use them on their own; instead, theyʼre usually used to assign a variable. $apache = $operatingsystem ? { centos => 'httpd', redhat => 'httpd', /(?i)(ubuntu|debian)/ => 'apache2', default => undef, } Careful of the syntax, there: it looks kind of like weʼre saying $apache = $operatingsystem, butweʼre not. The question mark flags $operatingsystem as the control variable of a selector, and theactual value that gets assigned is determined by which option $operatingsystem matches. Alsonote how the syntax differs from the case syntax: it uses hash rockets and line-end commasinstead of colons and blocks, and you canʼt use lists of values in a match. (If you want to matchagainst a list, you have to fake it with a regular expression.) It can look a little awkward, but there are plenty of situations where itʼs the most concise way to geta value sorted out; if youʼre ever not comfortable with it, you can just use a case statement to assign Selectors can also be used directly as values for a resource attribute, but try not to do that, becauseit gets ugly fast. Exercises Use the $operatingsystem fact to write a manifest that installs a C build environment on Debian-based (“debian,” “ubuntu”) and Enterprise Linux-based (“centos,” “redhat”) machines. (Both types of system require the gcc package, but Debian-type systems also require build-essential.) Write a manifest that installs and configures NTP for Debian-based and Enterprise Linux- based Linux systems. This will be a package/file/service pattern where both kinds of systems use the same package name ( ntp), but youʼll be shipping different config files (Debian version, Red Hat version – remember the file typeʼs “source” attribute) and using different service names ( ntp and ntpd, respectively). Now that your manifests can adapt to different kinds of systems, itʼs time to start groupingresources and conditionals into meaningful units. Onward to classes, defined resource types, andmodules! Since facts from every node show up in the console, Puppet Enterprise can be a powerful inventorytool. Download Puppet Enterprise for free, follow the quick start guide to get a small environmentinstalled, then try browsing the consoleʼs inventory for a central view of your operating systemversions, hardware profiles, and more. class my_class { notify {"This actually did something":} } include my_class Past a handful of resources, this gets unwieldy. You can probably already see the road to the threethousand line manifest of doom, and you donʼt want to go there. Itʼs much better to split chunks oflogically related code out into their own files, and then refer to those chunks by name when youneed them. Classes are Puppetʼs way of separating out chunks of code, and modules are Puppetʼs way oforganizing classes so that you can refer to them by name. ClassesClasses are named blocks of Puppet code, which can be created in one place and invokedelsewhere. Defining a class makes it available by name, but doesnʼt automatically evaluate the code inside it. Declaring a class evaluates the code in the class, and applies all of its resources. For the next five minutes, weʼll keep working in a single manifest file; either a one-off, or site.pp. Ina few short paragraphs, weʼll start separating code out into additional files. Defining a Class Before you can use a class, you must define it, which is done with the class keyword, a name, curlybraces, and a block of code: What goes in that block of code? How about your answer from last chapterʼs NTP exercise? It shouldlook a little like this: # /root/examples/modules1-ntp, enable => true, subscribe => File['ntp.conf'], } } Note: You can download some basic NTP config files here: Debian version, Red Hat version. Class names must start with a lowercase letter, and can contain lowercase letters, numbers, and underscores. Class names can also use a double colon ( ::) as a namespace separator. (This should look familiar.) Namespaces must map to module layout, which weʼll cover below. Any variables you assign inside the class wonʼt be accessible by their short names outside the class; to get at them from elsewhere, you would have to use the fully-qualified name (e.g. $ntp::service_name, from our example above). You can assign new, local values to variable names that were already used at top scope. For example, you could specify a new local value for $fqdn. Declaring Okay, remember how we said that defining makes a class available, and declaring evaluates it? Wecan see that in action by trying to apply our manifest above: To declare a class, use the include function with the classʼs name: # /root/examples/modules1-ntp, include ntp ModulesYou know how to define and declare classes, but weʼre still doing everything in a single manifest,where theyʼre not very useful. To help you split up your manifests into an easier to understand structure, Puppet uses modulesand the module autoloader. Modules are just directories with files, arranged in a specific, predictable structure. The manifest files within a module have to obey certain naming restrictions. Puppet looks for modules in a specific place (or list of places). This set of directories is known as the modulepath, which is a configurable setting. If a class is defined in a module, you can declare that class by name in any manifest. Puppet will automatically find and load the manifest that contains the class definition. This means you can have a pile of modules with sophisticated Puppet code, and your site.ppmanifest can look like this: # /etc/puppetlabs/puppet/manifests/site.pp include ntp include apache include mysql include mongodb include build_essential The Modulepath Before we make a module, we need to know where to put it. So weʼll find our modulepath, the set ofdirectories that Puppet searches for modules. The Puppet config file configuration guide, but in short, the [main] sectionhas settings that apply to everything (puppet master, puppet apply, puppet agent, etc.), and it setsthe value of modulepath to a colon-separated list of two directories: /etc/puppetlabs/puppet/modules /opt/puppet/share/puppet/modules The first, /etc/puppetlabs/puppet/modules, is the main module directory weʼll be using. (Theother one contains special modules that Puppet Enterprise uses to configure its own features; youcan look in these, but shouldnʼt change them or add to them.) ASIDE: CONFIGPRINT You can also get the value of the modulepath by running puppet master --configprint modulepath. The --configprint option lets you get the value of any Puppet setting; by using the master subcommand, weʼre making sure we get the value the puppet master will use. A module is a directory. The moduleʼs name must be the name of the directory. It contains a manifests directory, which can contain any number of .pp files. Thereʼs more to know, but this will get us started. Letʼs turn our NTP class into a real module: # cd /etc/puppetlabs/puppet/modules # mkdir -p ntp/manifests # touch ntp/manifests/init.pp Edit this init.pp file, and paste your ntp class definition into it. Be sure not to paste in the includestatement; itʼs not necessary here. # /etc/puppetlabs/puppet/modules/ntp/manifests/init.pp package { 'ntp': ensure => installed, } file { 'ntp.conf': path => '/etc/ntp.conf', ensure => file, require => Package['ntp'], source => "/root/examples/answers/${conf_file}" } service { 'ntp': name => $service_name, ensure => running, enable => true, subscribe => File['ntp.conf'], } } Now that we have a working module, you can edit your site.pp file: if there are any NTP-relatedresources left in it, be sure to delete them, then add one line: include ntp Turn off the NTP service, then do a foreground puppet agent run so you can see the action: It worked! Include We already saw this: you can declare classes by putting include ntp in your main manifest. The include function declares a class, if it hasnʼt already been declared somewhere else. If a classHAS already been declared, include will notice that and do nothing. This lets you safely declare a class in several places. If some class depends on something in anotherclass, it can declare that class without worrying whether itʼs also being declared in site.pp. These look like resource declarations, except with a resource type of “class:” class {'ntp':} These behave differently, acting more like resources than like the include function. Rememberweʼve seen that you canʼt declare the same resource more than once? The same holds true forresource-like class declarations. If Puppet tries to evaluate one and the class has already beendeclared, it will fail compilation with an error. However, unlike include, resource-like declarations let you specify class parameters. Weʼll coverthose in a later chapter, and go into more detail about why resource-like declarations are so strict.Learning Puppet • Learning Puppet — Modules and Classes 41/76The PE Console You can also assign classes to specific nodes using PEʼs web console. Youʼll have to add the class tothe console, then navigate to a nodeʼs page and assign the class to that node. Weʼll go into more detail later about working with multiple nodes. # mkdir /etc/puppetlabs/puppet/modules/ntp/files # mv /root/examples/answers/ntp.conf.* /etc/puppetlabs/puppet/modules/ntp/files/ Then, edit the init.pp manifest; weʼll use the special puppet:/// URL format to tell Puppet where thefiles are: # ... file { 'ntp.conf': path => '/etc/ntp.conf', ensure => file, require => Package['ntp'], source => "puppet:///modules/ntp/${conf_file}", } } Now, everything the module needs is in one place. Even better, a puppet master can actually servethose files to agent nodes over the network now — when we were using /root/examples/etc...paths, Puppet would only find the source files if they already existed on the target machine. Weʼve seen two of the subdirectories in a module, but there are several more available: templates/ — Contains templates, which can be referenced from the moduleʼs manifests. More on templates later. lib/ — Contains plugins, like custom facts and custom resource types. tests/ or examples/ — Contains example manifests showing how to declare the moduleʼs classes and defined types. Our printable Module Cheat Sheet shows how to lay out a module and explains how in- manifest names map to the underlying files; itʼs a good quick reference when youʼre getting started. The Puppet reference manual also has a page of info about module layout. This is a good time to explain more about how the manifests and files directories work: Each manifest in a module should contain exactly one class or defined type. (More on defined typeslater.) Each manifestʼs filename must map to the name of the class or defined type it contains. The init.ppfile, which we used above, is special — it always contains a class (or defined type) with the samename as the module. Every other file must contain a class (or defined type) named as follows: <MODULE NAME>::<FILENAME> You can see more detail about this mapping at the namespaces and autoloading page of thePuppet reference manual. Static files can be arranged in any directory structure inside the files/ directory. When referencing these files in Puppet manifests, as the source attributes of file resources, youshould use puppet:/// URLs. These have to be structured in a certain way: Note that the final segment of the URL starts inside the files/ directory of the module. If there areany extra subdirectories, they work like youʼd expect, so you could have something likepuppet:///modules/ntp/config_files/linux/ntp.conf.el. The Puppet Forge is a repository of free modules you can install and use. Most of these modulesare open source, and you can easily contribute updates and changes to improve or enhance thesemodules. You can also contribute your own modules. Puppet ships with a module subcommand for installing and managing modules from the PuppetForge. Detailed instructions for using it can be found in the Puppet reference manualʼs “installingmodules” page. Some quick examples: Modules from the Puppet Forge have a user name prefix in their names; this is done to avoid name clashes between, for example, all of the Apache modules out there. The puppet module subcommand handles these user name prefixes automatically — it preserves them as metadata, but installs the module under its common name. That is, your Puppet manifests would refer to a mysql module instead of the puppetlabs-mysql module. Building on your work from two chapters ago, create an Apache module and class, which ensures Apache is installed and running and manages its config file. Bonus work: Make Puppet manage the DocumentRoot folder, and put a custom 404 page and default index.html in place. You can also use conditional statements to set any files or package/service names that might vary per OS; if you donʼt want to research the names used by other OSes, you can just have the class fail if itʼs not used on CentOS. Whatʼs with that templates/ folder in the module structure? And can we do anything moreinteresting with config files than just replacing them with static content? Find out in the Templateschapter. Since you know how to install free modules from the Puppet Forge, and how to declare the classesinside those modules, search around and try to find some modules that might be useful in yourinfrastructure. Then download Puppet Enterprise for free, follow the quick start guide to get a smallenvironment installed, and try managing complex services on some of your test nodes. class ntp { #... #... #... file { 'ntp.conf': path => '/etc/ntp.conf', ensure => file, require => Package['ntp'], content => template("ntp/${conf_file}.erb"), } } # cd /etc/puppetlabs/puppet/modules/ntp # mkdir templates # cp files/ntp.conf.el templates/ntp.conf.el.erb # cp files/ntp.conf.debian templates/ntp.conf.debian.erb Right now, weʼre shipping around two different config files, which resemble the defaults for RedHat-like and Debian-like OSes. What if we wanted to make a few small and reasonable changes? Forexample: We could end up maintaining eight or more different config files! Letʼs not do that. Instead, we canmanage a bunch of small differences in one or two template files. Templates are documents that contain a mixture of static and dynamic content. By using a smallamount of conditional logic and variable interpolation, they let you maintain one source documentthat can be rendered into any number of final documents. For more details on the behavior of Puppet templates, see the guide for Using Puppet Templates;weʼll cover the basics right here. Template FilesTemplates are saved as files with the .erb extension, and should be stored in the templates/directory of any module. There can be any number of subdirectories inside templates/. Rendering TemplatesTo use a template, you have to render it to produce an output string. To do this, use Puppetʼs built-in template function. This function takes a path to one or more template files and returns anoutput string: file {'/etc/foo.conf': ensure => file, require => Package['foo'], content => template('foo/foo.conf.erb'), } Notice that weʼre using the output string as the value of the content attribute — it wouldnʼt workwith the source attribute, which expects a URL rather than the actual content for a file. Note that the path to the template doesnʼt use the same semantics as the path in a puppet:/// URL. Sorry about the inconsistency. Inline Templates Alternately, you can use the inline_template function, which takes a string containing a templateand returns an output string. This is less frequently useful, but if you have a very small template, you can sometimes embed it inthe manifest instead of making a whole new file for it. Weʼve seen several functions already, including include, template, fail, and str2bool, so this is as good a time as any to explain what they are. The template and str2bool functions both return values; you can use them anywhere that requires a value, as long as the return value is the right kind. The include and fail functions do something else, without returning a value — declare a class, and stop catalog compilation, respectively. All functions are run during catalog compilation. This means they run on the puppet master, and donʼt have access to any files or settings on the agent node. Functions can take any number of arguments, which are separated by commas and can be surrounded by optional parentheses: Complete documentation about functions are available at the functions page of the Puppet reference manual and the list of built-in functions. Facts, global variables, and local variables from the current scope are available to a template as Ruby instance variables — instead of Puppetʼs $ prefix, they have an @ prefix. (e.g. @fqdn, @memoryfree, @operatingsystem, etc.) Variables from other scopes can be accessed with the scope.lookupvar method, which takes a long variable name without the $ prefix. (For example, scope.lookupvar('apache::user').) ERB templates mostly look like normal configuration files, with the occasional <% tag containingRuby code %>. The ERB syntax is documented here, but since tags can contain any Ruby code, itʼspossible for templates to get pretty complicated. In general, we recommend keeping templates as simple as possible: weʼll show you how to printvariables, do conditional statements, and iterate over arrays, which should be enough for mosttasks. Non-Printing Tags ERB tags are delimited by angle brackets with percent signs just inside. (There isnʼt any HTML-likeconcept of opening or closing tags.) Tags contain one or more lines of Ruby code, which can set variables, munge data, implementcontrol flow, or… actually, pretty much anything, except for print text in the rendered output. Printing an Expression For that, you need to use a printing tag, which looks like a normal tag with an equals sign rightafter the opening delimiter: The value you print can be a simple variable, or it can be an arbitrarily complicated Ruby A tag with a hash mark right after the opening delimiter can hold comments, which arenʼtinterpreted as code and arenʼt displayed in the rendered output. Regular tags donʼt print anything, but if you keep each tag of logic on its own line, the line breaksyou use will show up as a swath of whitespace in the final file. Similarly, if youʼre indenting forreadability, the whitespace in the indent can mess up the format of the rendered output. Trim line breaks by putting a hyphen directly before the closing delimiter Trim leading space by putting a hyphen directly after the opening delimiter First, make sure you change the file resource to use a template, like we saw at the top of this page.You should also make sure youʼve copied the config files to the templates/ directory and giventhem the .erb extension. Next, weʼll move the default NTP servers out of the config file and into the manifest: class ntp { case $operatingsystem { centos, redhat: { $service_name = 'ntpd' $conf_file = 'ntp.conf.el' $default_servers = [ "0.centos.pool.ntp.org", "1.centos.pool.ntp.org", "2.centos.pool.ntp.org", ] } debian, ubuntu: { $service_name = 'ntp' $conf_file = 'ntp.conf.debian' $servers_real = $default_servers package { 'ntp': ensure => installed, } service { 'ntp': name => $service_name, ensure => running, enable => true, subscribe => File['ntp.conf'], } file { 'ntp.conf': path => '/etc/ntp.conf', ensure => file, require => Package['ntp'], content => template("ntp/${conf_file}.erb"), } } Weʼre storing the servers in an array, so we can show how to iterate within a template. Right now,weʼre not providing the ability to change the list of servers, but weʼre paving the way to do so in thenext chapter. First, make each template use the $servers_real variable to create the list of server statements: # Managed by Class['ntp'] <% @servers_real.each do |this_server| -%> server <%= this_server %> <% end -%> # ... Using a non-printing Ruby tag to start a loop. We reference the $servers_real Puppet variable by the name @servers_real, then call Rubyʼs each method on it. Everything between do |server| -%> and the <% end -%> tag will be repeated for each item in the $servers_real array, with the value of that array item being assigned to the temporary this_server variable. # Managed by Class['ntp'] server 0.centos.pool.ntp.org server 1.centos.pool.ntp.org server 2.centos.pool.ntp.org Next, letʼs use the $is_virtual fact to make NTP perform better if this is a virtual machine. At thetop of the file, add this: Then, below the loop we made for the server statements, add this (being sure to replace the similarsection of the Red Hat-like template): By using facts to conditionally switch parts of the config file on and off, we can easily react to thetype of machine weʼre managing. Weʼve already seen that classes should sometimes behave differently for different kinds of systems,and have used facts to make conditional changes to both manifests and templates. Sometimes, though, facts arenʼt enough — there are times when a human has to decide whatmakes a machine different, because that difference is a matter of policy. (For example, thedifference between a test server and a production server.) In these cases, we need to give ourselves a way to manually change the way a class works. We cando this by passing in data with class parameters. Are you managing any configuration on your real infrastructure yet? Youʼve learned a lot by now, sowhy not download Puppet Enterprise for free, follow the quick start guide to get a smallenvironment installed, and start automating? class {'echo_class': to_echo => 'Custom value', } But this isnʼt always the best way to do it, and it starts to break down once you need to switch amoduleʼs behavior on information that doesnʼt map cleanly to system facts. Is this a databaseserver? A local NTP server? A test node? A production node? These arenʼt necessarily facts; usually,theyʼre decisions made by a human. In these cases, itʼs often best to just configure the class, and tell it what it needs to know when youdeclare it. To enable this, classes need some way to ask for information from the outside world. Class ParametersWhen defining a class, you can give it a list of parameters. Parameters go in an optional set ofparentheses, between the name and the first curly brace. Each parameter is a variable name, andcan have an optional default value; each parameter is separated from the next with a comma. class {'mysql': user => mysqlserver, } If you declare the class with a resource-like class declaration, the parameters are available as resource attributes. Inside the definition of the class, they appear as local variables. Default Values When defining the class, you can give any parameter a default value. This makes it optional whenyou declare the class; if you donʼt specify a value, it will use the default. Parameters without defaultsbecome mandatory when declaring the class. In Puppet 2.7, which is used in the Puppet Enterprise 2.x series, you must use resource-like classdeclarations if you want to specify class parameters; you cannot specify parameters with include orin the PE console. If every parameter has a default and you donʼt need to override any of them, youcan declare the class with include; otherwise, you must use resource-like class declarations. Resource-like declarations donʼt play nicely with include, and if youʼre using them, you need toorganize your manifests so that they never attempt to declare a class more than once. This hastraditionally been a pain, but class parameters are still superior to older ways of configuringclasses, and the best practices developed over the course of the Puppet 2.7 series have made themmuch easier to deal with. The best way to deal with class parameters in the Puppet Enterprise 2.x series is to create “role” and“profile” modules that combine your functional classes into more complete node descriptions. Onceyou find yourself managing multiple nodes with Puppet, you should read Craig Dunnʼs “Roles andProfiles” essay, which matches the best practices used by Puppet Labsʼs services engineers. To make your roles and profiles more flexible and avoid repeating yourself, you can also install andconfigure Hiera on your puppet master and specify Hiera lookup functions as the values of classparameters. The problem is that classes are singletons, parameters configure the way they behave, and includecan declare the same class more than once. If you were to declare a class multiple times with different parameter values, which set of valuesshould win? The question didnʼt seem to have a good answer. The older method of using magic The solution Puppetʼs designers settled on was that parameter values either had to be explicit andunconflicting (the restrictions on resource-like class declarations), or had to come from somewhereoutside Puppet and be already resolved by the time Puppetʼs parsing begins (Puppet 3ʼs automaticparameter lookup). Class parameters were added to Puppet in version 2.6.0, to address a need for a standard andvisible way to configure clases. Prior to that, people generally configured classes by choosing an arbitrary and unique externalvariable name and having the class retrieve that variable with dynamically-scoped variable lookup: $some_variable include some_class # This class will reach outside its own scope, and hope # it finds a value for $some_variable. Every class was competing for variable names in an effectively global name space. If you accidentally chose a non-unique name for your magic variables, something bad would happen. When writing modules to share with the world, you had to be very careful to document all of your magic variables; there wasnʼt a standard place a user could look to see what data a class needed. This inspired many many people to try and make intricate data hierarchies with node inheritance, which rarely worked and had a tendency to fail dramatically and confusingly. Next, weʼll change how we set that $servers_real variable that the template uses: if $servers == undef { $servers_real = $default_servers } else { $servers_real = $servers And… thatʼs all it takes. If you declare the class with no attributes… …itʼll work the same way it used to. If you declare it with a servers attribute containing an array ofservers (with or without appended iburst and dynamic statements)… class {'ntp': servers => [ "ntp1.example.com dynamic", "ntp2.example.com dynamic", ], } Thereʼs a bit of trickery to notice: setting a variable or parameter to undef might seem odd, andweʼre only doing it because we want to be able to get the default servers without asking for them.(Remember, parameters canʼt be optional without an explicit default value.) Also, remember the business with the $servers_real variable? That was because the Puppetlanguage wonʼt let us re-assign the $servers variable within a given scope. If the default value wewanted was the same regardless of OS, we could just use it as the parameter default, but the extralogic to accomodate the per-OS defaults means we have to make a copy of the variable. While weʼre in the NTP module, what else could we make into a parameter? Well, letʼs say yousometimes wanted to prevent the NTP daemon from being used as a server by other nodes. Ormaybe you want to install and configure NTP, but not keep the daemon running. You could exposeall of these as extra class parameters, and make changes in the manifest or the templates to usethem. All of these changes are based on decisions from the free puppetlabs/ntp module. You can browsethe source of this module and see how these extra parameters play out in the manifest andtemplates. Module DocumentationYou have a fairly functional NTP module, at this point. About the only thing itʼs missing is somedocumentation: # = Class: ntp # # This class installs/configures/manages NTP. It can optionally disable NTP This doesnʼt have to be Tolstoy, but you should at least write down what the parameters are andwhat kind of data they take. Your future self will thank you. Also! If you write your documentation inRDoc format and put it in a comment block butted up directly against the start of the classdefinition, you can automatically generate a browsable Rdoc-style site with info for all yourmodules. You can test it now, actually: (Then just upload that ~/moduledocs folder to some webspace you control, or grab it onto yourdesktop with SFTP.) Okay, we can pass parameters into classes now and change their behavior. Great! But classes arestill always singletons; you canʼt declare more than one copy and get two different sets of behaviorLearning Puppet • Learning Puppet — Class Parameters 56/76simultaneously. And youʼll eventually want to do that! What if you had a collection of resources thatcreated a virtual host definition for a web server, or cloned a Git repository, or managed a useraccount complete with group, SSH key, home directory contents, sudoers entry, and.bashrc/.vimrc/etc. files? What if you wanted more than one Git repo, user account, or vhost on asingle machine? What you want is something more like a resource type — you canʼt declare the same resource twice,but you can declare as many files or users as you want. apache::vhost {'users.example.com': port => 80, docroot => '/var/www/personal', options => 'Indexes MultiViews', } This turns out to be easy. To model repeatable chunks of configuration — like a Git repository or anApache vhost — you should use defined resource types. Defined types act like normal resource types and are declared in the same way, but theyʼrecomposed of other resources. Defining a TypeYou define a type with the define keyword, and the definition looks almost exactly like a class withparameters. You need: A name A list of parameters (in parentheses, after the name) Defined types also get a special $title parameter without having to declare it, and its value is always set to the title of the resource instance. (The $name parameter acts the same way, and usually has the same value as $title.) Classes get these too, but theyʼre less useful since a class will only ever have one name. Like this: user {'nick': ensure => present, managehome => true, uid => 517, } planfile {'nick': content => "Working on new Learning Puppet chapters. Tomorrow: upgrading the LP virtual machine.", } This oneʼs pretty simple. (In fact, itʼs basically just a macro.) It has two parameters, one of which isoptional (it defaults to the title of the resource), and the collection of resources it declares is just asingle file resource. See how the title of the file resource isnʼt tied to any of the definitionʼs parameters? planfile {'chris': content => "Resurrecting a very dead laptop.", } Yikes. You can see where we went wrong — every time we declare an instance of planfile, itʼsgoing to declare the resource File['.plan'], and Puppet will fail compilation if you try to declarethe same resource twice. To avoid this, you have to make sure that both the title and the name (or namevar) of everyresource in the definition are somehow derived from a unique parameter (often the $title) of thedefined type. (For example, we couldnʼt derive the fileʼs title from the $content of the planfileresource, because more than one user might write the same .plan text.) Also inside the type definition, use something like the following to establish an order dependency: Establishing ordering relationships at the class level is generally better than directly requiring one of the resources inside it. You might have already noticed this above, but: when you make a resource reference to an instanceof a defined type, you have to capitalize every namespace segment in the typeʼs name. That meansan instance of the foo::bar::baz type would be referenced like Foo::Bar::Baz['mybaz']. # Definition: apache::vhost # # This class installs Apache Virtual Hosts # # Parameters: # - The $port to configure the host on # - The $docroot provides the DocumentationRoot variable # - The $template option specifies whether to use the default template or override # - The $priority of the siteLearning Puppet • Learning Puppet — Defined Types 60/76 # -'], }Learning Puppet • Learning Puppet — Defined Types 61/76 } # /etc/puppetlabs/modules/apache/templates/vhost-default.conf.erb # ************************************ # Default template in module puppetlabs-apache # Managed by Puppet # ************************************ And thatʼs more or less a wrap. You can apply a manifest like this: apache::vhost {'testhost': port => 8081, docroot => '/var/www-testhost', priority => 25, servername => 'puppet', } …and (as long as the directory exists) youʼll immediately be able to reach the new vhost: # curl In a way, this is just slightly more sophisticated than the first example — itʼs still only one fileresource — but the use of a template makes it a LOT more powerful, and you can already see howmuch time it can save. And you can make it slicker as you build more types: once youʼve got a ExercisesTake a minute to make a few more defined types, just to get used to modeling repeatable groups ofresources. Try wrapping a user resource in a human::user type that manages that personʼs .bashrc file and manages one or more ssh_authorized_key resources for their account. If youʼre familiar with git, take a stab at writing a git::repo type that can clone from a repository on the network (and maybe even keep the working copy up-to-date on a specific branch!). Thisʼll be harder — youʼll probably have to make a git class to make sure git is available, and youʼll have to use at least one file ( ensure => directory) and at least one exec resource. Keep in mind that execs can be tricky, since you need to make sure they only run when necessary. If youʼre going to make a practice of validating your inputs (hint: DO), you can save yourself a lot ofeffort by using the validation functions in Puppet Labsʼ stdlib module. We ship a version of stdlibwith PE 2.0, and you can also download it for free at either GitHub or the module forge. Thefunctions are: validate_array validate_bool validate_hash validate_re validate_string You can learn how to use these by running puppet doc --reference function | less on asystem that has stdlib installed in its modulepath, or you can read the documentation directly ineach of the functionsʼ files — look in the lib/puppet/parser/functions directory of the module. Thereʼs more to say about modules — we still havenʼt covered data separation, patterns for makingyour modules more readable, or module composition yet — but thereʼs more important businessafoot. Continue reading to prepare your VMs (yes, plural) for agent/master Puppet. Weʼve seen several Apache examples already, and itʼs pretty likely that youʼre running at least oneweb server in your own infrastructure. Why not use one of the off-the-shelf modules available, andsee whether you can reproduce your own configuration in an automated way? Download Puppet Enterprise for free, and follow the quick start guide to get a small environmentinstalled on some test machines. Then, install one of the following modules: puppetlabs/apache simondean/iis (for IIS on Windows Server) Any of the many Nginx modules Read the moduleʼs documentation to see how it works, then try managing the service and anyrelevant virtual hosts to match your manually configured infrastructure. If youʼre up to date, skip down to here. If youʼre running an older version, do one of the following: Before replacing your VM, make sure to save any manifests or modules from your previous copy.(After all, the whole point of Puppet is that you can use them to get right back to where you were.) Download the latest version of Puppet Enterprise. Choose the EL 5 for i386 installer, which is about 50 MB. Copy the installer tarball to your VM and follow the upgrade instructions in the PE 2 Userʼs Guide. This is more advanced than just downloading the current VM, especially if youʼre upgrading from PE1.0 or 1.1, but weʼve tried to document the process clearly. Follow the instructions for upgrading acombined master/console server. Below, we give instructions for copying the VM with VMware Fusion and with VirtualBox. (Note: although we donʼt provide a full walkthrough for VMware Workstation, the process should besimilar.) 1. If you still have the zipped VM archive you originally downloaded, you can extract it again for a fresh copy. Otherwise, shut down the VM by running shutdown -h now while logged in as root. Once the system is stopped, locate the folder or bundle that contains the VMX file — you can right-click its entry in the Virtual Machine Library window and choose “Show in Finder” — and duplicate that entire directory. 3. Once Fusion has the VM, you can right-click its entry in the Library window and choose “Settings” to change the amount of memory it will consume. (Use the “Processors & RAM” section of the settings window.) Although the original (puppet master) VM will need at least 512 MB of RAM, you can safely dial the agent VM down to 256 MB. You shouldnʼt need to change the networking settings from the default mode (NAT); with VMware, this will allow your VMs to access the internet, each other, and your host system. If you need other nodes on the network to be able to contact your VMs, you can change the networking mode to Bridged. 4. When you start the VM for the first time, Fusion will ask whether you moved it or copied it. You should answer that you copied it. With VirtualBox 1. If you still have the folder with the original OVF file, you can re-import it into VirtualBox for a new VM. Otherwise, shut down the VM by running shutdown -h now while logged in as root. Once the system is stopped, right-click on the VMʼs entry in the VirtualBox Manager window, and select Clone. You will be presented with a series of dialog boxes. 3. You can also click on the “System” settings to reduce the amount of memory the VM will consume. An agent node should only need 256 MB of RAM. # wget # tar -xzf learningpuppet.tar.gz # mv learningpuppet /etc/puppetlabs/puppet/modules/ # puppet apply -e "class {'learningpuppet::makeagent':}" If you donʼt give the class a newname attribute, it will default to agent1, which is probably what youwant. The VMs will be communicating via their eth0 IP addresses. Find these addresses by runningfacter ipaddress_eth0 on each system, then try to ping that IP from the other VM. WITH VIRTUALBOX If both VMs have a single network adapter in Bridged Adapter mode (recommended), they will becommunicating via their eth0 IP addresses. Find these addresses by running facteripaddress_eth0 on each system, then try to ping that IP from the other VM. If you have configured the VMs to have two network adapters, examine their settings — the VMs willbe communicating via whichever adapter is set to Host Only Adapter mode. Run facteripaddress_<ADAPTER> to find these IP addresses. Make sure both VMsʼ /etc/hosts files contain a line similar to the following: The IP address should be the one you found for the puppet master in the previous step. Once youʼve edited the files, test that both VMs can ping the master at both its full name and itsaliases: If this doesnʼt work, make sure that the /etc/hosts files donʼt have any conflicting lines — thereshould be only one line with those puppet master hostnames. If /etc/hosts looks good, you mayalso need to flush cached DNS information in each VM: # nscd --invalidate=hosts We shipped the VM with iptables turned off, but itʼs worth checking to make sure itʼs still down: (In a real environment, youʼd add firewall rules for Puppet traffic instead of disabling the firewall.) Run date -u on both VMs, and compare the output. They should be within about a minute of eachother. NextYour VMs are ready — now continue reading for a tour of the agent/master Puppet workflow. IntroductionHow Do Agents Get Configurations? Puppetʼs agent/master mode is pull-based. Usually, agents are configured to periodically fetch acatalog and apply it, and the master controls what goes into that catalog. (For the next fewexercises, though, youʼll be triggering runs manually.) Earlier, you saw this diagram of how Puppet compiles and applies a manifest: Weʼll be using the second mode, since it gives a better view of whatʼs going on. To keep the agentfrom daemonizing, you should use the --test option, which also prints detailed descriptions ofwhat the agent is doing. If you accidentally run the agent without --test, it will daemonize and run in the background. Tocheck whether the agent is running in the background, run: # /etc/init.d/pe-puppet status # /etc/init.d/pe-puppet stop Saying HiTime to start! On your agent VM, start puppet agent for the first time: Hmm. What Happened? Puppet agent found the puppet master, but it got stopped at the certificate roadblock. It isnʼtauthorized to fetch configurations, so the master is turning it away. TroubleshootingLearning Puppet • Learning Puppet — Basic Agent/Master Puppet 72/76Itʼs possible you didnʼt see the response printed above, and there are a number of possible culprits.Read back over the instructions for creating your agent VM and make sure you didnʼt miss anything;in particular, check that: Thereʼs our agent node. And the request fingerprint matches, too. You know this node is okay, sogo ahead and sign its certificate with puppet cert sign: Now that itʼs authorized, go back to the agent VM and run puppet agent again: It worked! That was a successful Puppet run, although it didnʼt do much yet. Site.pp When we were using puppet apply, we would usually specify a manifest file, which declared all ofthe classes or resources we wanted to apply. The puppet master works the same way, except that it always loads the same manifest file, whichwe usually refer to as site.pp. With Puppet Enterprise, itʼs located by default at/etc/puppetlabs/puppet/manifests/site.pp, but you can configure its location with themanifest setting. You could declare classes and resources directly in site.pp, but that would make every node get thesame resources in its catalog, which is of limited use. Instead, weʼll hide the classes we want todeclare in a node definition. Node Definitions node 'agent1.localdomain' { # Note the quotes around the name! Node names can have characters that # aren't legal for class names, so you can't always use bare, unquoted # strings like we do with classes. class {'ntp': enable => false, ensure => stopped, } But unlike classes, nodes are declared automatically, based on the name of the node whose catalogis being compiled. Only one node definition will get added to a given catalog, and any other nodedefinitions are effectively hidden. An agent nodeʼs name is almost always read from its certname setting, which is set at install timebut can be changed later. The certname is usually (but not always) the nodeʼs fully qualified domainname. More on node definitions later, as well as alternate ways to assign classes to a node. Now that youʼve saved site.pp with a node definition that matches the agent VMʼs name, go back tothat VM and run puppet agent again: If you change this nodeʼs definition in site.pp, it will fetch that new configuration on its next runLearning Puppet • Learning Puppet — Basic Agent/Master Puppet 75/76If you change this nodeʼs definition in site.pp, it will fetch that new configuration on its next run(which, in a normal environment, would happen less than 30 minutes after you make the change). Authorize a new agent node to pull configurations from the puppet master Use node definitions in site.pp to choose which classes go into a given nodeʼs catalog But there are some important details weʼve glossed over. In a future installment, weʼll talk moreabout certificates and node classification.© 2010 Puppet Labs info@puppetlabs.com 411 NW Park Street / Portland, OR 97209 1-877-575-9775
https://de.scribd.com/document/193582420/Learning-Puppet
CC-MAIN-2019-43
refinedweb
13,085
61.87
Without the name, it runs fine. I read up that adding const before new could solve my problem, but it doesn't. Any ideas? include <iostream> include <string.h> using namespace std; class Player { int Health, *Strength, *Speed, *Accuracy, *Defense; char *Name[80]; public: Player (char, int, int, int, int, int); ~Player (); void Manip (int, int, int, int, int); void Output (); }; Player::Player (char Nme, int Hth, int Str, int Spd, int Acc, int Dfn) { Name = new char[80]; Health = new int; Strength = new int; Speed = new int; Accuracy = new int; Defense = new int; *Name[80] = Nme[]; *Health = Hth; *Strength = Str; *Speed = Spd; *Accuracy = Acc; *Defense = Dfn; } Player::~Player () { delete Health; delete Strength; delete Speed; delete Accuracy; delete Defense; } void Player::Manip (int A, int B, int C, int D, int E) { *Health = *Health + A; *Strength = *Strength + B; *Speed = *Speed + C; *Accuracy = *Accuracy + D; *Defense = *Defense + E; } void Player::Output () { cout << "\nHealth: " << *Health << endl; cout << "Strength: " << *Strength << endl; cout << "Speed: " << *Speed << endl; cout << "Accuracy: " << *Accuracy << endl; cout << "Defense: " << *Defense << endl << endl; } int main () { Player Player1 ("Player One", 100, 20, 20, 20, 20), Player2 ("Player Two", 500, 100, 100, 100, 100); Player1.Player::Output(); Player2.Player::Output(); Player1.Player::Manip (10, 10, 10, 10, 10); Player2.Player::Manip (20, 10, 10, 20, 10); Player1.Player::Output(); Player2.Player::Output(); return 0; }
https://www.daniweb.com/programming/software-development/threads/420263/constructor-with-char-calling-an-error
CC-MAIN-2017-43
refinedweb
220
51.11
Webhooks¶ pretix can send webhook calls to notify your application of any changes that happen inside pretix. This is especially useful for everything triggered by an actual user, such as a new ticket sale or the arrival of a payment. You can register any number of webhook URLs that pretix will notify any time one of the supported events occurs inside your organizer account. A great example use case of webhooks would be to add the buyer to your mailing list every time a new order comes in. Configuring webhooks¶ You can find the list of your active webhooks in the “Webhook” section of your organizer account: Click “Create webhook” if you want to add a new URL. You will then be able to enter the URL pretix shall call for notifications. You need to select any number of notification types that you want to receive and you can optionally filter the events you want to receive notifications for. You can also configure webhooks through the API itself. Receiving webhooks¶ Creating a webhook endpoint on your server is no different from creating any other page on your website. If your website is written in PHP, you might just create a new .php file on your server; if you use a web framework like Symfony or Django, you would just create a new route with the desired URL. We will call your URL with a HTTP POST request with a JSON body. In PHP, you can parse this like this: $input = @file_get_contents('php://input'); $event_json = json_decode($input); // Do something with $event_json In Django, you would create a view like this: def my_webhook_view(request): event_json = json.loads(request.body) # Do something with event_json return HttpResponse(status=200) More samples for the language of your choice are easy to find online. The exact body of the request varies by notification type, but for the main types included with pretix core, such as those related to changes of an order, it will look like this: { "notification_id": 123455, "organizer": "acmecorp", "event": "democon", "code": "ABC23", "action": "pretix.event.order.placed" } Notifications regarding a check-in will contain more details like orderposition_id and checkin_list. Warning You should not trust data supplied to your webhook, but only use it as a trigger to fetch updated data. Anyone could send data there if they guess the correct URL and you won’t be able to tell. Therefore, we only include the minimum amount of data necessary for you to fetch the changed objects from our REST API in an authenticated way. Warning In very rare cases, you could receive the same webhook notification twice. We try to avoid it, but we prefer it over missing a notification. If you want to further prevent others from accessing your webhook URL, you can also use Basic authentication and supply the URL to us in the format of. We recommend that you use HTTPS for your webhook URL and might require it in the future. If HTTPS is used, we require that a valid certificate is in use. Note If you use a web framework that makes use of automatic CSRF protection, this protection might prevent us from calling your webhook URL. In this case, we recommend that you turn of CSRF protection selectively for that route. In Django, you can do this by putting the @csrf_exempt decorator on your view. In Rails, you can pass an except parameter to protect_from_forgery. Responding to a webhook¶ If you successfully received a webhook call, your endpoint should return a HTTP status code between 200 and 299. If any other status code is returned, we will assume you did not receive the call. This does mean that any redirection or 304 Not Modified response will be treated as a failure. pretix will not follow any 301 or 302 redirect headers and pretix will ignore all other information in your response headers or body. If we do not receive a status code in the range of 200 and 299, pretix will retry to deliver for up to three days with an exponential back off. Therefore, we recommend that you implement your endpoint in a way where calling it multiple times for the same event due to a perceived error does not do any harm. There is only one exception: If status code 410 Gone is returned, we will assume the endpoint does not exist any more and automatically disable the webhook. Note If you use a self-hosted version of pretix (i.e. not our SaaS offering at pretix.eu) and you did not configure a background task queue, failed webhooks will not be retried.
https://docs.pretix.eu/en/latest/api/webhooks.html
CC-MAIN-2020-50
refinedweb
769
59.84
Hausdorff Distance¶ This example shows how to calculate the Hausdorff distance between two sets of points. The Hausdorff distance is the maximum distance between any point on the first set and its nearest point on the second set, and vice-versa. import matplotlib.pyplot as plt import numpy as np from skimage import metrics shape = (60, 60) image = np.zeros(shape) # Create a diamond-like shape where the four corners form the 1st set of points x_diamond = 30 y_diamond = 30 r = 10 fig, ax = plt.subplots() plt_x = [0, 1, 0, -1] plt_y = [1, 0, -1, 0] set_ax = [(x_diamond + r * x) for x in plt_x] set_ay = [(y_diamond + r * y) for y in plt_y] plt.plot(set_ax, set_ay, 'or') # Create a kite-like shape where the four corners form the 2nd set of points x_kite = 30 y_kite = 30 x_r = 15 y_r = 20 set_bx = [(x_kite + x_r * x) for x in plt_x] set_by = [(y_kite + y_r * y) for y in plt_y] plt.plot(set_bx, set_by, 'og') # Set up the data to compute the hausdorff distance coords_a = np.zeros(shape, dtype=np.bool) coords_b = np.zeros(shape, dtype=np.bool) for x, y in zip(set_ax, set_ay): coords_a[(x, y)] = True for x, y in zip(set_bx, set_by): coords_b[(x, y)] = True # Call the hausdorff function on the coordinates metrics.hausdorff_distance(coords_a, coords_b) # Plot the lines that shows the length of the hausdorff distance x_line = [30, 30] y_line = [20, 10] plt.plot(x_line, y_line, 'y') x_line = [30, 30] y_line = [40, 50] plt.plot(x_line, y_line, 'y') # Plot circles to show that at this distance, the hausdorff distance can # travel to its nearest neighbor (in this case, from the kite to diamond) ax.add_artist(plt.Circle((30, 10), 10, color='y', fill=None)) ax.add_artist(plt.Circle((30, 50), 10, color='y', fill=None)) ax.add_artist(plt.Circle((15, 30), 10, color='y', fill=None)) ax.add_artist(plt.Circle((45, 30), 10, color='y', fill=None)) ax.imshow(image, cmap=plt.cm.gray) ax.axis((0, 60, 60, 0)) plt.show() Total running time of the script: ( 0 minutes 0.223 seconds) Gallery generated by Sphinx-Gallery
https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_hausdorff_distance.html
CC-MAIN-2020-45
refinedweb
350
64.61
Opened 4 years ago Last modified 4 years ago #23501 new Bug remove/add fields programatically in modelform fails in admin Description (last modified by ) model: class Thickness(models.Model): value = models.DecimalField(primary_key=True, max_digits=7, decimal_places=2) is_active = models.BooleanField() model form: class ThicknessForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ThicknessForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) # edit if instance and instance.pk: del self.fields['value'] else: del self.fields['is_active'] class Meta: model = Thickness fields = '__all__' admin: class ThicknessAdmin(admin.ModelAdmin): list_display = ('value', 'is_active') form = ThicknessForm admin.site.register(Thickness, ThicknessAdmin) refresh page, go to admin->Thickness, create one: KeyError at /admin/thicknesses/thickness/add/ "Key 'is_active' not found in 'ThicknessForm'" ... Error during template rendering In template D:\env\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 7 The highlighted line is number 7 6 {% for line in fieldset %} 7 <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"> 8 {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %} go to admin->Thickness again, modify one (created previously without using model form): KeyError at /admin/thicknesses/thickness/0.55/ "Key 'value' not found in 'ThicknessForm'" ... same error as above Without admin, model form works as expected, it remove is_active when create, and it remove value when edit Change History (6) comment:1 Changed 4 years ago by comment:2 Changed 4 years ago by comment:3 Changed 4 years ago by I am aware of such methods, what i was trying to do is to push as much form control in modelform instead of in the admin. So next time when i have time i can build my own admin and reuse modelform without modifying the code again comment:4 Changed 4 years ago by You should be able to keep the del logic, as long as you also use get_fields(). comment:5 Changed 4 years ago by thank you for your quick response, in the mean time, i will try your suggestion comment:6 Changed 4 years ago by A little update: i tried get_fields() method and still keep del intact, it turns out to be an error KeyError at /admin/thicknesses/thickness/0.55/ 'value' 21. def __init__(self, *args, **kwargs): 22. super(ThicknessForm, self).__init__(*args, **kwargs) 23. instance = getattr(self, 'instance', None) 24. 25. # edit 26. if instance and instance.pk: 27. del self.fields['value'] <-- 28. 29. class Meta: occur in line 27 i guess i have to forget about the form and put everything in admin then. What worries me is there will be several models that requires the clean() method in form to check related fields, that means that i have two places (form and admin) that handles the form, and i don't think that's a good approach I looked into this and I believe you can fix this by using ModelAdmin.get_fields() to exclude the field. It might be easiest to simply document that you should use that method and not the delapproach.
https://code.djangoproject.com/ticket/23501
CC-MAIN-2018-34
refinedweb
532
57.27
Windows Phone 8 Unit Testing - The Basics Unit testing in Windows Phone has never been really supported by Microsoft: the only semi-official way to do unit tests in Windows Phone 7 is using an adaptation of the Silverlight Unit Test Framework made by Jeff Wilcox. This library is able to render a Windows Phone application, that is capable of running the unit tests included in the project. The downside of this approach is that you have to use a dedicated Windows Phone app to run the tests, instead of using a built-in tool like Resharper. The biggest advantage, instead, is that unit tests are executed into a real environment, so it’s easy to write integration tests that makes use, for example, of the storage or of a real Internet connection. Since, how to run simple tests and, in the next post, how to face some more complicated scenarios (like mocking and dealing with async methods). Preparing the environment As I anticipated you, the tests are executed in a separate Windows Phone application: for this reason, you’ll have to add another Windows Phone project to your solution. Once you’ve done it, you can install the Windows Phone toolkit from NuGet and the unit testing framework: now we are ready to set up the application. The first thing is to open the code behind file of the MainPage, that is MainPage.xaml.cs and add in the constructor, right below the InitializeComponent() method, the following code: public MainPage() { InitializeComponent(); this.Content = UnitTestSystem.CreateTestPage(); } This way when the application is launched the unit test runner is displayed: you can see it by yourself by launching the application in the emulator. The first screen will ask you if you want to use tags or not (we’ll see later which is their purpose): if you press the Play button in the application bar you’ll be redirected to the main window of the unit test runner, even if you won’t see no tests at the moment since we haven’t added one yet. The next step is to create one or more classes that will hold our tests: in a real scenario we would create a unit test class for every real class that we need to test. For this example, we’re simply going to create a single class: we can place it everywhere we want but, to keep the structure of the project organized, we will add a new foldercalled UnitTests and we will add the new class there: in my example, I’ve called it SimpleUnitTest. To add it, simply right click on the new folder, choose Add – New item and add a Class file. The first thing to do is to add the namespace Microsoft.VisualStudio.TestTools.UnitTesting at the top of your class: this way we can access to the attributes and classes needed to test our code. The second step is to mark the entire class with the attribute [TestClass]: this way we’ll tell to the application that this class contains unit tests that should be processed and executed. Now let’s add a simple unit test (to be honest, it’s more stupid than simple ): the purpose is just to make you comfortable with the basics. [TestClass] public class SimpleUnitTest { [TestMethod] public void SimpleTest() { int a = 1; int b = 2; int c = a + b; Assert.IsTrue(c == 3); } } Notice the [TestMethod] attribute that we used to mark the SimpleTest method: with this attribute we’re telling to the application that this method actually contains a unit test that should be executed. The test is really stupid: we sum two numbers and we check that the sum is correct, using the Assert class, which contains different methods that can be used to check the results of our test. In this case, we need to test a boolean condition, so we can use the IsTrue method. Other examples of methods are IsNotNull (to check that a object actually has a value) or IsInstanceOfType (to check if the object’s type is the one we expect). Run the application and launch the tests: this time you’ll see the test run and you’ll be prompted with the results. Obviously, in this case, the test will pass, since 1+2 = 3. Let’s test a fail case: change the condition that is tested in a way that is not true anymore, like in the example: [TestClass] public class SimpleUnitTest { [TestMethod] public void SimpleTest() { int a = 1; int b = 2; int c = a + b; Assert.IsTrue(c == 4); } } Run again the application: this time you’ll see that test is failed. Clicking on the test will let you see the details and why it failed: in this case, you’ll clearly understand that the Assert.IsTrue operation is failed. Using tags Sometimes you don’t want to run all the tests that are available in your classes, but just a subsets: this is what tags are for. To use them, you have to add to your test class the namespace Microsoft.Phone.Testing, which will allow you to decorate a test method with the Tag attribute, followed by a keyword. To see this feature in action, let’s add another test method: we’ll set the Tag attribute just for one of them. [TestClass] public class SimpleUnitTest { [Tag("SimpleTests")] [TestMethod] public void SimpleTest() { int a = 1; int b = 2; int c = a + b; Assert.IsTrue(c == 3); } [TestMethod] public void SimpleTest2() { int a = 3; int b = 1; int c = a + b; Assert.IsTrue(c == 4); } } Now run again the application and this time, in the first screen, trigger the Use tags switch to On. You will be prompted to specify a keyword that will be used by the application to determine which test run: insert the keyword SimpleTests (which is the tag we’ve set for the test method called SimpleTest) and press the Play button. You’ll see that, despite the fact you have two test methods in your class, only the first one will be executed. Tagging is a great way to group unit tests so that, if you need to test just a specific class or feature, you don’t have to go through all the unit tests. Debugging If a test fails and you don’t know, it’s really easy to debug it: since, when you launch the unit test runner from Visual Studio, you are launching a standard Windows Phone application, you can simply set breakpoints in your test methods: they will be hit when the tests are executed and you can step into the code to see what’s going on. Asynchronous tests, mocking and a lot more In the next post we’ll cover some advanced but quite common scenarios, like mocking and asynchronous method testing. Keep up the good work meanwhile! end (Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
http://mobile.dzone.com/articles/windows-phone-8-unity-testing
CC-MAIN-2014-35
refinedweb
1,169
62.01
I need to take the following two files as input and replace the words in input 2 with its corresponding tag (some words have multiple tags,which need to be accounted for as seen in "api . ani"). input1 - Code: Select all last-n nmod+j+n year-n 9492 last-n nmod+j+n night-n 8075 first-n nmod+j+n-the time-n 7749 same-n nmod+j+n-the time-n 7530 other-j nmod+j+n-the hand-n 5319 ast-j nmod+j+n year-n 1000 last-j nmod+j+n night-n 5000 first-j nmod+j+n-the time-n 1000 same-j nmod+j+n-the time-n 3000 other-j nmod+j+n-the hand-n 200 input2 - Code: Select all same ani.api first ani abaya art abbacy log abbe hum abbess hum abbey art for the following output: - Code: Select all last-n nmod+j+n year-n 9492 last-n nmod+j+n night-n 8075 ani.api nmod+j+n-the time-n 7749 ani nmod+j+n-the time-n 7530 other-j nmod+j+n-the hand-n 5319 ast-j nmod+j+n year-n 1000 last-j nmod+j+n night-n 5000 ani.api nmod+j+n-the time-n 1000 ani nmod+j+n-the time-n 3000 other-j nmod+j+n-the hand-n 200 This is the code I am trying to work with, but I need some help to solve the problem. - Code: Select all from __future__ import division import collections import codecs input_file1 = codecs.open("test_awking","r",encoding="utf-8") input_file2 = codecs.open("final_FILLERS2CATS.map","r",encoding="utf-8") countsCorps = {} with input_file1 as f: for line in f: (concept, link, slot, freq) = line.split() classDict = {} with input_file2 as f: for line in f: (classConc, classId) = line.split() classDict[classConc] = classId classes = classDict[classConc].split(".") try lemma in classDict.keys(): count[lemma][]+=1/len(classes) except AttributeError continue print lemma, link, slot, freq input_file1.close() input_file2.close() I think I am getting a bit confused in the organization of arguments.. but I am getting too far in and need some fresh insight. Can anyone offer assistance? Thank you
http://python-forum.org/viewtopic.php?f=6&t=8286&p=10946
CC-MAIN-2015-11
refinedweb
372
54.22
On Sun, Jun 5, 2011 at 5:49 AM, Geert Uytterhoeven <geert@linux-m68k.org> wrote:> On Sun, Jun 5, 2011 at 09:54, Baruch Siach <baruch@tkos.co.il> wrote:>> On Sun, Jun 05, 2011 at 01:13:28PM +0530, Jassi Brar wrote:>>> On Sun, Jun 5, 2011 at 12:48 PM, Grant Likely <grant.likely@secretlab.ca> wrote:>>> > [repost: I had a typo on the spi-devel-general mailing list address]>>> >>>> > Sort the SPI makefile and enforce the naming convention spi_*.c for>>> > spi drivers.>>>> [snip]>>>>> Though the spi_ prefix seems redundant considering the files are in>>> 'spi' directory.>>> Just a thought, no objection.>>>> When looking at the list of loaded modules (e.g. in an Oops message), the name>> "spi_xilinx" is much more meaningful than just "xilinx", for example.>> Plus, when dropping the prefix, spi_xilinx.ko and gpio-xilinx.ko> become the same...Exactly. We essentially have a flat namespace for modules, despitethe fact of them being organized into directories. At least for thesubsystems I maintain, I'd like to have a consistent prefix for thatreason.> So now we have spi_<name>.c (with underscore) and gpio-<name>.c (with dash)?> And other subsystems go with <name>-<type>.c instead, e.g.> drivers/mfd/wm831x-spi.c?On a brief survey of drivers:apci: *.cata: pata_*.c, sata_*.catm: *.cblock: *.cbluetooth: *.ccrypto: *.cdma: *dma.cgpio: gpio-*.c (after applying my patch)hid: hid-*.chwmon: *.ci2c: i2c-*.cide: *.c and ide-*.cinput: *.cleds: leds-*.cmca: mca-*.cmd: largely dm-*.cmfd: *.cmmc: *.cmtd: *.cnet: *.crtc: rtc-*.cscsi: *.c and scsi_*.c for core codespi: (before patch) mix of spi_*.c and *_spi.c and *.cuio: uio_*.cvirtio: virtio_*.cwdt: *wdt.c and *_wdt.cSo, in this (admittedly incomplete) survey, I see 5 users of the"prefix_" pattern, 8 of the "prefix-" pattern, a small number using asuffix, and a whole lot without any pattern at all. Personally, Iprefer the using a prefix with a '-', but in the spi directory therewas already a number of drivers using '_', so it was smaller impact tochange to using that instead of a dash. If people don't think it is abig deal though, then I'll change it to '-' to match the gpio change.g.
http://lkml.org/lkml/2011/6/5/183
CC-MAIN-2014-42
refinedweb
373
69.28
What is the fast power of a matrix? - Fast power is a fast method to solve the power of a number by using binary. The principle of fast power will be briefly explained later. If you still don't understand it, please Baidu yourself. I believe that many young friends are new to college and may not have studied linear algebra (such as me), so they almost don't know what matrix is. I recommend a website to see how matrix multiplication works. Here is the website link: (how to this website is really a cow. There are tutorials on everything, and the quality is high! 😂) Calculation method of matrix multiplication So how to use code to represent the matrix and its multiplication? In fact, it is very simple, that is, three-layer cycle control. For example, here is the overloaded operator of C + +. Matrix is a class defined by me.; } How to calculate the fast power of matrix? About how to fast power a matrix, let's first look at the simple fast power. Fast power is to realize fast same number multiplication through bit operation. Briefly describe the principle of fast power: The principle is that if the third power of X is required, it can be transformed into the second power of x*x, and it is very simple to find the 2^n power of a number. For example, if x *= x once, we will get the quadratic power of X. if x *= x again, we will get the fourth power, and if we continue, we can get 8 / 16... In short, it is the time of log2N. The code is as follows: int QuickPow(int x,int n){ int c = n; int res = 1; while(c!=0){ if(c&1!=0){ res *= x; } c >>= 1; x *= x; } return res; } - So how does the fast power of the matrix proceed? Replacing the above int type with a self-defined matrix is the fast power of the matrix. I directly pasted the fast power writing method of the class after the overloaded operator implemented in C + +: quickPow here represents a member function of a class, so you can directly use the data in this matrix for operations. This represents the pointer to this object. init() member function represents initialization to the identity matrix. void quickPow(ll c){ if(c==1||c<0)return; if(c==0){ init(); return; } Matrix tmp(*this); init(); while (c){ if(c&1){ *this = *this * tmp; } c >>= 1; tmp = tmp*tmp; } } Why do you suddenly want to write this template? It's mainly because I recently did several fast power problems, and I was badly hurt. Then I suddenly wanted to design a template, mainly my_tiny_stl This warehouse hasn't been updated for a long time 😂 subject How did I get trapped - First, I got this question, and I immediately started to implement the simple O(n) recursive method, then submitted it, and then timed out.. When I fixed my eyes, the amount of data turned out to be so large! After thinking about it, it must be the fast power of the matrix. First come up with the recursive formula of the following matrix: Then the problem can be solved. Then I simply encapsulated a matrix class with C + + classes, which overloaded the multiplication and quickpow methods, and then leisurely prepared to submit. Before submitting, I encountered the syntax traps of C + + Syntax trap (non-C + + party detour recommended) Because classes use heap memory, I wrote destructors. The problem I encountered was that when I overloaded multiplication, I returned an lvalue, and I did not overload '=', so '=' is a direct copy of member variables. As a result, the date s of the two objects point to the same memory space, and the previous memory space is leaked, and The latter two objects will certainly call the destructor, which leads to the destructor calling twice! - How to solve this problem? If it is C++98, this problem is very big. Basically, there are two methods to solve it: - To avoid the problem, the left operand of multiplication must be the current assignment object, so as to avoid the direct change of the pointer in the original object by the last assignment statement. - The most direct way to solve this kind of problem, whether C++11 or C++98, is to overload the '=' number. The implementation of the overload '=' number is carried out according to the specific situation. For the specific implementation of the overload of assignment, we need to consider two things: first, we need to reduce the application and use of memory as much as possible (specifically, judge whether the pointers of two objects point to the same space, even if they are not the same space. In order to increase space utilization, you can also judge whether the two spaces are the same size, and then copy). Second, if it is a temporary object, you need to set its pointer to null (prevent the compiler from not optimizing the destructor of temporary variables, so that the destructor is called to destruct the same memory multiple times). - Since C++11 began to have the right value reference and its supporting mobile assignment constructor, it can directly call the temporary variable to the mobile constructor into a named object, and then operate. Generally, it is to transfer its pointer ownership, and then set its pointer to null to prevent parsing errors. In my understanding, the emergence of right value reference is to capture anonymous objects After that, the appropriate performance optimization operation is given to the programmer. Before there is no right value reference, the memory of the anonymous object can not be used at all. It can only be used after simple assignment and copy operation, which consumes memory. After the right value reference appears, we can capture the anonymous object through the right value reference, and then operate its underlying memory. There is also a big problem Memory related updates have a nullptr keyword, which makes null pointers no longer ambiguous, so delete nullptr is safe. Therefore, to prevent errors from deleting the same space multiple times, you can assign it nullptr. - So how to solve the problem based on C++11? The solution is just as good as C++98, which is more convenient for memory management. If there is an R-value on the right of the equal sign, it must be a temporary object, so we can directly use its memory in the overload of '=' and set its pointer to null. If there is no R-value type For line capture, the compiler will also optimize temporary objects by default, and can prevent the generation of assignment copies of multiple objects, but it can only be optimized during object initialization! At other times, the destructor will still be called. At this time, if the '=' overload generated by the compiler by default will be used, the pointer of the space to be parsed will be assigned, The assignment overload of our R-value reference version is aimed at this phenomenon. In this way, it is convenient for memory management to separate the R-value and l-value. The R-value is a temporary variable, which only takes a while, so it can directly take its memory to continue to use without affecting the program logic. The l-value is different, and it still needs to survive for a long time, so I We need to create another space to copy. Special reminder: if you are doing algorithm problems, you don't need to consider memory management at all, and don't write destructors. After all, you only need a single call, and the object can exist for a while at most. Problem trap Don't be reluctant to open long long when necessary!!!! The data quantity of this problem, whether to the power of power or the data of the whole recording process, should be long long!!! I've been trapped by this trap countless times, and this time it's no different 😅 After I started writing this class, I passed the first five, and then the last five reported errors. I thought there was a problem with the class I designed, and I specially wrote several ordinary C language versions 😂 Finally, I found that the old one didn't open long long. The following is the code version after changing long long. I wrote several versions with macro definitions... The design of this Matrix class is still not considered in place in many places. For example, the problem of the previous trap is only solved through method 1 without overloading the assignment operator... So learn from the past and design a more available Matrix class! - The efficiency is fast and slow, which mainly depends on whether the compiler is optimized. // // Created by Alone on 2021/11/19. // #include <bits/stdc++.h> using namespace std; //#define ELSE_MAIN #define MY_MAIN #define MAT #ifdef MAT typedef long long ll; class Matrix{ ll** date; int m; int n; public: static const int MOD; public: Matrix(ll** rec,int n,int m):date(rec),n(n),m(m){}//C style initialization Matrix():date(NULL),m(0),n(0){} //default Matrix(Matrix& b):n(b.n),m(b.m){//copy construction assert(b.date!=NULL && b.n>0 && b.m>0); date = new ll*[n]; copy(b.date,b.date+n,date); for(int i=0;i<n;i++){ date[i] = new ll[m]; copy(b.date[i],b.date[i]+m,date[i]); } } ~Matrix(){//Destructor implementation assert(date!=NULL && n>0 && m>0); for (int i = n-1; i >=0 ; --i) { delete [] date[i]; } delete[] date; }; } void init(){//Reinitialize to identity matrix assert(date!=NULL && n>0 && m>0); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if(i==j)date[i][j] = 1; else date[i][j] = 0; } } } void quickPow(ll c){ if(c==1||c<0)return; if(c==0){ init(); return; } Matrix tmp(*this); init(); while (c){ if(c&1){ *this = *this * tmp; } c >>= 1; tmp = tmp*tmp; } } void print(){ for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ cout<<date[i][j]<<' '; } cout<<endl; } } int get(int x,int y){ assert(date!=NULL && x<n && y<m); return date[x][y]; } }; const int Matrix::MOD = 1e9+7; #endif #ifdef MY_MAIN int main(){ ll c; cin>>c; ll** matrix = new ll*[2]; matrix[0] = new ll[2]{1,1}; matrix[1] = new ll[2]{1,0}; Matrix mat(matrix,2,2); mat.quickPow(c-1); //mat.print(); ll** res = new ll*[2]; res[0] = new ll[1]; res[1] = new ll[1]; res[0][0] = res[1][0] = 1; Matrix fib(res,2,1); //There is a memory allocation error. mat*fib returns an lvalue, while = does not overload the default direct assignment member variable. //As a direct result, fib loses its previous variable ownership and shares a memory space with mat, resulting in the same space being free twice //Overload the = sign to prevent rebinding the same piece of memory without releasing the direct memory Matrix ret(mat*fib); cout<<ret.get(0,0); return 0; } #endif #ifdef TEST_MAIN typedef long long ll ; const int MOD = 1e9+7; ll a[2][2]{{1,1},{1,0}};ll b[2]{1,1}; void selfMut(){ ll tmp[2][2]; for(int i=0;i<2;i++){ for(int j=0;j<2;j++){ ll sum = 0; for(int k=0;k<2;k++){ sum = (sum+a[i][k]*a[k][j])%MOD; } tmp[i][j] = sum; } } for(int i=0;i<2;i++){ memmove(a[i],tmp[i],sizeof(tmp[i])); } } void difMut(){ ll tmp[2]; for(int i=0;i<2;i++){ ll sum = 0; for(int k=0;k<2;k++){ sum = (sum + a[i][k]*b[k])%MOD; } tmp[i] = sum; } b[0] = tmp[0]; b[1] = tmp[1]; } void Mut(ll _a[2][2],ll _b[2][2],int n1,int m1,int n2,int m2){ if(m1!=n2) return ; int tmp[n1][m2]; for(int i=0;i<n1;i++){ for(int j=0;j<m2;j++){ ll sum = 0; for(int k=0;k<m1;k++){ sum = (sum+_a[i][k]*_b[k][j])%MOD; } tmp[i][j] = sum; } } for(int i=0;i<n1;i++){ for(int j=0;j<m2;j++){ _a[i][j] = tmp[i][j]; } } } void quickPow(int k){ ll tmp[2][2]{{1,0},{0,1}}; while (k){ if(k&1){ Mut(tmp,a,2,2,2,2); } k>>=1; selfMut(); } for(int i=0;i<2;i++){ memmove(a[i],tmp[i],sizeof(tmp[i])); } } int main(){ int c; cin>>c; quickPow(c-1); for(int i=0;i<2;i++){ for(int j=0;j<2;j++){ printf("%d ",a[i][j]); } cout<<endl; } difMut(); cout<<b[0]; } #endif #ifdef ELSE_MAIN const long long int p = 1000000007; struct Mat { long long int m[2][2]; }; Mat ans, base; Mat Mul(Mat x, Mat y) { Mat c; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { c.m[i][j] = 0; for(int k = 0; k < 2; k++) { c.m[i][j] = (c.m[i][j] + x.m[i][k] * y.m[k][j]) % p; } } } return c; } int Qpow(long long int n) { for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { if(i == j) { ans.m[i][j] = 1; } else { ans.m[i][j] = 0; } if(i == 1 && j == 1) { base.m[i][j] = 0; } else { base.m[i][j] = 1; } } }//In this section, in order to initialize ans as an identity matrix, initialize base as a matrix of the required n-power while(n) { if(n & 1) { ans = Mul(ans, base); } base = Mul(base, base); n >>= 1; } return ans.m[0][0]; } int main() { long long int n = 0; cin >> n; cout << Qpow(n); return 0; } #endif Teach you to design Matrix classes How to design a class? Structure: - Internal data abstraction: operation data storage of objects - The two-level pointer date is used for memory management of the two-dimensional space of the matrix, and n and m represent the row height and column width of the matrix. - Behavior abstraction: a description of the behavior of an object - Constructor (default, custom, copy, move) and destructor (call destory member function). - Setters and getter s. Provide function interface to set and get data. - Function functions: for example, overloaded multiplication operators and fast power functions are all function functions. Property abstraction of object: - Whether the data and behavior are external or not. The significance of encapsulating data externally is to prevent the destruction of the object behavior description. A behavior that is open to the outside world usually requires repeated calls from multiple internal functions. At this time, the public and private keywords need to be used for modification. - Whether the data and behavior can be inherited. For some behaviors (functions), we don't want to be called externally, but it is very useful for subclasses. At this time, we can use the protect keyword to modify them. - Whether the data and behavior can be reused. In order to save unnecessary memory overhead, general functions that do not need to generate specific objects can be designed and modified with the static keyword. This can avoid that I have to apply for a piece of irrelevant memory space before I want to use a function, and the data of an object can also be modified with static, In this way, the data does not need to be applied and assigned during the creation of the object. Next, let's determine the properties of the behavior (function). The data must not be private, otherwise object-oriented will be meaningless. - Constructors and destructors are the key to the creation and destruction of objects, so if you don't want objects not to be created or destroyed, you should use public decoration. - Setters and getter s. Obviously, it is an open interface function, so it must also be a public modification. - Function function: matrix fast power function. Obviously, we want to set a general-purpose case. At this time, it should be called without creating an object, so it's best to modify it with static (this is generally an external general-purpose interface, and a convenient class calling version needs to be implemented internally, which is also very simple. Just call the function by directly passing parameters), Overloaded multiplication must also be external, so it needs public modification. The destroy function is used to deal with memory recycling. Obviously, this is an internal general function, but the outside world doesn't need it at all! So set it to the private property. The above is the design idea of the whole class. Of course, when you really design, you also need to be specific to the function parameters and return value types, because this involves the specific syntax of C + +. For example, what type should I return when overloading multiplication? It is best to return an R-value! The overloaded assignment operator is better to return an lvalue. Generally, when considering the choice of return value type, the most difficult thing is whether I should return an l-value or an R-value if I return an object. After writing C + + for so long, I feel that the feature of Java shielding overloaded operators written in C + + is that there are too many processes to consider when overloading operators. C + + chicken (I'm a rookie) 😂) Write extremely inefficient and unsafe code, and only old birds can write elegant and efficient code. Concrete abstract structure of class (concrete planning diagram of code) Each part of the class is classified according to attributes. After all, attributes basically represent the usage scenario of this method. - Finally, basic assertions or exceptions can be used to make the code more robust, making it easier to locate the location and cause of the error. Implementation matrix generic template class Source code implementation I first draw a plan for implementation, and then in the process of implementation, I find that some features can be added, such as overloading the subscript operator, such as printing it with the print function for verification. In the specific implementation process, in order to easily locate possible errors, a large number of assertions are used for assertion checking. If you want to make the code more robust, you can use the method of throwing exceptions. GitHub warehouse address corresponding to source code: Warehouse link, and the implementation of more templates, including a small amount of STL Better source code reading experience: Source code online reading It is not easy to read the following code directly. It is recommended to check the source code in GitHub1s above. // // Created by L_B__ on 2021/11/20. // #ifndef LQTEST_MATRIX_H #define LQTEST_MATRIX_H #include <cassert> #include <algorithm> #include <iostream> #define _MOD template<typename T> class Matrix { /*Type define*/ typedef T data_t; typedef int ssize_t; /*data source*/ data_t **data; ssize_t n; ssize_t m; public: static const data_t MOD; public: /*default construct*/ Matrix() : m(0), n(0), data(nullptr) {} /*custom construct*/ Matrix(data_t **mat, ssize_t n, ssize_t m) : data(mat), n(n), m(m) {}//External request memory passed into internal Matrix(ssize_t n, ssize_t m) : data(nullptr), n(n), m(m) {//You can specify the rows and columns of the matrix externally, and the memory initialization is performed internally assert(n > 0 && m > 0); data = new data_t *[n]; for (int i = 0; i < n; i++) { data[i] = new data_t[m]; } init(data, n, m); } /*copy construct*/ Matrix(Matrix &src) : data(nullptr), n(src.n), m(src.m)//Const & reference type can also be used, but in this way, many right value cases will not call the move construct { assert(n > 0 && m > 0); data = new data_t *[n]; for (int i = 0; i < n; ++i) { data[i] = new data_t[m]; std::copy(src.data[i], src.data[i] + m, data[i]); } } /*move construct*/ Matrix(Matrix<data_t> &&src) : n(src.n), m(src.m), data(nullptr) { assert(src.data != nullptr && n > 0 && m > 0); data = src.data; src.data = nullptr; src.n = src.m = 0; } /*destruct*/ ~Matrix() { destroy(); } /*overload*/ //Plus a special version of MOD #ifdef ]) % MOD; } tmp[i][j] = sum; } } //Directly construct anonymous object return return Matrix(tmp, n, src]) % MOD; } #ifndef ]; } tmp[i][j] = sum; } } //Directly construct anonymous object return return Matrix (tmp,n,src.m); } /*The only difference from multiplication is that multiplication constructs a new object, while * = returns //The overload of assignment number needs to separate the left and right values to achieve copy: the deep is the deep, and the shallow is the shallow Matrix &operator=(Matrix &src)//If the right is an lvalue, a deep copy (without copying the pointer) is required { assert(src.data != nullptr && src.n > 0 && src.m > 0); destroy();//Clear memory before copying n = src.n; m = src.m; data = new data_t *[n]; for (int i = 0; i < n; ++i) { assert(data[i] != nullptr);//In fact, it is not necessary, because the bad_alloc exception will be thrown if the new application fails data[i] = new data_t[m]; std::copy(src.data[i], src.data[i] + m, data[i]); } return *this; } Matrix &operator=(Matrix &&src)//If the right is an R-value, a shallow copy is made { assert(src.data != nullptr && src.n > 0 && src.m > 0); destroy();//Clear memory before copying n = src.n; m = src.m; data = src.data; src.data = nullptr; src.n = src.m = 0; return *this; } data_t *&operator[](ssize_t i) { assert(i >= 0 && i < n); return data[i]; } /*Fast implementation, object-oriented interface*/ void quickPow(data_t c) { QPow(*this, c); } /*setter And getter implementation*/ void set(ssize_t x, ssize_t y, data_t src) { assert(x >= 0 && x < n && y >= 0 && y < m); data[x][y] = src; } data_t &get(ssize_t x, ssize_t y) { //Return a reference, which can be modified directly in the outside world. Of course, the outside world should also use a reference to catch it, otherwise it is just a copy assert(x >= 0 && x < n && y >= 0 && y < m); return data[x][y]; } void print() { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { std::cout << data[i][j] << ' '; } std::cout << std::endl; } } public: static void init(data_t **data, ssize_t n, ssize_t m) { assert(data != nullptr && n > 0 && m > 0); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (i == j)data[i][j] = 1; else data[i][j] = 0; } } } static void QPow(Matrix &_Dest, data_t n) { assert(n >= 0); Matrix tmp(_Dest);//Make a copy for multiplication init(_Dest.data, _Dest.n, _Dest.m);//Initialize to identity matrix if (n == 0) return; while (n) { if (n & 1) { _Dest *= tmp; } tmp *= tmp; n >>= 1; } } private: void destroy() { if (data == nullptr) return; for (int i = 0; i < n; i++) { if (data[i] == nullptr)//If there is nullptr in this memory, it indicates that it has been delete d before return; delete[] data[i]; data[i] = nullptr; } delete[] data; data = nullptr; } }; #endif //LQTEST_MATRIX_H usage method - Instructions for use: two sets of multiplication codes are implemented internally through macro definition. One set does not take the module of MOD, and the other is to take the module, but the initial value of MOD must be assigned externally first. End use example: We only need to care about two points: 1. The construction and initialization of matrix class 2. The use of basic member functions 1, Construction and initialization of matrix class Because it is a template class, you need to specify the type of template #include "Matrix.h" //The dataType below is the data type of each element of the matrix you need, which you need to pass in yourself int main(){ Matrix<dataType> a;//Default Constructor Matrix<dataType> b(3,3);//Get the matrix with three rows and three columns. The default is the identity matrix int** ret = new ...//Omitted here, in short, is to apply for two-dimensional memory Matrix<dataType> c(ret,m,n);//The outside world applies for memory and assigns an initial value, and then initializes the class Matrix<dataType> d(c);or Matrix d = c;//Initializing d objects with existing classes (creating new memory) Matrix<dataType> e(c*d);or Matrix e = c*d;//Initialization through temporary objects (no new memory is created) } Corresponding source code: 2, Use of basic member functions Of course, multiplication has been overloaded, so as long as the two matrices can be multiplied, the result can be obtained directly. #include "Matrix.h" int main(){ //Initialize a matrix as {{1,1}, {1,0} Matrix<long long > a(2,2); a[0][0] = a[1][0] = a[0][1] = 1; a[1][2]; int c; cin>>c; //Call the fast power to update the data of the matrix to the power of c a.quickPow(c); a[0][0];or a.get(0,0);//An element that can access the (0,0) position of a a.print() //Print out the current value of the matrix //For example, a is now {1,1} {1,0} // Print: //1 1 //1 0 } If you want to get the fast power result of modular MOD, you need to add a macro definition _modin front of the Matrix file, and then use it as follows: #include "Matrix.h" template<> const long long Matrix<long long>::MOD = 1e9+7;//Initialize the value of MOD int main(){ Matrix<long long > a(2,2); a[0][0] = a[1][0] = a[0][1] = 1; a[1][2]; Matrix<long long> b(2,1); b[0][0] = b[1][0] = 1; long long c; std::cin>>c; a.quickPow(c-1); b = a*b; std::cout<<b[0][0]; } Corresponding source code: MOD version: Non MOD version: k fast power realization: 3, Problem solving verification - Because lanqiao network does not support C++11, I directly input test cases locally for testing. First measure a simple: The following measurements were made: A little bigger (it should be the limit of long long) Still stable for about 1ms!!!! I can only say two words: excellent! summary Because it is a template class implemented with the syntax of C++11, compilers lower than this version cannot be used normally. I consulted relevant materials. In fact, C++11 can be used in the Blue Bridge Cup, and acm needless to say, C++11 can be used long ago. Simple redo: To implement such a class, you can mainly learn the following points: - Class design skills. - Have a deeper understanding of the left and right values of C + +. - The design and implementation of various constructors have reached the level of perfection.
https://programmer.group/6199627f85700.html
CC-MAIN-2021-49
refinedweb
4,457
58.52
Have you ever viewed the page source for a web page while loading components asynchronously? If you have, there’s a possibility you may have noticed the actual content is not being rendered. This is because the components are being loaded asynchronously and on the client side, which can be bad for SEO because crawlers will be unable to get the actual content when indexing the site. This article will provide a method with which you can get the best of both worlds by using loadable-components to asynchronously load components. We’ll be working with an existing Gatsby project in this article. The project already uses the loadable component, and we’ll see how to implement it better for SEO purposes. Problem statement We have a Gatsby site that uses dynamic data from Contentful, a content management system to render information and modules. The Gatsby site is a blog that shows all the posts from Contentful. The posts are written in a rich text editor, and we use a rich text renderer in the codebase to parse rich text to React components. However, we’d also like to be able to display other things apart from blog posts on the site. To that end, we created a new content type in Contentful: custom blocks . A custom block, as the name suggests, would allow us to render custom blocks (content that is not necessarily a blog post) on the website. This is where the challenge lies. As opposed to blog posts, which are always rendered in article format, custom blocks may need to be rendered by different and multiple React components depending on design. For example, there’s a React component for a pricing information custom block on Contentful, a React component for an FAQ custom block on Contentful, etc. So, to implement that, there’s a file below that uses the custom block’s name to render its own component — i.e., if the custom block’s name matches any of the keys in CUSTOM_BLOCKS, then the corresponding component will be rendered. // blocks.js import TestPage from './TestPage' import PricingInfo from './PricingInfo' import FAQInfo from './FAQInfo' const CUSTOM_BLOCKS = { TestPage: TestPage, PricingInfo: PricingInfo, FAQInfo: FAQInfo, } export default CUSTOM_BLOCKS The custom blocks can then be used in a code snippet like the one below, where the CustomBlockComponent is only returned if there’s a corresponding match with customBlock.name. // CustomBlock.js import CUSTOM_BLOCKS from './blocks' const CustomBlock = ({ customBlock }) => { const CustomBlockComponent = CUSTOM_BLOCKS[customBlock.name] if (!CustomBlockComponent) { return null } return <CustomBlockComponent customBlock={customBlock} /> } export default CustomBlock With this current implementation, we’re loading all the custom blocks and their components all at once, even though we don’t need them. Right now, it’s just two custom blocks, but imagine if it were a whole lot more than that. Using loadable-components A case like this is where loadable/component comes in. It allows us to only load the components when they are needed, i.e., asynchronously. Let’s add loadable/component to the first code snippet shared above. // blocks.js import loadable from '@loadable/component' const CUSTOM_BLOCKS = { TestPage: loadable(() => import('./TestPage')), PricingInfo: loadable(() => import('./PricingInfo')), FAQInfo: loadable(() => import('./FAQInfo')), } export default CUSTOM_BLOCKS All the custom blocks are being loaded asynchronously, so they’ll only be loaded when needed, which in turn results in the code being optimized for performance. This is the reason why we have chosen to use loadable-components in our project, and it seems to solve the problem we initially had. However, importing the components with loadable means the content of the custom block will not be pre-rendered into the static HTML. As an example, in the page source below, I’m expecting the Date One text to be in the source, but it’s not. The Date One text is inside one of the custom block files above, and it needs some JavaScript to be evaluated, hence, it’s not showing up. This is what we’ll try to solve in this article: how to load the components asynchronously and also make sure that content gets rendered in the static HTML. Configuring loadable-components We can solve this by making some additional configurations to how loadable/component is set up. We already have loadable/component installed in the codebase, but we need to make some configurations. First, install the dependencies below. yarn add -D @loadable/babel-plugin @loadable/webpack-plugin babel-preset-gatsby The next thing is to add a custom Babel plugin to the project. To do that, we’ll need to modify the .babelrc.js file. In the plugins array, add the line below: // .babelrc.js { "plugins": [ ... "@loadable/babel-plugin", ... ] } Next, we’ll add a custom webpack plugin to the gatsby-node.js file. // gatsby-node.js const LoadablePlugin = require('@loadable/webpack-plugin') exports.onCreateWebpackConfig = ({ stage, actions }) => { actions.setWebpackConfig({ plugins: [new LoadablePlugin()], }) } exports.onCreateBabelConfig = ({ actions }) => { actions.setBabelPlugin({ name: `@loadable/babel-plugin`, }) } The final step in all of this is making sure that the content of the custom block is pre-rendered with the static HTML. One way to do that is by using the fallback prop of loadable/components. Pre-rendering custom block elements in static HTML The fallback prop determines what to show while the component is being loaded asynchronously. This is what will be used to make sure asynchronous components get rendered to the static HTML. How? So, for asynchronous components, the following happens: - Static HTML is rendered - React components are hydrated into the static HTML - Because of the asynchronous components taking time to resolve, the current DOM is destroyed and only created again when it’s done loading We can then take advantage of step two to get and save the current static HTML and then use that as a fallback. That’s exactly what’s being done in the code snippet below. If you recall above, the CustomBlock.js file simply checks whether a custom block component exists and then returns it. Now it’s doing a whole more than that: - Setting an idto CustomBlock__, plus whatever the current custom block name is - Adding a fallback prop, which is set to be HTML gotten from the getRenderedContent()function - Lastly, the getRenderedContentfunction checks whether an element with an ID exists in the HTML and, if yes, returns it // CustomBlock.js import * as React from 'react' import CUSTOM_BLOCKS from './blocks'</p> <p>const getRenderedContent = customBlockName => { if (typeof window === 'undefined') return '' const element = window.document.querySelector( <code>#CustomBlock__${customBlockName}</code> ) return element ? element.innerHTML : '' } const CustomBlock = ({ customBlock }) => { const CustomBlockComponent = CUSTOM_BLOCKS[customBlock.name] if (!CustomBlockComponent) { return null } return ( <section id={<code>CustomBlock__${customBlock.name}</code>}> <CustomBlockComponent customBlock={customBlock} fallback={ <div dangerouslySetInnerHTML={{ __html: getRenderedContent(customBlock.name), }} /> } /> </section> ) } export default CustomBlock It’s a bit of a hack, but then we get to see the content of the asynchronous components in the page source, and that’s good for SEO. Now we can build the site and run it in production with the commands below: yarn build && serve public The dates are now coming up in the page source, which means the custom block elements are now being pre-rendered which in turn means crawlers can successfully crawl this page. Conclusion To simulate what I’ve explained in this article, there’s a GitHub repository that contains the codebase for the Gatsby project above. It also contains an exported Contentful space so you can set that up (by importing into a new space) and connect to the Gatsby project..
http://blog.logrocket.com/seo-approach-async-loadable-components/
CC-MAIN-2020-40
refinedweb
1,242
54.12
SessionId obtained when running FacesRequest test is nullAndy Torble Apr 3, 2009 8:24 PM Hi All, I have a test that exercises some code in a session scoped bean that does some manipulation based on the logged in user's sessionId. The snippet of code being tested looks like this: ExternalContext externalContext = facesContext.getExternalContext(); HttpSession _session = (HttpSession)externalContext.getSession(true; where facesContext is injected. When the app is run in JBoss this returns a sensible value but when I call the action method from a test class (invokeApplication() from within a FacesRequest instance running in jboss-embedded) it always returns null which breaks my test. Can anyone suggest how I might resolve this? TIA seam 2.0.2 SP1 Andy 1. Re: SessionId obtained when running FacesRequest test is nullMarcio Endo Apr 3, 2009 9:53 PM (in response to Andy Torble) I assume you are trying to inject org.jboss.seam.faces.FacesContext, correct? Check your logs and see if it is getting installed. Otherwise I'd suspect your missing some jars in your test classpath, most probably jsf-api.jar. 2. Re: SessionId obtained when running FacesRequest test is nullAndy Torble Apr 6, 2009 4:30 PM (in response to Andy Torble) Correct on both counts. For the possible benefit of others this is what I did in the end. A bit of digging around revealed that the HttpSession being served by SeamTest was a mock object that always returned null for getId(). So I decided to create a Seam component named httpSession in SESSION scope and used that in my app to replace the code to derive the session id from the facesContext component. The class itself is just a thin wrapper round a 'real' HttpSession @Name("httpSession") @Scope(SESSION) @Install(precedence = APPLICATION) @Startup @BypassInterceptors public class Session { @Unwrap public javax.servlet.http.HttpSession getSession() { return (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); } } I also created a MockHttpSession class in the src/test area that replaces the above component during testing and provides my code with a mock sessionId. @Name("httpSession") @Scope(SESSION) @Install(precedence = APPLICATION) @Startup @BypassInterceptors public class MockSession extends MockHttpSession { private static final String chars = "0123456789abcdefghijklmnopqrstuvwxyz"; public MockSession() { super(null); } @Override public String getId() { StringBuffer sb = new StringBuffer(20); Random rand = new Random(); for (int i = 0; i < 20; i++) { sb.append(chars.charAt(rand.nextInt(35); } return sb.toString(); } } Works like a dream :-) 3. Re: SessionId obtained when running FacesRequest test is nullAndy Torble Apr 6, 2009 4:33 PM (in response to Andy Torble) Oops! Slight cut n paste typo there. The precedence of MockSession should of course be MOCK.
https://developer.jboss.org/thread/187136
CC-MAIN-2018-17
refinedweb
438
54.73
Closed Bug 982797 Opened 9 years ago Closed 8 years ago Robocop: Switch tests from using wait For Test to wait For Condition Categories (Firefox for Android Graveyard :: Testing, defect) Tracking (firefox38 fixed) Firefox 38 People (Reporter: liuche, Assigned: AndyP, Mentored) Details (Whiteboard: [lang=java][good first bug]) Attachments (1 file, 4 obsolete files) Robotium 4.2 added Conditions, and we should replace all instances of waitForTest with waitForCondition. Assignee: nobody → mozbugs.retornam Mentor: liuche Whiteboard: [mentor=liuche][lang=java] → [lang=java] Reset assignee due to inactivity. Assignee: mozbugs.retornam → nobody And a list of all instances of `waitforTest(`:^[^\0]*%24&hitlimit=&tree=mozilla-central Whiteboard: [lang=java] → [lang=java][good first bug] Hi. I'd like to confirm that the only change you'd like performed is to change the method from waitForTest to waitForCondition, right? Are the parameters the same? If so, I believe I can have a patch submitted shortly. I replaced all instances of waitForTest (at^[^\0]*%24&hitlimit=&tree=mozilla-central) with waitForCondition. Please let me know if this is sufficient. Comment on attachment 8516110 [details] [diff] [review] waitForCondition.patch Review of attachment 8516110 [details] [diff] [review]: ----------------------------------------------------------------- Hi David! Thanks for picking up this bug! Taking a quick glance, I see a few big changes you should make to this patch before it's ready for review. Take a look at the waitForCondition method in BaseTest.java - it's right before BooleanTest and waitForTest. The signature is not in fact the same as waitForTest, so you'll need to change that as well. If you want to do a partial build with this patch to catch compile errors, you can just build the tests with: mach build $TOP_SRC_DIR/build/mobile/robocop where TOP_SRC_DIR is your code directory. Clearing review flag for these changes - this needs a little more work. ::: mobile/android/base/tests/BaseTest.java @@ +330,5 @@ > } > > // TODO: With Robotium 4.2, we should use Condition and waitForCondition instead. > // Future boolean tests should not use this method. > + protected final boolean waitForCondition(BooleanTest t, int timeout) { You should remove this instance of waitForTest completely, because this bug is for switching calls of the deprecated waitForTest to the new waitForConditon call. In fact, if waitForTest is the only consumer of BooleanTest, you can remove that too! :) I see that this is more complicated than I thought. So it looks like, as you said, the method that switches calls of waitForTest to waitForCondition and BooleanTest can be deleted. Since waitForCondition uses conditions instead of booleantests, this means that the parameters for the new method calls needs to be different. Could you please advise on how to handle situations in which the condition parameter is given an overridden method, such as in this example: boolean correctText = waitForTest(new BooleanTest() { @Override public boolean test() { final String clipboardText = Clipboard.getText(); mAsserter.dumpLog("Clipboard text = " + clipboardText + " , expected text = " + copiedText); return clipboardText.contains(copiedText); } }, MAX_TEST_TIMEOUT); I'm having trouble finding the declaration of Condition. Can I just leave the "public boolean test()" as it is, or does it need to be replaced with something? Flags: needinfo?(liuche) I'd like to add on to the last question, would it be enough to replace "public boolean test()" with "public boolean isSatisfied()" and leave the definition unchanged? Condition is part of the Robotium framework, so it wouldn't actually be in our code base. Here's the link to the Robotium API: (this is not exactly the version that we're using, but the API is the same) So yes, you are correct! You can just switch the test() method to isSatisfied() when you replace waitForTest(). Assignee: nobody → lubin.davidg Status: NEW → ASSIGNED Flags: needinfo?(liuche) I believe this patch handles the changes discussed. Please let me know what you think. Attachment #8516110 - Attachment is obsolete: true Comment on attachment 8516373 [details] [diff] [review] waitForConditionV2.patch Review of attachment 8516373 [details] [diff] [review]: ----------------------------------------------------------------- Hi David, thanks for the patch. You're pretty close! A few more things: I would recommend applying your patches to your local copy of the tree and at least building successfully before requesting review. For the files that now use Condition instead of BooleanTest, you'll also need to import Condition so that the patch will build. (As a side note, you should pull your tree again because there's a little bitrot from bug 1092254 having landed, so the patch isn't applying cleanly for me.) If you have already built Fennec, you can do a partial build by running: mach build build/mobile/robocop from the top directory of the source tree. This should only take a minute! If you haven't built Fennec, take a look at . The rest of that wiki is also a good place to make sure you have everything set up. If you need help, feel free to jump into #mobile and ask! I and other members of the mobile team are around during PST work hours, and are happy to help. Thanks for your help so far. I pulled the latest changes and fixed the patch so that it would apply properly. This latest patch includes Condition imports for the files that did not previously have it, but I'm not sure whether or not build is currently working, so I just flagged for feedback. When building, both with and without the patch, I'm receiving a message saying "For some reason, Clobber had problems applying the changes for Android in Bug 1091118," and it seems to be failing. Do you have any idea why I might be having this issue, even without any patches on my Mercurial queue? Attachment #8516373 - Attachment is obsolete: true Hi David, I'm not sure what this problem is - can you drop the relevant part of your log into pastebin? Also, make sure you've got all the build dependencies from . Again, I encourage you to drop into #mobile on Mozilla IRC (connect to irc.mozilla.org) - it will definitely be easier to debug this problem, and there are more people there who might have run into this problem. Comment on attachment 8516410 [details] [diff] [review] waitForConditionV3.patch Clearing the feedback flag until we figure out the building problems. In general, before uploading a patch, you should always make sure it is building and try to verify that the changes that you have made are working as expected. Otherwise, it doesn't really make sense for someone else to review or give feedback on the patch because it'll have to change anyways. Take a look at the instructions at for setting up a build again, and make sure you've done all the steps - this should get you to a working build of the tree. Assignee: lubin.davidg → nobody I'd like to work on this bug, could someone assign me please? Andy: just get started! We can mark it as assigned when you've got a patch underway. Status: ASSIGNED → NEW Component: General → Testing Hardware: ARM → All I've successfully built, installed and run Fennec with these changes. No further testing done. I forgot to mark the old patch as obsolete, sorry. Is there a way to change that? The problem with the old patch was possibly because David forgot the two methods in testFindInPage.java. Probably because the link in comment #2 did not include the file because the waitForTest methods there had a space before the "(". Thanks for the patch, Andy! Since you're fixing a test file, building and running Fennec won't reflect the changes you've made, unless you run the tests locally. We have instructions for running tests locally, but sometimes they can be flaky :/ In the meantime, I've pushed to our Try server for you (which will run our tests), so we'll see how those tests run. If you end up working on more tests, we can definitely give you push access to the try server. :) You can mark an attachment "obsolete" by clicking on the "Details" link, and then clicking "edit details" next to the patch name; there is a checkbox for "obsolete". (You can also un-obsolete patches that way.) Thanks for your work, Andy! I forgot to mention: if you want to try compiling the tests, you can run |mach build build/mobile/robocop|, which builds our robocop tests. Good news, your changes to the tests do in fact compile :) Assignee: nobody → drag Attachment #8562731 - Attachment is obsolete: true Attachment #8562731 - Attachment is obsolete: false Comment on attachment 8562731 [details] [diff] [review] bug982797_waitForTestReplacement.diff Review of attachment 8562731 [details] [diff] [review]: ----------------------------------------------------------------- Great job, just a couple of nits! Once you change that, upload a new patch, obsolete the old ones, and I'll r+ the new patch (or you can move the r+ to that patch). The commit message should also match the name of the bug and include the reviewer, so for this bug: Bug 982797 - Robocop: Switch tests from using waitForTest to waitForCondition. r=liuche ::: mobile/android/base/tests/testFindInPage.java @@ +20,2 @@ > public class testFindInPage extends JavascriptTest implements GeckoEventListener { > private static final int WAIT_FOR_TEST = 3000; Nit: Let's rename this so it matches the methods better, and also specify the unit of time. WAIT_FOR_CONDITION_MS @@ +98,5 @@ > return false; > } > } > }, WAIT_FOR_TEST); > mSolo.sleep(500); // TODO: Find a better way to wait here because waitForTest is not enough One nit - this references waitForTest, which is now no longer in the code base. Will you update this to refer to waitForCondition? Attachment #8562731 - Flags: review?(liuche) → review+ I've made the changes as requested. For some reason I cannot mark the other patch obsolete though. Attachment #8562731 - Attachment is obsolete: true Attachment #8564223 - Flags: review?(liuche) Comment on attachment 8564223 [details] [diff] [review] bug982797_waitForTestReplacement.diff - v2 Review of attachment 8564223 [details] [diff] [review]: ----------------------------------------------------------------- Nice! Thanks Andy :) Attachment #8564223 - Flags: review?(liuche) → review+ Green try run from a few days ago, only comment and var changes since then: Flags: in-testsuite+ Status: NEW → RESOLVED Closed: 8 years ago status-firefox38: --- → fixed Resolution: --- → FIXED Target Milestone: --- → Firefox 38 Product: Firefox for Android → Firefox for Android Graveyard
https://bugzilla.mozilla.org/show_bug.cgi?id=982797
CC-MAIN-2022-40
refinedweb
1,680
63.59
How to do real Server Side Rendering with Vue 2 I have an semi-finished boilerplate using the techniques taught in this article you are welcome to use. Server side rendering in Vue is a little unclear for larger projects. Most of the examples I’ve seen require heavy use of webpack. I’m going to show a more Node driven approach. When the server renders the page it will just be a plain string without any vue functionality. That means if you try to navigate pages it will do a full page reload. So in order to get the benefits of both server side rendering and client side vue functionality like ajax routing you need to reboot the app client side after it’s rendered from the server. Just make sure your root vue component has the same root html as the index.html page like <div id="app"></div> Both the client rendered version and server rendered version must have exactly the same html or it will throw a hydration error (server and client html out of sync). The thing you have to be careful of is not all libraries will work server-side yet. For instance vue-material has direct references to the document or window that are not accessible server side and those components will not render on the server. Server side rendering can happen in 5 files. The index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimal-ui"> <title></title> <script> window.__INITIAL_STATE__= "init_state" </script> <link rel="stylesheet" href="/public/app/style.css"> </head> <body> <div id="app"></div> <script src="/public/app/app.js"></script> </body> </html> The unique parts to note here is we have an <div id="app"></div> We will boot our root instance from this element both server side and client side. The other unique thing to note is <script> window.__INITIAL_STATE__= "init_state" </script> The server side rendering will likely make changes to our centeralized store (I’m using Vue-Stash). We will save the updated state of the store to this __INITIAL_STATE__ variable so the client can load from it if it’s set. One other note of interest is I have webpack separate the style.css and app.js. Since the html is already loaded from the server if the styles aren’t loaded till the bottom of the page it will flicker and temporarily show an un-styled page. Express routes file - Use webpack to compile a renderer file. (This will import your main .vue component, router, and store. It needs webpack to handle the .vue files.) It any of your links import stylesheets they will be ignored, but you still need the appropriate webpack loader for each new file type. You can’t use any imports that have direct access to the window or document properties. - Import vue-server-renderer and use `createBundleRenderer()` passing in your compiled renderer file and caching options - Run renderToString({ url: req.url }) from the bundleRenderer created passing in an object with a url. It needs to be an object so the renderer can attach the store changes to it. - Read the index.html page with fs and .replace() the #app element with the rendered html. - Replace the window.__INITIAL_STATE__= “init_state” with our store state. const isProd = process.env.NODE_ENV === 'production' const path = require('path'); const fs = require('fs'); const express = require('express'); const app = express();const serverRenderer = require('vue-server-renderer') //load the index.html const indexHTML = fs.readFileSync(path.join('public', 'index.html'), 'utf8') //if we are in production mode set a 15 minute cache const options = isProd? { cache: require('lru-cache')({ max: 1000, maxAge: 1000 * 60 * 15 }) }: undefined app.get('/*', (req, res) => { //Normally we would read this file outside of the route but if we are in development we want to dynamically load changes const filePath = path.join( 'lib', 'renderer.js' ); const code = fs.readFileSync(filePath, 'utf8'); const renderer = serverRenderer.createBundleRenderer(code, options); //we pass in req.url for vue-router. The renderer will attach the updated store state to this object var context = { url: req.url } //Render the html string renderer.renderToString(context, (err, html) => { if (err) { console.log('Error rendering to string: '); console.log(err); console.log(err.message); return res.status(200).send('Server Error'); } html = indexHTML.replace('<div id="app"></div>', html); //we will set context.initialState with the renderer const newStoreState = JSON.stringify(context.initialState) //I have a script in my index page called //<script> window.__INITIAL_STATE__= "init_state" </script> //So I replace init_state with our updated store html = html.replace('"init_state"', newStoreState); return res.status(200).send(html); }) }) app.listen(3000, function () { console.log('Example app listening on port 3000!') }) The Renderer File The renderer file must export a function that returns the root vue component. It can do this as a promise. However if you are using Vue-Router it’s likely you won’t want to render just the root component but any sub-views for the provided route. So if someone visits /about you want to load the component associated within the /about route. You do this with router.push('/about') But we can use the req.url we passed in with the context. Wait for beforeCreate and created lifecycle hook promises to resolve If we have some ajax requests that we want to run before we load the page we can put those in the beforeCreate and created lifecycle hooks in our Vue component and wait for those to finish rendering before resolving the main app component. Make sure you are using an isomorphic (works on both server and client) ajax library like isomorphic fetch or axios. I recommend axios because it has a unit test mocker library. //app is our root vue component //router is the instance of VueRouter import { app, router, store } from '../app/boot' export default function(context) { //Load the correct router view server side router.push(context.url) // Get the components belonging to that view let matchedComponents = routing.getMatchedComponents() // no matched routes if (!matchedComponents.length) { return Promise.reject({ code: '404' }) } // We wait for the "beforeCreate" and "created" hooks to finish their promises before rendering. You can run an isomorphic ajax library such as axios or isomorphic-fetch in it. It should be a function that returns a promise and when it resolves it will render the html. This allows you to fetch all your ajax data before the html is sent. The store is attached to this and passed in as the first parameter as well return Promise.all(matchedComponents.map(async component => { if (component.beforeCreate) { try { //I'm passing in the store as the this context await component.beforeCreate.apply(store, store) } catch(err) {} } if(component.created) { try { //I'm passing in the store as the this context await component.created.apply(store, store) } catch(err) {} } })).then(() => { context.initialState = store return app }) }; Store Reconciliation The server may have made changes to the store before rendering the initial html. We will write those changes to window.__INITIAL_STATE__. We need to set out local store to be the same as the server so vue does not throw an hydration error. // The server may have made changes to the store before rendering the initial html. It writes those changes to window.__INITIAL_STATE__. We need to set out local store to be the same as the server so vue does not throw an hydration error (server and client html out of sync) import Vue from 'vue' import VueStash from 'vue-stash' //defaultStore is a plain object imported from another file import defaultStore from '../store' Vue.use(VueStash) let store = defaultStore try { if(window && window.__INITIAL_STATE__ && window.__INITIAL_STATE__ !== "init_state") { store = window.__INITIAL_STATE__ } } catch(err) {} export default store Webpack Our webpack file should compile the renderer using the .vue loader. { target: 'node', entry: path.resolve(__dirname, 'src', 'renderer.js'), output: { libraryTarget: 'commonjs2', path: path.resolve(__dirname, 'lib'), filename: 'renderer.js' }, loaders : [ { test: /\.vue$/, loader: 'vue', exclude: /node_modules/, } ] } Reboot Client Side We will have some specific libraries that we only want to load client side and not server side such as authentication, toastr notifications, styles and css, jQuery, etc… We will have a separate file that will be a script in the index.html page that when loaded will reboot the app from the <div id="app"></div> dom using the same root component. Your root Vue component should have #app at the top of it’s template. <div id="app"> <navigation></navigation> <heading></heading> <div class="container"> <router-view></router-view> </div> <foot></foot> </div> This might take a while to wrap your head around but I will be releasing a boilerplate in the future. Please ask questions so I can make this tutorial more clear.
https://medium.com/@codingfriend/how-to-do-real-server-side-rendering-with-vue-2-5ec6f0efd041
CC-MAIN-2018-09
refinedweb
1,457
58.89
A brief introduction to the Simpson’s 1/3rd rule and a uniform interval Composite Simpson’s 1/3rd Rule implementation. Simpson’s 1/3rd Rule The Simpson’s 1/3 rule is a numerical method to find the integral within some finite limits and . Simpson’s 1/3rd rule approximates with a polynomial of degree two , ie. a parabola between the two limits and , and then finds the integral of that bounded parabola, and is used to represent the approximate integral . The integral of the approximated function is the area under the parabola bounded by the points and and by the positive side of the x axis. The quadratic function has three points common to the function , which are as follows: The end points of the approximate quadratic function is the same as the function at , . And takes the same value of the function at point . Thus three points are fixed each in equal interval and a parabola is drawn through these three points and the area under the parabola through these points bounded by and and the positive side of the X axis is found, which is used as the approximated integral value. The below iterative formula an be used to find the integral of a function using Simpson’s 1/3rd rule. The above formula approximates with only one parabola. To represent the function more accurately with with method, the function is divided in many intervals say having same width say , such that and then a parabola is fit within each of the intervals to approximate the integrals of the function within those intervals. The evaluation of the integral within each such interval using the above single interval iterative formula is used to find the overall evaluation of the integral within the limits and . This is known as the Simpson’s 1/3rd Composite Rule. The iterative method for the Simpson’s 1/3rd Composite Rule can be found by repetitively applying the single interval formula in each intervals, and is found to be: The Process The Simpson’s Composite Rule function will calculate the first and the last ordinate separately and also calculate and sum up the odd and the even ordinates separately for better clarity, and at last the Simpson’s Composite Rule iterative formula would be used directly. For demonstration purpose some sample functions are used: FUNCTION simpson_13(f, a, b, n) Find width of each interval h = (b-a)/n Find y0 = f(a), yn = f(b) Initialize x = a+h, i = 1, sum = 0 Initialize even = 0, odd = 0 /* Calculate the sum of the even and odd ordinates from (x + h) to (x + (n-1)h) */ WHILE (i < n) DO IF i is even THEN even = even + f (x) ELSE IF i is odd THEN odd = odd + f(x) ENDIF x = x + h ENDWHILE /* Apply Simpson's 1/3rd Composite Formula to find the integral */ Is = (h/3* {y0 + yn + 2 * even + 4 * odd}) ENDFUNCTION Sourcecode #include <stdio.h> #include <math.h> double f1 (double x); double f2 (double x); double simpson_13 (double (*f) (double x), double a, double b, int n); int main (void) { double a, b, n; double Is; printf ("\nEnter a,b,n: "); scanf ("%lf %lf %lf", &a, &b, &n); printf ("\nf(x) = sin (2x) / (1+x)^5"); /* Show integral computed with simpson's 1/3 rd rule */ Is = simpson_13 (f1, a, b, n); printf ("\n\tI_Simpson_13rd (f(x), %g, %g, %g) = %g", a, b, n, Is); printf ("\n"); printf ("\nf(x) = (1/x) + 5 + 10x^2;"); /* Show integral computed with simpson's 1/3 rd rule */ Is = simpson_13 (f2, a, b, n); printf ("\n\tI_Simpson_13rd (f(x), %g, %g, %g) = %g", a, b, n, Is); simpson_13 (double (*f) (double x), double a, double b, int n) { double h; double y = 0, x, even = 0, odd = 0, y0, yn; int i; h = (b - a) / n; y0 = f (a); yn = f (b); for (i = 1, x = a + h; i < n; x = x + h, i++) { if (i % 2 == 0) even = even + f (x); else odd = odd + f (x); } y = (h / 3) * ((y0 + yn) + 2 * even + 4 * odd); return y; } double f1 (double x) { return sin (2 * x) / pow ((1 + x), 5); } simpson_13 (double (*f) (double x), double a, double b, int n) : This takes a pointer to a function pointer values of the passed function starting from up to ). The values of the function values for the odd interval number are summed in a separate variable odd, and the values for the even interval numbers are summed in another variable even. At the end of the interval the composite iterative Simpson’s formula is directly used to find the integral, and the value is returned: (h / 3) * ((y0 + yn) + 2 * even + 4 * odd); - int main (void) : The main function prompts the user to enter the upper and the lower limits and the number of intervals to be taken and calls the functions with the proper parameters. The simpson_13() is called as Is = simpson_13 (f1, a, b, n); which computes the integral of the function f1 within upper and lower limit a and b with the Simpson’s 1/3 rule. Error When is continuous and is the upper bound for the values of on , then Simpson’s 1/3rd is found to be: The magnitude of the Simpson’s rule error decreases as the the step size is decreased as the function is better approximated with the second degree equation. The Simpson’s 1/3rd = simpson_13 _Simpson_13rd (f(x), 1, 2, 10) = 0.00505831 f(x) = (1/x) + 5 + 10x^2; I_Simpson_13rd (f(x), 1, 2, 10) = 29.0265 Run 2: input = lower limit a = 5.3, upper limit b = 10.23, intervals n = 100 Enter a,b,n: 5.3 10.23 100 f(x) = sin (2x) / (1+x)^5 I_Simpson_13rd (f(x), 5.3, 10.23, 100) = -3.20359e-05 f(x) = (1/x) + 5 + 10x^2; I_Simpson_13rd (f(x), 5.3, 10.23, 100) = 3097.71 Links - Check for more: - - Trapezoidal Rule: References - Calculus and Analytic Geometry: Thomas Finney - Images from : Wikipedia 3 thoughts on “Simpson’s 1/3rd Rule” how do you apply composite simpsons 1/3 rule for double and triple integrals where h=(b-a)/(2n) and k=(d-c)/(2m) and J=(g-f)/(2p). “To represent the function more accurately with with method, the function is divided in many intervals say n having same width say h, such that h=\frac{(b-a)}{n} and then a parabola is fit within each of the n intervals to approximate the integrals of the function within those intervals.” A parabola is fit taking two successive intervals. So there are total n/2 elementary parabola.
https://phoxis.org/2011/03/11/simpson-13-rd-rule/?replytocom=23624
CC-MAIN-2020-10
refinedweb
1,119
58.05
Mixing ActiveX with Java Al Williams, a longtime Dobb's contributor and our resident tinkerer, has been making waves recently with his one-instruction CPU (you can click here to watch a video demo). Back in 2004, he was busy playing with robots and servos, and in this article from DDJ, he shows you how to use JACOB (a library for running Java code under Windows) to connect with ActiveX objects for robotic control. Mixing ActiveX with Java by Al Williams Mimicking Microsoft's JVM interface With the demise of Microsoft's JVM, Java programmers can't easily access ActiveX objects. Or can they? Although the Microsoft JVM is no more, the JACOB ("Java COm Bridge") open-source library essentially duplicates its ability to allow Java code running under Windows to connect with ActiveX objects. Many specialized libraries are only available as ActiveX (or COM) objects, so using them from Java is an important trick to have in your toolkit. I recently encountered this problem when trying to integrate a custom hardware board with a Java program. The custom board's interface expected to talk to an ActiveX DLL. Rather than rewrite the library in Java, I decided to interface the existing library to my Java code. There are several commercial solutions available, but I selected JACOB (written by Dan Adler and available at) because it closely mimics the Microsoft JVM's interface. This is both a strength and a weakness. The Microsoft JVM has plenty of documentation, so there are lots of examples and resources. The weakness is that the Microsoft JVM is disappearing, and JACOB depends on Microsoft documents for its primary documentation. However, there is an active user's group for people using JACOB, and the necessary files are available from the group. If you are a Java purist, you've probably already stopped reading. After all, mixing anything with Java-and Windows-specific code, in particular-is sure to flare tempers. However, politics aside, it is often necessary to interoperate with other software. Like it or not, there is a large body of ActiveX code out there and being able to call it from Java simply expands the number of projects you can do in Java instead of using some other language. Using JACOB To show how JACOB works, I wanted to control the robot in Figure 1 from a PC running a Java program. Figure 1. Admittedly, this robot isn't a commercial project, but I use it to demonstrate a board that controls servo motors from a PC. Like a lot of commercial devices, the robot's wheels are servo motors, and the board provides an ActiveX DLL that lets you control up to eight motors. (For more information, see the note at the end of this article entitled "Robots and Servos.") Of course, to be practical, the robot would need to carry a Java-enabled PC (maybe a PC/104 board) or have a wireless serial connection. However, for my purposes here, I simply kept the robot tethered to a long RS-232 cable. My goal was to build a command-line program that could issue instructions to the robot's drive motors. You could then use the program in a batch file or even add the class to a JavaScript Interpreter. Understanding ActiveX If you've worked at all with JavaBeans, you won't find ActiveX mysterious. At the lowest level, an ActiveX object is simply any piece of code that exposes one or more interfaces. These interfaces are tables of function pointers. So an object might publish an interface where the fifth function in the table causes the object to, say, generate a report. By itself, this provides encapsulation, but little else. The secret to ActiveX is that each interface contains at least three pointers (the first three, obviously) that perform the same function. In particular, these three functions make up the IUnknown interface. This shows one form of ActiveX polymorphism. By ignoring all but the first three functions of an interface, you can treat any interface as an IUnknown interface (just as you can treat any Java object as type Object). However, there is another, more common form of polymorphism used by ActiveX. One of the functions defined by IUnknown is QueryInterface. So suppose you are building a database for your local brick and mortar library. You have an object that exposes an imaginary IMedia interface. Because IMedia is a superset of IUnknown, you can call QueryInterface to discover if the object also has an IBook interface. If it does, then it must be a type of book. If it doesn't, then it isn't a book (perhaps it is a CD with an ICDRom interface). So by exploiting QueryInterface, you can treat a CD or a book as a type of media, which is, of course, polymorphism. This is ActiveX at the core level. If you are a C programmer, there isn't much more to it than this. There are many predefined interfaces you can provide (or use), but they all assume that you know which slot in the interface table has the function you want to use. For programming languages such as Visual Basic (a major user of ActiveX technology), this is too great of a restriction. Foreknowledge of the interface table amounts to early binding-the language tool has to know about the object you wish to access. So how can ActiveX perform late binding (where the runtime system resolves the function reference)? IDispatch The answer is through a specialized interface, IDispatch. This is a special interface that lets you refer to functions in an object via name or number. Because early binding is more efficient, some objects provide custom interfaces in addition to IDispatch. In fact, some objects provide dual interfaces that are IDispatch interface tables followed by custom functions. After all, programs expecting IDispatch will just ignore the extra functions. IDispatch provides for three main items: properties, methods, and events. As you might expect, properties are quasi-variables, while methods are simply function calls. An event is a way to register a function with an object. The object can then use the function to communicate with the original caller. For example, a button object might call a programmer-defined function when users press a button. ActiveX also supports many common data types. However, most variables used by IDispatch-implementing objects will be variants. This is very similar to an untyped Visual Basic variable. It can contain nearly anything (numbers, strings, dates, currency, object references, and even arrays). Most ActiveX objects of interest will provide IDispatch and work through various properties, methods, and events. JACOB allows you to very easily access these parts of an ActiveX object. If the object doesn't support IDispatch, you won't be able to use JACOB to access it. Using JACOB JACOB uses a special class to represent an IDispatch interface. The constructor for this class takes a string that is usually the ActiveX server's progid. This is simply a short name that identifies the server (for example, Microsoft Excel's progid is Excel.Application). If you want to use the classid (a 128-bit number that is unique for each server), you can provide it using an alternate syntax. There are several ways you can handle properties, methods, and events in JACOB (although events are handled a bit differently than in the original Microsoft JVM). In addition, JACOB provides classes to represent variants and other specialized ActiveX types. For example, consider accessing data from Excel, as in: ActiveXComponent xl = new ActiveXComponent("Excel.Application"); System.out.println("version="+xl.getProperty("Version")); xl.setProperty("Visible", new Variant(true)) You can also call static members of Dispatch to achieve the same effect. When you call a method, you must provide an array of Variant objects that represent the arguments. Here, for instance, is a call to the robot's servo controller board: servo.invoke("SetPosition", new Variant [] { new Variant(chan), new Variant(pos) }); There are also helper methods of the Dispatch class that take a varying number of arguments, if you prefer to use them. This, for instance, iant f = new Variant(false); Dispatch.call(workbook, "Close", f); is essentially the same as writing this: workbook.invoke("Close", new Variant [] { new Variant(false) }); You can find other syntax examples by reading the JACOB source or referring to the Microsoft documentation. A Java Wrapper The robot's servo controller board (a GP4;) has an ActiveX object that provides several methods and a property to set the active COM port. Obviously, it would be possible to just write the robot controller program to use the ActiveX object directly via JACOB. However, I will eventually write an actual Java object that interfaces with the board. With that in mind, I wrote a wrapper around the ActiveX object that simply provides the same methods and properties. Eventually, I'll replace this class with one that is pure Java and the remaining code will not require any changes. Listing One is the result. The constructor creates the ActiveX object (the progid is AWCGP4DLL.GP4DLL). Listing One /* Java wrapper for GP-4 ActiveX DLL. Requires: JACOB -- GP4 -- */ import com.jacob.com.*; import com.jacob.activeX.*; public class GP4 { private ActiveXComponent servo; // The COM object // Create ActiveX object public GP4() { servo=new ActiveXComponent("AWCGP4DLL.GP4DLL"); } // Reset servo controller public void reset() { servo.invoke("Reset",new Variant[] {} ); } // Set servo position public void setPosition(int chan, int pos) { servo.invoke("SetPosition", new Variant [] { new Variant(chan), new Variant(pos) }); } // Enable channel public void enableChannel(int chan, boolean enable) { servo.invoke("EnableChannel", new Variant[] { new Variant(chan), new Variant(enable) }); } // Turn groups of servos on/off public void setMask(int mask) { // Another way to do this // servo.invoke("SetMask", new Variant [] { new Variant(mask) }); Dispatch.call(servo,"SetMask",new Variant(mask)); } // Enable/disable all servos public void enable(boolean enflag) { servo.invoke("Enable", new Variant [] { new Variant(enflag) }); } // Set the COM port public void setComPort(int port) { servo.setProperty("Comport",new Variant(port)); } } Each method corresponds to a method or property in the original object. For variety, I commented out the invoke call in the setMask method and replaced it with a Dispatch object method that does the same function. Armed with this wrapper class, it is easy to use it to control the motors. Listing Two is a command-line program that does the job. Listing Two /* The robot driver */ public class ServoDrive { // General-purpose pause { try { Thread.sleep(ms); } catch (InterruptedException e) {} } // Convert a string into a speed number private static int setSpeed(String v,int defspeed) { int speed; try { speed=Integer.parseInt(v); // read integer } catch (Exception e) { speed=0; } if (speed==0) speed=defspeed; // or use default return speed; } // The main code public static void main(String[] args) { GP4 servos=new GP4(); // create a servo controller int servoA=7; // the wheels are on servo #7 and #6 int servoB=6; // read speeds int speedA=setSpeed(args.length>0?args[0]:"",25); int speedB=setSpeed(args.length>1?args[1]:"",-speedA); // set the COM port servos.setComPort(1); // Turn servos on servos.enable(true); // Set them to run servos.setPosition(servoA,speedA); servos.setPosition(servoB,speedB); pause(3000); // 3 seconds // disable all servos so they stop at once servos.setMask(0); // Reset both servos servos.setPosition(servoA,0); servos.setPosition(servoB,0); // And reenable them (although they are stopped now servos.setMask(0xFF); } } The program accepts one or two speed arguments (which can range from -50 to 50). If you provide one argument, the motors move the robot forward (or backward if you use a negative number) with a speed proportional to the magnitude of the argument. With two arguments, you can set the speed and direction of each wheel independently. In either case, the program runs the motors for about three seconds and then stops them. If you read the command-line program's source code, you'll notice that the code has no idea that the servo manipulation is being handled by ActiveX. All the JACOB code is restricted to the GP4 class in Listing One. Pros and Cons I could have rewritten the servo controller's library using javax.comm and handled it in native Java. I have no doubt that would be a better solution. After all, with the ActiveX component, the program only runs under Windows. With javax.comm, the program would operate with Linux, Macintosh, or Windows. However, rewriting the module would take time-time to rewrite it and also time to test it. In this case, I had the luxury of having the source code to the ActiveX components, but if it were from a third party, it might be even more difficult to reproduce. What's more is that changes from that third party could be difficult to incorporate. With a JACOB wrapper, it is fast and easy to incorporate the ActiveX code into a Windows-only Java program. Even if the ActiveX object added features later, it would be simple to either ignore them or add them to the wrapper with a minimum of effort. Politics aside, there are times when you need to absorb some ActiveX code. The unfortunate legal wrangling has made that more difficult than it used to be. But thanks to JACOB, it's only a little more difficult. Note: Robots and Servos The robot used in this article is a model of simplicity. The frame is made from Radio Shack perf boards and a small piece of bass wood (available from almost any hobby shop). The large wheels are also from a hobby shop and are made for model airplanes. A few angle braces and a small caster from Home Depot complete the mechanical construction. The two drive wheels are inexpensive servo motors made for radio-control vehicles. These make motor drive very simple. Each motor shaft connects internally to a potentiometer that controls a pulse-generating circuit. To move the motor, you send a pulse to it approximately every 20 ms. The motor generates its own pulse and compares the two pulses. Suppose the potentiometer in the motor (which is connected to the shaft) is set so that the internal circuit generates a 1-ms pulse. If you send a 1-ms pulse, the motor will not move. However, if you send, for example, a 1.2-ms pulse, the motor will move until the internal circuit is also generating a 1.2-ms pulse. Or, if you sent a 0.8-ms pulse, the motor would move in the opposite direction to make the internal pulse match the pulse you supply. Normally, these servos don't rotate. They simply move in an arc (useful for an airplane's control surface or a car's steering wheel, for example). However, it is possible to modify the servo so that its potentiometer is not connected to the shaft (you also have to remove the stops that prevent it from rotating through 360 degrees). If you adjust the potentiometer so that the servo generates a 1.5-ms pulse, you can easily control the motor. A 1.5-ms pulse makes the servo hold position. A shorter pulse makes the motor rotate in one direction and a longer pulse makes the motor rotate in the opposite direction. You can even control the speed of the motor by controlling the length of the input pulse. A 1.6-ms pulse makes the motor move more slowly than a 2-ms pulse because the motor perceives more error with a 2-ms pulse. Of course, with the potentiometer disconnected from the shaft, the motor can never correct the perceived error, so the motor just continues to turn as long as you keep supplying pulses. This is perfect for controlling a small robot. Since the two servos are mounted back to back, if you feed the same pulse to both motors, the robot will spin in place. That's because if you rotate both motors clockwise (for example), they will spin in opposite directions since they are back to back. The solution is to turn one wheel clockwise and the other one counterclockwise. This requires two separate signals, one to drive each wheel. Of course, if you want the robot to turn, you can send identical pulses to each wheel.
http://www.drdobbs.com/jvm/mixing-activex-with-java/228700132
CC-MAIN-2015-27
refinedweb
2,724
55.44
News from the Trenches Last week's XML-Deviant introduced a debate at the W3C concerning issues with the Namespaces Recommendation and URIs. Since then, the discussion on the newly created xml-uri mailing list has exploded, with well over 400 messages being posted in the first week! (And this from many who were spending the week in Amsterdam at WWW9.) Approaching such an in-depth discussion is not an easy task. This week's column poses some questions -- and attempts to provide some answers -- to help guide developers concerned over the current debate. (If you've not read last week's column yet, it's probably a good idea to give it a read before carrying on.) Why are we having a debate? We gave good coverage of the background to this debate in last week's column, "Namespace Trouble." What has become clear during subsequent discussion is that, before it became public, the issue was rigorously tackled by the XML Plenary (the collective group of all members of the W3C's XML activities). Despite that, as Joe Kesselman noted, a consensus still wasn't reached: I think everyone on the plenary understood the issues and honestly disagreed anyway, and I was very impressed with the amount of time and skill invested in considering the alternatives. It would appear this deadlock is what precipitated the now notorious "Pope 32767" leak to XML-DEV. What's the problem? The main point under debate is the use of relative URI references within namespace identifiers. There is a general consensus that they are a cause for concern, and that significant action is needed to address them. To recap, the Namespaces Recommendation says equality between namespace identifiers should be character-for-character string equality. However, this is in conflict with their essential "URI-ness" and brings unpredictability into any system that relies on dereferencing a relative namespace URI. Tim Bray, co-editor of the Namespace Recommendation, has stated that he believes relative URIs are a bug in the recommendation: ... it is my view a huge bug that the Namespace Recommendation doesn't forbid the use of relative URI references. The obvious reaction to finding a bug is to fix it. While this works for software, it's a little more complex with W3C Recommendations. There are already many documents in existence that make use of relative URIs in namespace declarations. Some Microsoft tools make use of relative URIs to reference intra-document schemas (i.e., the schema definition is given within the referencing document). This usage is quite legal, and well within the letter of the specification. John Cowan, who has been leading much of the debate, has made it clear that any solution must not break these documents: These documents were issued in conformance with a W3C Recommendation, which is supposed to be stable, and people are supposed to be able to rely on it. Cowan has characterized the issue as the "Moral Problem." In a nutshell, any fixes must be backwards compatible. We'll go on to look at proposed solutions, but first cover two points germane to the debate. The first is to define "absolutization," a technique featured in several solutions. Secondly, we'll look at the significance (if any) of a namespace URI to a processing application. What does "absolutize" mean? The desperately unwieldy term absolutization has been defined on the xml-uri list as "RFC2396-style relative reference resolution." The relevant section in RFC 2396 is Section 5.2. "Resolving Relative References to Absolute Form." Basically, the term describes the process of turning a relative URI into an absolute URI. What does a namespace URI point to? This is a common question, and has been raised again because the most common use of relative URIs is to reference a schema (for instance, in some of the Microsoft documents we mentioned above). Another way of asking the question would be "What happens when I dereference a Namespace URI?" In English, this means, "If I point my browser at a Namespace URI, what is returned?" The answer: whatever you like. The Namespace Recommendation leaves room for an individual application, or specification, to define what the namespace identifier signifies. It may be human-readable documentation, a schema, or even nothing. It is a point of debate whether or not this is useful, but there is some precedent for it. For example, the RDF specification says that ... the namespace name serves as the identifier. So, in RDF, the namespace URI reference identifies the location of the RDF schema, but not necessarily the format of that schema. However, the W3C XML Schemas specification uses a different mechanism, based around an optional schemaLocation attribute. This solution avoids mandating the use of namespace URIs for locating schemas. Additionally, to assume that a namespace URI dereferences to a single kind of resource is quite limiting. As Tim Bray has illustrated, there is a wide range of content that could potentially be retrieved: I see a multiplicity of interesting schema facilities (XML-Schema, RDF Schema, Relax, Schematron, DTDs, more coming), a multiplicity of other interesting stuff about vocabularies that isn't captured by schemas (style sheet. As Bray goes on to suggest, this is a packaging issue and one that could usefully be addressed in the short term. (See "Good Things Come in Small Packages" for related discussion.) What are the proposed solutions? The following three proposals have been discussed so far, and are extracted from an excellent summary by Joe Kesselman: There are obviously more details to each proposal, but these are the key points. From certain perspectives, the different proposals can blur into one another. For example, a short term solution may be to follow the LITERAL option, with the qualification that relative URIs are to be phased out, and that ultimately all namespace identifiers will be absolute URI references -- which gives, in effect, the FORBID proposal. Ignoring the philosophical debates about "What's in a Name?", and "What is a Resource?", etc., a bald statement of the problem could be as one of change management. There is a bug in an installed base of software (or documents in this case). How do we manage the roll-out of a bug fix? For the developer on the ground this is the main concern. What does the debate mean to the XML developer? If you're using relative URIs in your namespaces identifiers then you should probably reconsider whether or not they add real benefit. Tim Berners-Lee has presented a brief example of a potentially valid use for relative namespaces in "virtual" documents. These are documents created on the fly by a database and thus have no representation outside a database request. Here are two questions to consider: - If you're using a relative URI to reference a schema locally (which seems to be the most common usage), can you guarantee that the schema will always be distributed with the document? - Secondly, if you're using a relative URI to reference a schema defined within your document, then can you guarantee that some XSLT transformation may not separate the schema and the content? If the answer is "no" to either case, then using an absolute URI that references a fixed location is going to be a better option. If you're not using relative URI references in namespaces, then you are largely immune to the debate. The Namespace Recommendation still stands, and it can be used safely. As to the fall-out from this debate, it remains to be seen what will happen. It's possible that one or more W3C specifications will get revised. The Namespace Recommendation is the obvious one, although XPath, RDF, and the DOM all interact with namespaces in different ways and some revisions may have to propagate through the specifications. If you're working on XML tools or parsers, then there may be changes required at various levels -- from the parser right through to DOM implementations. This shouldn't be a cause for undue concern, but it's something to be aware of. How will it all end? Some order needs to be imposed onto the xml-uri list shortly, to better propose a plan of action. It being the first time a W3C issue has been taken public in this manner, there is no defined process for how closure will be reached. Judging from current comments it would appear that even the W3C doesn't quite know how to end it yet. Michael Champion suggested that a poll would be extremely useful to determine the current course of the debate: ... I'll bet many of us would like to know quantitatively where people in the XML community, not just the W3C, stand on the issue. It's by no means certain that the community at large will be any more effective at finding a clear way through the problem than the XML Plenary. Yet the public discussion has not been in vain. Although we've not covered "philosophical" issues in this article, the recent debate has revealed an interesting contrast in vision between the W3C core team and the XML community, and provided both groups with a useful mirror in which to see themselves. Whatever the outcome, you can be sure that we'll be here to keep you informed!
http://www.xml.com/pub/a/2000/05/24/deviant/index.html
crawl-003
refinedweb
1,551
53.71
Question : I’d like to find out the arity of a method in Python (the number of parameters that it receives). Right now I’m doing this: def arity(obj, method): return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self class Foo: def bar(self, bla): pass arity(Foo(), "bar") # => 1 I’d like to be able to achieve this: Foo().bar.arity() # => 1 Update: Right now the above function fails with built-in types, any help on this would also be appreciated: # Traceback (most recent call last): # File "bla.py", line 10, in <module> # print arity('foo', 'split') # => # File "bla.py", line 3, in arity # return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self # AttributeError: 'method_descriptor' object has no attribute 'func_co Answer #1: Module inspect from Python’s standard library is your friend — see the online docs! inspect.getargspec(func) returns a tuple with four items, args, varargs, varkw, defaults: len(args) is the “primary arity”, but arity can be anything from that to infinity if you have varargs and/or varkw not None, and some arguments may be omitted (and defaulted) if defaults is not None. How you turn that into a single number, beats me, but presumably you have your ideas in the matter!-) This applies to Python-coded functions, but not to C-coded ones. Nothing in the Python C API lets C-coded functions (including built-ins) expose their signature for introspection, except via their docstring (or optionally via annotations in Python 3); so, you will need to fall back to docstring parsing as a last ditch if other approaches fail (of course, the docstring might be missing too, in which case the function will remain a mystery). Answer #2: Use a decorator to decorate methods e.g. def arity(method): def _arity(): return method.func_code.co_argcount - 1 # remove self method.arity = _arity return method class Foo: def bar(self, bla): pass print Foo().bar.arity() Now implement _arity function to calculate arg count based on your needs Answer #3: This is the only way that I can think of that should be 100% effective (at least with regard to whether the function is user-defined or written in C) at determining a function’s (minimum) arity. However, you should be sure that this function won’t cause any side-effects and that it won’t throw a TypeError: from functools import partial def arity(func): pfunc = func i = 0 while True: try: pfunc() except TypeError: pfunc = partial(pfunc, '') i += 1 else: return i def foo(x, y, z): pass def varfoo(*args): pass class klass(object): def klassfoo(self): pass print arity(foo) print arity(varfoo) x = klass() print arity(x.klassfoo) # output # 3 # 0 # 0 As you can see, this will determine the minimum arity if a function takes a variable amount of arguments. It also won’t take into account the self or cls argument of a class or instance method. To be totally honest though, I wouldn’t use this function in a production environment unless I knew exactly which functions would be called though as there is a lot of room for stupid errors. This may defeat the purpose. Answer #4: Ideally, you’d want to monkey-patch the arity function as a method on Python functors. Here’s how: def arity(self, method): return getattr(self.__class__, method).func_code.co_argcount - 1 functor = arity.__class__ functor.arity = arity arity.__class__.arity = arity But, CPython implements functors in C, you can’t actually modify them. This may work in PyPy, though. That’s all assuming your arity() function is correct. What about variadic functions? Do you even want an answer then? Answer #5: here is another attempt using metaclass, as i use python 2.5, but with 2.6 you could easily decorate the class metaclass can also be defined at module level, so it works for all classes from types import FunctionType def arity(unboundmethod): def _arity(): return unboundmethod.func_code.co_argcount - 1 # remove self unboundmethod.arity = _arity return unboundmethod class AirtyMetaclass(type): def __new__(meta, name, bases, attrs): newAttrs = {} for attributeName, attribute in attrs.items(): if type(attribute) == FunctionType: attribute = arity(attribute) newAttrs[attributeName] = attribute klass = type.__new__(meta, name, bases, newAttrs) return klass class Foo: __metaclass__ = AirtyMetaclass def bar(self, bla): pass print Foo().bar.arity()
https://discuss.dizzycoding.com/how-to-find-out-the-arity-of-a-method-in-python/
CC-MAIN-2022-33
refinedweb
719
54.12
Details Description Check that the private and public keys belong to the same pair (via, e.g. or by en/decrypting a dummy message). Issue Links Activity - All - Work Log - History - Activity - Transitions I've just committed this. Thanks Andrei! (I manually tested the patch with a valid keypair and then with an invalid keypair. I also made a minor change to formatting, and put the new dependency version number in the top-level POM.) Thanks for reviewing. I will fix the remaining issues as soon as possible. > Have you manually tested this with a keypair generated with ssh-keygen? I have successfully started a 3-node ZooKeeper cluster using a version of whirr with this patch and ~/.ssh/id_rsa as a private-key-file. I have been able to login to all the nodes using the standard ssh client. I'm pretty confident this works for any valid SSH RSA key. Thanks for the new patch. It's getting close now. - KeyPair#sameKeyPair swallows the exception. We should at least log it. - KeyPairTest should use assertThat rather than assert (since the latter depends on whether asserts are enabled). - The indentation and start import still need fixing. Have you manually tested this with a keypair generated with ssh-keygen? +1 to moving DSA key support to another issue. I suggest that we should open another JIRA for accepting DSA key pairs if needed. I will change the patch to use commons-codec for Base64 encoding. > Does this code only support RSA keys? Should we generalize to support DSA keys too? It supports only RSA keys but this limitation was already in the code base. Should we keep things the way they are? I will add a note to confluence explaining the restriction. > Nits: the indentation should be two spaces, and star imports should be avoided. Ok. I will fix that. - Apache James uses not-yet-commons-ssl, so there's a precedent (). - Can you use Apache Commons Codec for the Base64 encoding? - Does this code only support RSA keys? Should we generalize to support DSA keys too? Or at least update the docs to spell out what is supported (I would suggest a note in src/site/confluence/quick-start-guide.confluence). - Nits: the indentation should be two spaces, and star imports should be avoided. I've attached a patch that checks that both keys belong to the same key pair. I have edited core/pom.xml and added not-yet-commons-ssl.jar as a dependency. It should be safe to use from a license point of view: [1] [2] I have also used a class placed in the public domain for Base64 encoding: [3] > ... the only dependency that needs to be added is not-yet-commons-ssl.jar (org.apache.commons.ssl). Is this acceptable? Hmm, this uses the Apache namespace, but is not an ASF project as far as I can tell. You could send a question to Apache's legal-discuss list () to get a definitive answer. I think I can avoid adding OpenSAML as a dependency by extracting only the relevant code. After taking a quick look I believe that the only dependency that needs to be added is not-yet-commons-ssl.jar (org.apache.commons.ssl). Is this acceptable? I will give it a try tomorrow. I understand having really strict validation it's not mandatory but it would be a nice addition. I had a quick look at this too and realized it was non-trivial! The OpenSAML code has precisely the right function, but I hesitate to add a big dependency like this. In fact, the problem we saw was that the public key didn't match because a user had changed whirr.private-key-file but not whirr.public-key-file. With the change in WHIRR-160 which makes the public key default to private key + ".pub" (rather than {{$ /.ssh/id_rsa_rackspace.pub}}), perhaps this isn't such a problem now? I need some help on this one. I have posted a question on stackoverflow [1]. The Java CE documentation is really hard to use. [1] Got any suggestions for a cross-platform pure Java solution? Great! Tom, thanks for reviewing.
https://issues.apache.org/jira/browse/WHIRR-161
CC-MAIN-2017-43
refinedweb
700
69.28
Daily return (P&L) of total broker value Dear Backtrader community, I replicated the quickstart example with the SMA indicator (chapter: "adding an indicator"), and it works perfectly. Backtrader is awesome, so thanks to everybody who contributed to this project and the great documentation! I would now like to better understand the return characteristics of the strategy, and would therefore like to access the daily returns ("PnL") of the strategy (=total broker value of active positions and cash combined). The final idea would be to plot a histogram of the daily returns of the strategy and compare it with the returns of just "buy-and-hold"-ing the asset, similar to this plot: So far I could only find the absolute value of the broker (using "broker.getvalue()") but not the daily returns (= daily percentage change of the absolute value). Could anybody indicate where the returns are stored/how I can access them? I couldn't find that in the documentation nor the forum... Your help would be highly appreciated! Thanks, jf - backtrader administrators last edited by backtrader You have to plug in an analyzer. You probably want to read this post: ok great, thanks!
https://community.backtrader.com/topic/1077/daily-return-p-l-of-total-broker-value
CC-MAIN-2020-40
refinedweb
195
52.39
:: - The gc compilers generate better code in many cases, most noticeably for floating point on the 32-bit Intel architecture. - The gc compilers do more in-lining, including for some operations in the run-time such as append and interface conversions. - There is a new implementation of Go maps with significant reduction in memory footprint and CPU time. - The garbage collector has been made more parallel, which can reduce latencies for programs running on multiple CPUs. - The garbage collector is also more precise, which costs a small amount of CPU time but can reduce the size of the heap significantly, especially on 32-bit architectures. - Due to tighter coupling of the run-time and network libraries, fewer context switches are required on network operations. You can find a full list of changes in Go 1.1 on the language's official site. 61 Reader Comments Other than that, Go has an insightful object model and elegant concurrency framework and is, IMHO, the best attempt to reconcile static typing with practical object-oriented design. Consider open source hardware, which is nonsensical if you expand "open source" to "open source code." If you think of "source" in its literal meaning, i.e. something from which a widget is obtained, it makes more sense. You can obtain binaries from code, or circuit boards from design files, or tasty drinks from a fresh water spring, and if those sources are open to the public for use and/or modification then they're literally open source. In the MATLAB example, the source of the language--the language specification--is not open, and the existence of Octave doesn't change that. The good people at GNU reverse engineered the closed MATLAB specification to implement the open Octave specification. If the Go specification was made available under, say, a creative commons license then it would be open source. Otherwise, I guess you could reverse engeer the language spec and then implement your language spec using Google's open source code, which is to say that the question at hand is pretty meaningless. Perhaps that's because Rob Pike and Ken Thompson were involved in the creation of both Go and Plan 9. Apparently Plan 9 is one of the available target platforms for Go, although I'm curious how well it's supported. The Go authors also reused a lot of open-sourced Plan 9 compiler code in the Go toolchain. That's most likely intentional, as two of the creators of Go (Rob Pike & Ken Thompson) were also two of the creators of Plan 9. Go is also descended from the concurrent languages they'd previous created that largely targeted Plan 9 and its descendants. Edit: Ninja'd I agree the familiarity with the phrase "open source" has been leveraged in labeling other similar concepts, even if "source" isn't the thing. I was trying to get to the fact that the license for what you do with the product (be it code, or whatever is under the license) has no bearing on the decision making process for the project itself, and should not have emphasized the code in particular to contrast with the decision making. It's as if open processes or practices are somehow synonymous with open source licenses and the associated works, and they are not. As I read through the BSD license (and others), it tells me everything I can and can not do with the "stuff" - code in this case. Or what I have to do if I use it. That is a great metric for judging the implementation, and may be one important method for judging whether a language is a good choice for a project based on the associated tools. Is it an open source environment, or open source implementation, or open source toolchain? That it is in no way a metric for whether the language itself is "open" or not. What matters there are things like whether the process for modifications to the language is transparent, whether there is mechanism for people to join the decision making process. Sometimes that can be encapsulated by whether it is part of standards body, but that is not the only way. The former may be open source or not. The latter may be an open process or not. The two are relatively orthogonal, although the implications are often congruent. But I would not call a language or anything else defined by the latter "open source", with all the associations to licenses and behavior that have no relevance in that context. It could be a standards-based language or a <xyz co> defined language with a published spec or any number of things. Yep. A language isn't the same thing as the tools to build programs in that language. Just because there is an open source *SOMETHING* in sight somewhere, that doesn't make everything around open source. A language, as opposed to the tools for the language, doesn't even have source code per se. Probably the closest thing to the "source code" for a language would be the language specification document. You're free to fork and modify the language as well as the tools. Sounds like open source to me. I agree with this. Too many spoiled people in this thread not stuck using closed languages. For example, take MATLAB: "The MATLAB Syntax and Semantics are not published to the public." ... read/61312 Closed source languages really do exist. Take a look at how many years the Octave people have spent reverse engineering MATLAB and you'll see why this matters. To be fair, I'm not sure even Mathworks has a complete specification of the language written down. The whole language is such a bloody mess... Its a software engineer's absolute worst nightmare. It didn't even have namespaces until a couple years ago. Keep in mind, C++'s compilers haven't been standing still this whole time, either. In C++11, move semantics alone resulted in a free 30% speedup. ). In response, a quote from that thread: "[The Haunts team's poor decisions are] not mutually-exclusive with: Go's designer's made extremely poor decisions that screwed the usability of the language." You're correct that there was misunderstanding on the behalf of the developer. But it seems like certain elements of Go's design also contributed to the problem. Why does Go use the local copy of the library even when the import statement still points to an external repo? Why ship Go without a mechanism for ensuring the repo owner and the programmer have the same version (or at least, the local version gets merged with the repo owner's version)? Fixing either or both of those would have preemptively prevented the problem from occurring. Last edited by lettucemode on Tue May 14, 2013 3:03 pm What's the definition of such a language? AFAIK Go is designed by Google, it's basically a proprietary language. An 'open source' Go compiler / platform might be available but that doesn't make it an open (source) language. doesn't make the LANGUAGE open source. Python devs will often make a distinction between Python the language and Python implementations (eg CPython, Jython, IronPython, Pypy etc). But yeah most people will use it as shorthand for a language where the "reference" implementation is open source. I've been reading up on this feature a little because I also found it a bit odd.. If you really want to get involved with a Proprietary Corporate Language, while not working for that particular shop, you should have your head examined first. I like the bunny better.. Go only reached specification "stability" in March; it's still a new language with an experimental implementation. I'm all for playing with and learning new tools and languages, but it seems like a particularly poor choice to do that on a crowdfunded game project with a shoestring budget. As you say, the (completely optional!) feature they used worked as designed, albeit there's a good argument to be made that the design is (a little) unintuitive. It's obviously intended for the reasonably common case where you want to include a reference library with a stable API but don't care to make any changes to its code. Seems to me, though, that this generally best handled outside the language; e.g. if I make no changes to the library, developers can download that dependency for themselves, if I do change the library, then I maintain a copy of the source in my VCS. As you suggest, a local git clone of the new library would be a reasonable way to maintain this separation if you do wish to include it in the language spec. (And people call the C++ STL complex--at least C++ doesn't require you to implement git!) I think the idea is that they want to avoid the annoying things you get in other languages (like Python) where you have to go dependency hunting when you try to build something. At first I found the idea incredibly stupid, but the more I think about it the more it makes sense. But as you say, this is intended to be used for stable modules that you want to include (and not change locally). You do realize that you just skipped an two pages explaining why that very link is wrong? I have never seen a collection of posts that has completely misunderstood open source in every single aspect of what open source is. The only other consistent failing of the concept of open source is MS its own self. Good job, sir. You have executed the perfect fail. What's the definition of such a language? AFAIK Go is designed by Google, it's basically a proprietary language. An 'open source' Go compiler / platform might be available but that doesn't make it an open (source) language. The text of the allows the modification of the source in any manner. The requirement that "Google" and other Google, Inc. trademarks not be attached to modified source (with the exception of the required copyright notice) without permission has no effect on the right to modify and redistribute with the required copyright attributions specified in the license. Open Source simply means that anyone can modify or borrow from the source and redistribute the new code that results from the modification or insertion of borrowed code. Open Source does not necessarily grant the right to use trademarks that may be applied to unmodified code distributed by the owner of the trademark or with permission of the owner of the trademark. Dart uses this definition of "Open Source". Dart is a modification of the Java specification that is not distributed as a "Java" language. It is advertised as mostly compatible with Java, but other than that description does not use the Oracle trademark. Similarly a programmer may grab this source and generate a "new" language that is 99% compatible with Google Go. However "Go" is a Google trademark so in order to distribute the new version as "Go" permission from the trademark holder is needed, but to distribute the new version as "Gehe" the only thing that is needed is a search to make sure that no one has a registered trademark on that label. They can add to the documentation comments stating that "Gehe" is largely "Go" compatible...hopefully with an explanation of which parts of Go don't work and what features Gehe adds to the Go language. There are language specifications that are in the public domain, but that is an entirely different class of "Open". BASIC, Lisp & C are examples of these truly Open languages. Each has certain characteristics that usage requires of any language claimed to be an implementation of the language, but compatibility with the canonical standard is not required. (This license appears to include Go in this group as it says nothing about the language standard...if random modification to the language standard is restricted, then that is a separate license) For example BASIC uses a specific set of English keywords with dozens of non-standard keywords, variable types and string operations. Changing the language to German though and it ceases to be BASIC even if the German keywords are a one for one substitution and the syntax is unchanged. It becomes a Deutsch programming language that is 100% bytecode compatible with the dialect of BASIC that was used by the person who generated the German language port. It will share the same portability problems across BASIC dialects that the 'proper' English language BASIC implementations do. That is they only agree on a limited subset of keywords and (relative) simplicity. Edit: From the Golang (Google Go) Wiki On the day of the general release of the language, Francis McCabe, developer of the Go! programming language (note the exclamation point), requested a name change of Google's language to prevent confusion with his language.[33] The issue was closed by a Google developer on 12 October 2010 with the custom status "Unfortunate" and with the following comment: "there are many computing products and services named Go. In the 11 months since our release, there has been minimal confusion of the two languages."[34] Given the developer's statement, clean room versions of Golang compilers and other tools implementing the "pure" Google Golang specification can use the Go name without the copyright notice crediting Google. Just make sure that the code that does not include the notice required by a license does not include portions of another programmer's licensed code. Nor are you restricted to the canonical standard if you think your preferred Go syntax, keywords and operators will do a better job. I am not saying that tools/environment are not open source. I am talking about the specification of the language itself. In practice, are there 8 variations of the Java language with significant traction, all calling themselves Java Language Specification 2.1, because people "forked" the language itself? Or are there instead multiple implementations of the JVM because there are both closed and open source variants of the implementation? Bad choice of example. Java is an Oracle trademark. Use of the trademark requires permission from Oracle. You are free to fork Java without permission IF you do NOT use the name Java. Google Dart is one example & it is not alone. The implementation(s) of a a language are more defining than the specifications. Since all Go implementations seem to be open source, I think that calling it an open source language fits well enough. I'd think there'd have to be a notable (or existing at the least) closed source implementation in existence to say otherwise. Human languages are not precise for every context. Close enough is close enough. When someone releases a closed source implementation, then you can start QQing over semantics. A closed source compiler or even complete tool chain does not close a language. C is a very good example. It is an Open language. Programmers are free to extend C in any manner they wish as long as they do not try to claim that their version is the standard. They are free to distribute their version of C under any license they like as long as the new license does not violate the license terms of the tools used to create it or licenses that apply to code borrowed from other programmers. A language is closed by registering the name as a trademark and requiring those who use the name to comply with the standards specification (non-standard versions can still be distributed as long as they do not use the trademark). Copyright law has also been used to restrictively license programming languages (x86 and ARM for examples) You must login or create an account to comment.
http://arstechnica.com/information-technology/2013/05/googles-programming-language-go-gets-a-big-speed-boost/?comments=1&start=40
CC-MAIN-2016-44
refinedweb
2,652
61.26
. lHHere is the dlll content in c#:I don't see any dll definition - just some C# code. If you're turning that into a native dll then you need to post the result definition, i.e. the exported function prototype. I have no idea why you'd want a dll though - at a quick glance all the current C# code is doing could be done in pure Java... using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Copy { public class Operation { public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { // Get the subdirectories); } // Get the files in the directory and copy them to the new location. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { string temppath = Path.Combine(destDirName, file.Name); file.CopyTo(temppath, false); } // If copying subdirectories, copy them and their contents to new location. if (copySubDirs) { foreach (DirectoryInfo subdir in dirs) { string temppath = Path.Combine(destDirName, subdir.Name); DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } } } } DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) is signature of the function.I don't think so. That's the signature of the function in C# i'd gather. What are the fully-qualified types of the parameters? Is that the standard library string class? >>Is that the standard library string class?I don't think you quite grasped the point. 'string' is a C# class. dlls do not contain C# types, they contain native types. When you build the C# target as type library, you will probably find that those string types are converted to char* or const char*. The latter maps to java.lang.String in JNA. See the following about what happens to type when you compile a C# file to a target type of library: yes. None of the class definitions above are mine. They are C# defaults. I didn't add use any referencing class. Regards. If you are experiencing a similar issue, please ask a related question Join the community of 500,000 technology professionals and ask your questions.
https://www.experts-exchange.com/questions/28138670/a-simple-JNA-example-that-invokes-a-simple-C-4-5-dll-having-a-one-function.html
CC-MAIN-2017-43
refinedweb
340
61.12
import license Function The import license command is used to import license files. If you want to use value-added features or update license files, run this command. Format import license ip=? user=? password=? license_path=? [ port=? ] [ protocol=? ] Parameters Level Super administrator Usage Guidelines - A license file can activate a value-added function for the storage system. To enable a value-added function, you must purchase and import a license file for the function. - This command can import license only from an FTP server or SFTP server connecting to the storage system. Prerequisites for using this command: - The FTP server or SFTP server is accessible to the storage system. - The FTP service or SFTP service has been started on the server. - The license file to be imported must be valid for the desired value-added function, because this command will override the existing license file and an incorrect license file can fail the desired function. - If the storage system serves as a server in the file transfer with external systems, it supports the SFTP service only. If the storage system serves as a client, it supports both the FTP and SFTP services. Example To import a license file which name is "license.dat", where the IP address of the FTP server for storing the license file is "10.10.10.1", the user name for accessing the FTP server is "admin", and the user's password is "123456", run the following command:. admin:/>import license ip=10.10.10.1 user=admin password=****** license_path=license.dat protocol=FTP WARNING: You are about to import a license file. This operation will overwrite the previous license file. Importing an incorrect license file will cause that some features are unavailable. Suggestion: Before you perform this operation, ensure that the license file to be imported is correct. Have you read warning message carefully?(y/n)y Are you sure you really want to perform the operation?(y/n)y Command executed successfully. System Response None
https://support.huawei.com/enterprise/en/doc/EDOC1000138382/3f3079ff
CC-MAIN-2019-39
refinedweb
330
58.48
Despite more complex and less intuitive syntax compared to Java, Scala actually drops several features of Java, sometimes for good, other times providing replacements on the standard library level. As you will see soon, Scala isn't a superset of Java (like Groovy) and actually removes a lot of noise. Below is a catalogue of the missing features. break and continue in loopsEvery time I see code like this: while(cond1) { work(); if(cond2) continue; rest(); } I feel as if it has been written by a guy who truly misses the times when goto wasn't yet considered harmful. Hands up who finds this version more readable: while(cond1) { work(); if(!cond2) rest(); } Getting rid of break requires a little more though, but generally extracting a loop to a separate method/function (or at least putting it at the end of existing method) and using return instead will do the trick. By the why Scala allows you to define functions inside other functions, so you won't pollute your global class namespace with plenty of small methods used only once – problem that sometimes arises when religiously extracting methods in Java. break and continue – we thank you in the name of our fathers and grandfathers for your contribution to imperative programming. But we no longer need you and we won't miss you. ArraysIt's amazing how many bad habits have we learnt by all these years and how we got used to idioms that are inconsistent and simply painful. You have covariant arrays in Java with square brackets syntax, length final property and ability to store primitive types. You also have Java collections framework with List&lt;T&gt; abstraction – that is not covariant, uses get() and size() methods and can't store primitives. The list of differences does not end here, however isn't every array just a special case of List? Why do we have a special syntax for arrays in the language while collections are implemented in on top of the language? And isn't a bit irritating to convert them from one to another all the time? String[] array = new String[10]; List<String> list = Arrays.asList(array); String[] array2 = list.toArray(new String[list.size()]); Converting from collection to array is my favourite Java idiom... Why not just have same syntax, same methods, same abstraction, polymorphic behaviour – and only different implementation names? val array = Array("ab", "c", "def") println(array(1)) array filter (_.size > 1) val list = List("ab", "c", "def") println(list(1)) println(list filter (_.size > 1)) And don't worry, behind the scenes Scala compiler will use the same efficient array bytecode as if you were using plain arrays in Java. No magic abstractions and several layers of wrapping. PrimitivesAnother weird Java inconsistency – why do we have a choice between primitive int and wrapping Integer? If the variable is of Integer type does this mean it is optional (null), or is it just that you can't use primitives in collections (but can in arrays, as pointed out above)? Is this unboxing safe (also known as: how on earth this can throw NullPointerException?) Can I compare these to integers using == operator? And can I simply call toString() to get string representation of this number? In Scala you no longer have a choice, every primitive type is an object, while most of the time still being a primitive in memory and in bytecode. How is that possible? Have a look at the following popular example: val x = 37 //x and y are objects of type Int val y = 5 val z = x + y //x.+(y) - yes, Int class has a "+" method assert(z.toString == "42") x, y and z are instances of type Int. They are all objects, even adding two integers is semantically a method + called on x with y argument. If you think it has to perform terribly – once again behind the scenes it is compiled into ordinary primitive addition. But now you can easily use primitives in collections, pass them when any type is required (Object in Java, Any in Scala) or simply create a text representation without awkward Integer.toString(7) idiom. Sooo many bad habits. Checked exceptionsAnother feature that I can hardly miss. Not much to be said here. Neither any mainstream language except Java have them, nor any mainstream JVM language (except Java). This topic is still relatively controversial, however if you've ever tried to deal with ubiquitous SQLException or IOException, you know how much boilerplate it introduces without good reason. Anyway, look at the next examples... InterfacesThis one is good! Scala doesn't have interfaces. Instead it introduces traits – something in between abstract classes (some trait methods might have implementation) and interfaces (one can mix in more than one trait). So essentially traits enables you to implement multiple inheritance while avoiding dreadful diamond problem. How it is done requires an article on its own (in short: last trait wins), but I would rather show you an example how helpful traits are to reduce duplication. Suppose you are writing an interface to abstract binary protocol. Most implementations take raw byte array, so in Java you would simply say: public interface Marshaller { long send(byte[] content); } This is great from the implementation perspective – just implement a single method and the abstraction is ready. However users of the interface are complaining that it is cumbersome and not very convenient. They would like to send strings, binary and text streams, serialized objects and so on. They can either create a facade around this interface (and every user will create his/hers very own with a distinct set of bugs) or force the author of the API to extend it: public interface Marshaller { long send(byte[] content); long send(InputStream stream); long send(Reader reader); long send(String s); long send(Serializable obj); } Now the API is a breeze, however every implementation has to implement five methods instead of one. Also note that since most abstracted protocols are based on byte arrays, all the methods can be implemented in terms of the first one. And only the first one contains the actual marshalling code. This in turns causes every implementation to have the exact same four methods – duplication didn't go away – it has just been moved. Actually this problem is known as a thin vs. rich interface and it has been described in great Programming in Scala book. What I was typically doing was to give service providers an abstract class with typical implementations of all the methods except the root one, which was used by all other methods: import org.apache.commons.io.IOUtils; public abstract class MarshallerSupport implements Marshaller { @Override public abstract long send(byte[] content); @Override public long send(InputStream stream) { try { return send(IOUtils.toByteArray(stream)); } catch (IOException e) { throw new RuntimeException(e); //choose something more specific in real life } } @Override public long send(Reader reader) { try { return send(IOUtils.toByteArray(reader)); } catch (IOException e) { throw new RuntimeException(e); } } @Override public long send(String s) { try { return send(s.getBytes("UTF8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } @Override public long send(Serializable obj) { try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); new ObjectOutputStream(bytes).writeObject(obj); return send(bytes.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } } Now everyone is happy – instead of copying all the overloaded methods over and over, just subclass the MarshallerSupport and implement what you need. But what if your interface implementation also has to subclass some other class? You are out of luck then. In Scala however you change the interface to trait, opening the possibility to mix in (think something between extending and implementing) several other traits. By the way do you remember what I said about checked exceptions? trait MarshallerSupport extends Marshaller { def send(content: Array[Byte]): Long def send(stream: InputStream): Long = send(IOUtils.toByteArray(stream)) def send(reader: Reader): Long = send(IOUtils.toByteArray(reader)) def send(s: String): Long = send(s.getBytes("UTF8")) def send(obj: Serializable): Long = { val bytes = new ByteArrayOutputStream new ObjectOutputStream(bytes).writeObject(obj) send(bytes.toByteArray) } } Switch statementThere is no switch statement in Scala. Calling pattern matching a better switch would be a blasphemy. Not only because pattern matching in Scala is an expression returning a value and also not because you can switch over literally any value if you want. Not even because there is no fall-through, break and default. It's because Scala's pattern matching enables you to match whole object structures and lists, even with wildcards. Consider this expression simplification method, originally taken from already mentioned Programming in Scala book: abstract class Expr case class Var(name: String) extends Expr case class Number(num: Double) extends Expr case class UnOp(operator: String, arg: Expr) extends Expr case class BinOp(operator: String, left: Expr, right: Expr) extends Expr //... def simplify(expr: Expr): Expr = expr match { case UnOp("-", UnOp("-", e)) => e //double negation case BinOp("+", e, Number(0)) => e //adding zero case BinOp("*", e, Number(1)) => e //multiplying by one case _ => expr } Look carefully how clever this code is! If our expression is unary “-” operation and the argument is a second unary “-” operation with any expression e as an argument (think: -(-e)), then simply return e. If you find this pattern matching example hard to read, check out the roughly equivalent Java code. However please remember: size doesn't matter (one could probably do the same with Perl one-liner) – it's about readability and maintainability: public Expr simplify(Expr expr) { if (expr instanceof UnOp) { UnOp unOp = (UnOp) expr; if (unOp.getOperator().equals("-")) { if (unOp.getArg() instanceof UnOp) { UnOp arg = (UnOp) unOp.getArg(); if (arg.getOperator().equals("-")) return arg.getArg(); } } } if (expr instanceof BinOp) { BinOp binOp = (BinOp) expr; if (binOp.getRight() instanceof Number) { Number arg = (Number) binOp.getRight(); if (binOp.getOperator().equals("+") && arg.getNum() == 0 || binOp.getOperator().equals("*") && arg.getNum() == 1) return binOp.getLeft(); } } return expr; } UPDATE: In one of the comments Yassine Elouafi claims this example is too limited as it can not simplify nested expressions like: BinOp("+", Var("x"), BinOp("*", Var("y"), Number(0))) which reads: x + y * 0. Indeed this algorithm assumes nested terms are already simplified. But it should be pretty obvious to improve this code to work with arbitrary complex expressions – without loosing readability. Recursion with bottom-up approach seems perfect: simplify the leaves first (simplest terms) and go up. Here is the improved code: def simplify(expr: Expr): Expr = expr match { case UnOp("-", UnOp("-", e)) => simplify(e) case BinOp("+", e, Number(0)) => simplify(e) case b@BinOp("+", _, _) => simplify(BinOp(b.operator, simplify(b.left), simplify(b.right))) case BinOp("*", e, Number(1)) => simplify(e) case BinOp("*", e, Number(0)) => Number(0) case _ => expr } Not that bad, don't you think? Of course there are still several improvements that might be applied (0 + e, 1 * e, operations on constants, etc.), but thanks to the power of recursion the results are already quite impressive: //x + y * 0 assert(simplify(BinOp("+", Var("x"), BinOp("*", Var("y"), Number(0)))) === Var("x")) //(x + y) * 0 assert(simplify(BinOp("*", BinOp("+", Var("x"), Var("y")), Number(0))) === Number(0.0)) //-(-(-(-5))) assert(simplify(UnOp("-", UnOp("-", UnOp("-", UnOp("-", Number(5)))))) === Number(5.0)) //y * 1 + (x + z) * 0 assert( simplify( BinOp( "+", BinOp( "*", Var("y"), Number(1) ), BinOp( "*", BinOp( "+", Var("x"), Var("z") ), Number(0) ) ) ) === Var("y") ) So is Scala scalable? instanceof/castingAs with many other features, Scala does not have a built-in syntax for instanceof and downcasting. Instead the language provides you methods on actual objects: val b: Boolean = expr.isInstanceOf[UnOp] val unOp: UnOp = expr.asInstanceOf[UnOp] In Scala a lot of features normally considered as part of the language are actually implemented in the language itself or at least they don't require a special syntax. I like this idea, in fact I find Ruby's way of creating objects (Foo.new – method instead of new operator) very attractive and even unusual lack of if conditionals in Smalltalk requires some attention. EnumsScala doesn't have built-in support for enums. Enumerations in Java are known to have several fancy features which other languages envy like type safety and ability to add methods to each enum. There are at least two ways to emulate enums in Scala: object Status extends Enumeration { type Status = Value val Pending = Value("Pending...") val Accepted = Value("Accepted :-)") val Rejected = Value("Rejected :-(") } assume(Status.Pending.toString == "Pending...") assume(Status.withName("Rejected :-(") == Status.Rejected) Or if you don't care about textual enum representation: object Status extends Enumeration { type Status = Value val Pending, Accepted, Rejected = Value } However the second and the most comprehensive way to emulate enums is to use case classes. Side note: name is actually an abstract method defined in base class. When you declare a method without defining the method body it is implicitly assumed to be abstract – no need to mark the obvious with extra keywords: sealed abstract class Status(val code: Int) { def name: String } case object Pending extends Status(0) { override def name = "?" } case object Accepted extends Status(1) { override def name = "+" } case object Rejected extends Status(-1) { override def name = "-" } //... val s: Status = Accepted assume(s.name == "+") assume(s.code == 1) s match { case Pending => case Accepted => case Rejected => //comment this line, you'll see compiler warning } This approach, although has nothing to do with enums per se, has many advantages. The biggest one is that the compiler will warn you when performing non exhaustive pattern matching – think: switch over an enum in Java without explicitly referencing each and every value or default block. Static methods/fieldsScala doesn't have a notion of static fields and methods. Instead it has a feature named objects as opposed to classes. When you define a class using object keyword, Scala runtime will eagerly create one instance of this class and make it available under class name. This is essentially a singleton pattern built into the language but the most important is the mindset shift introduced by this approach. Instead of a bunch of static functions artificially gathered together inside a class (which is only a de facto namespace in this case) you have a singleton with true methods: sealed abstract class Status case object Pending extends Status case object Accepted extends Status case object Rejected extends Status case class Application(status: Status, name: String) object Util { def groupByStatus(applications: Seq[Application]) = applications groupBy {_.status} } Here is how the syntax works (and nice ScalaTest DSL example): @RunWith(classOf[JUnitRunner]) class UtilTest extends FunSuite with ShouldMatchers { type ? = this.type test("should group applications by status") { val applications = List( Application(Pending, "Lorem"), Application(Accepted, "ipsum"), Application(Accepted, "dolor") ) val appsPerStatus = Util.groupByStatus(applications) appsPerStatus should have size (2) appsPerStatus(Pending) should ( have size (1) and contain (Application(Pending, "Lorem")) ) appsPerStatus(Accepted) should ( have size (2) and contain (Application(Accepted, "ipsum")) and contain (Application(Accepted, "dolor")) ) } } volatile/transient/native and serialVersionUID are goneThe language designers decided to convert the first three keywords into annotations. Both approaches have pros and cons, hard to find the clear winner. However turning serialVersionUID into a class level annotation is a pretty good choice. I know this field existed long before annotations were introduced to the Java language, so we shouldn't blame it. But I always hated when in statically typed languages some names/fields have special meaning not reflected anywhere except the language specification itself (magic numbers?) Unfortunately there are examples of this unpleasant behaviour in Scala as well, namely special treatment of apply() method and methods ending with colon. Too bad. Pre/post-incrementYou cannot do i++ and ++i in Scala. Period. You need a bit more verbose i += 1 – and to make matters worse this expression return Unit (think: void). How can we deal with this noticeable feature missing? Turns out that very often this type of constructs are imperative style legacy and they can easily be avoided by using more functional and pure constructs. Take the following problem as an example: You have two same sized arrays: one with names and a second one with ages. Now you want to display each name with a corresponding age – somehow iterating over both arrays in parallel. In Java this is surprisingly tough to implement cleanly: String[] names = new String[]{"Alice", "Bobby", "Eve", "Jane"}; Integer[] ages = new Integer[]{27, 31, 29, 25}; int curAgeIdx = 0; for (String name : names) { System.out.println(name + ": " + ages[curAgeIdx]); ++curAgeIdx; } //or: for(int idx = 0; idx < names.length; ++idx) System.out.println(names[idx] + ": " + ages[idx]); } In Scala maybe it is shorter, but very mysterious at first: var names = Array("Alice", "Bobby", "Eve", "Jane") var ages = Array(27, 31, 29, 25) names zip ages foreach {p => println(p._1 + ": " + p._2)} zip? I encourage you play a bit with this example. If you don't feel like starting up the whole IDE, try it with Scala REPL: $ scala scala> Array("one", "two", "three") zip Array(1, 2, 31) res1: Array[(java.lang.String, Int)] = Array((one,1), (two,2), (three,31)) Look carefully, do you see the result array containing pairs of corresponding elements from the first and the second arrays “zipped” together? One simple experiment and now suddenly it should be clear and much more readable than ordinary imperative solution. Scala inventors looked very thoroughly on Java language and they didn't just add syntactic sugar (like function literals or implicit conversions). They discovered plenty of inconsistencies and annoyances in Java, getting rid of them and providing more concise and deliberate replacements. Despite higher level constructs like primitive and array objects, under the hood the same fast and straightforward bytecode is generated. "Despite more complex and less intuitive syntax compared to Java, [...]" Really? The expression simplification will work only on a single level .....BinOp('+', Var(x), BinOp('*', Var(y), 0) yield a .....BinOp('+', Var(x), 0) Try to make it work on the whole expression tree and see if the resultant code is still as concise and readable. @steve: Really :-). I knew this is going to be controversial, but do you really think this way of adding all numbers in a collection is intuitive: "(0/:list)(_+_)"? Also see: Is the Scala 2.8 collections library a case of "the longest suicide note in history"?. Of course in Java you would have to write at least 3 lines of verbose code to achieve this and it is actually pretty readable once you have basic Scala knowledge. In Java you don't need any knowledge to understand the equivalent code. Don't get me wrong, personally I hope Scala is the new Java and growing in C++ environment I am not afraid of a bit more complex syntax. But you have to agree that all these wonderful features like lambdas come with a price (also compare javac and scalac performance...) @Yassine Elouafi: Very good point! I updated my article, see for yourself.
https://www.nurkiewicz.com/2011/08/what-features-of-java-have-been-dropped.html
CC-MAIN-2020-29
refinedweb
3,146
53.31
Opened 8 years ago Last modified 5 years ago #5527 assigned enhancement Include RPC handler to retrieve timed events managed by Timeline module Description :( ). It returns all timed events offered by instances of ITimelineEventProvider. Please see below a code snippet illustrating public methods : class TimelineRPC(Component): r""" An interface to Trac's timeline module. """ implements(IXMLRPCHandler) sources = ExtensionPoint(ITimelineEventProvider) def __init__(self): self._event_data = TimelineModule(self.env)._event_data # IXMLRPCHandler methods def xmlrpc_namespace(self): return 'timeline' def xmlrpc_methods(self): yield ('TIMELINE_VIEW', ((list, xmlrpclib.DateTime, xmlrpclib.DateTime, list), (list, xmlrpclib.DateTime, xmlrpclib.DateTime), (list, xmlrpclib.DateTime), (list, )), self.getEvents) yield ('TIMELINE_VIEW', ((list,),), self.getEventFilters) There are still a few open issues and further methods may be needed (e.g. to create, update, delete reports). Besides in order to retrieve all events related to ticket changes (e.g. attachments) timeline.ticket_show_details option in trac.ini needs to be set to true. It is possible to move it onto XmlRpcPlugin. Feel free to do it ! PS: I tested it using 0.11, that's why I specify that value in Trac Release field . Hope you don't mind. Attachments (0) Change History (4) comment:1 Changed 8 years ago by comment:2 Changed 8 years ago by :( ). BTW newer versions may include further features and bug fixes, so it's better to download the latest version. Thanks - a very useful set of methods! Haven't had time to look at it yet though, and first I have a few things I want to redo on the internals before I start adding new methods (specifically #5437). I'll get onto extending methods during August most likely. Stay tuned :-)
https://trac-hacks.org/ticket/5527
CC-MAIN-2017-22
refinedweb
273
52.76
Overloading Operators in C++! Hey guys! It’s the end of the week. Which means, another tutorial! Last couple weeks, we explored the Monte Carlos method, but this time, let’s change it up a little bit. Instead, we’ll be looking at some C++ operators, and more specifically, overloading them. Prequisites: - OOP - 'this' pointer - operators Introduction What are overloading operators? Well take this example: class ExampleClass { private: int value; }; ExampleClass exampleObject; exampleObject += 5; // error! We get an error! Why? Well adding 5 to an object? What does that mean? But how do we add a number to value? Well the attribute is private, so our only choose are methods. class ExampleClass { private: int value; public: void add(int addValue) { value += addValue; } }; ExampleClass exampleObject; exampleObject.add(5); Well, that's good an all, but this is C++! There has to be a better way. Overloading operators. class ExampleClass { private: int value; public: // method - boring! void add(int addValue) { value += addValue; } // overloading operator - much better! void operator += (int addValue) { value += addValue; } }; int main() { ExampleClass exampleObject; exampleObject.add(5); // methods? pfff... get outta here! exampleObject += 5; // overloading operators? much better } Don't worry about the syntax for now. Just know that overloading operators change the behavior of normal operators. Now, the compiler doesn't see it as adding 5 to the object, but rather adding 5 to value. Ready yourself to trash all your getters and setters. The Basics Let's start off by taking a look at the previous example. class ExampleClass { private: int value; public: // method void add(int addValue) { value += addValue; } // overloaded operator void operator += (int addValue) { value += addValue; } }; Notice how the method and overloaded operator are very similar. An overloaded operator starts off with it's return type (it's usually void, itself, or bool), then followed by the keyword operator, then the actual operator itself, and a parameter if required. Then inside the overloaded operator function, just do what you would normally do. Here's another example. class ExampleClass { private: int value; public: // prefix increment // also works for prefix decrement ExampleClass operator ++ () { value += addValue; return *this; } }; This time we overloaded the prefix increment. This means we can do stuff like this: ExampleClass exampleObject; ++exampleObject; Notice how the return type is the object. That's because we use the increment like this: // returns itself, which doesn't really do anything // by itself ++exampleObject; // returns itself, which is needed here // 'std::cout' cannot print a void type std::cout << ++exampleObject; So in the first example, we incremented the object. The object returned itself, but it wasn't being used by anything, so the return type isn't needed there. But, the second example saw us printing the object, which means we needed a return type there. That's why the increment operator needs a return type. Let's look at another example. class ExampleClass { private: int value; public: bool operator > (const int compareValue) { return (value > compareValue); } }; int main() { // ignore syntax shortcomings for now ExampleClass exampleObject; if (exampleObject > 5) std::cout << "is bigger"; } As you can see, this operator overload returns type bool, because it's making a comparison. Also, I added the const there because I'm trying to get into the habit of using const cause... idk, better programming practice? Now hopefully you guys get the jist of things. Now were going to take a look at what we're going to take a look at :) Unary Operator - operates on one value ++ (pre- and postfix) -- (pre- and postfix) conversion types Binary Operators - operates on two values ==, !=, <, >, <=, >= +, -, /, *, % +=, -=, /=, *=, %= [] (subscript operator) () (function operator) Unary Operators Increments and Decrements class squid { private: int legs; public: squid operator ++ () // prefix { ++legs; return *this; } squid operator ++ (int) // postfix { ++legs; return *this; } }; Notice how the return type is the object. This is because we use increments like this: cout << ++value;. If it didn't return anything, then cout would be printing a void value. Conversion Types class squid { private: int legs; public: // converts object to `int` (doesn't have to be `int`, could be whatever you want!) operator int () { return legs; } }; int main() { squid dynamicSquid; cout << dynamicSquid; // this works! int value = dynamicSquid; // this also works! } Notice how the coversion operator just turns the object into an int. It's kinda special since it doesn't have a return type. Oh, and just a side note, the conversion operator is very powerful. In some cases, that's the only overloaded operator you'll need! Because remeber, it takes an object, and turns it into an 'int'. Very useful. Binary Operators Addition Operator class squid { private: int legs; public: squid operator + (int addValue) // same for sub, div, mult, and mod { return legs + addValue; } }; Returns an object for the same reason that the increments return an object. Assignment Operators class squid { private: int legs; public: void operator += (int addValue) // same for sub, add, mult, div, and mod { legs += addValue; } }; Notice how the return type is void. This is because we don't need to return a value when working with assignment operators. Comparison Operators class squid { private: int legs; public: bool operator == (int compareValue) // same for `!=`, `>`, `<`, `<=`, and `>=` { return legs == compareValue; } }; The return type is expected. Subscript Operator class squid { private: string colour; public: const char operator [] (int index) { // this code is incomplete! always make sure you check whether or not the index is withing range! return colour[index]; } }; int main() { squid dynamicSquid; cout << dynamicSquid[2]; } The return type is expected. Function Operator class squid { private: vector<string> types; public: void operator () (string squidType) { types.push_back(squidType); } }; int main() { squid dynamicSquid; dynamicSquid("small"); } Again, doesn't return a type because it doesn't need too. Real Example Okay, now you know what overloading operators are, let's take a look at a real example. #include <iostream> #include <string> #include <vector> using namespace std; class squid { private: string name; public: vector<string> colours; squid(string _name) : name(_name) {} // conversion type - I'm using this for 'cout' operator const char* () { string output = "name: " + name; // converts string to const char* return output.c_str(); } string operator [] (size_t index) { if (index < colours.size()) return colours[index]; } // used to insert elements in 'colours' array void operator () (string squidType) { colours.push_back(squidType); } // used to compare two squids bool operator == (squid compareSquid) { return (name == compareSquid.name); } }; int main() { squid dynamicSquid("Dynamic Squid"); squid fuzzySquid("Fuzzy Squid"); // using the comparision operator if (dynamicSquid == fuzzySquid) cout << "They have the same name!\n"; // using the function operator dynamicSquid("pink"); dynamicSquid("blue"); dynamicSquid("red"); cout << "Here are my favourite colours:\n"; for (size_t a = 0; a < dynamicSquid.colours.size(); ++a) cout << dynamicSquid[a] << '\n'; // this is possible due to conversion operator } Oh, and what's up with all the squids? Well I'm making my own data type actually called "squid" (coming out soon), so yeah... And that's it! Most of the operators you'll ever need. If there's one that I missed, please let me know so I can add it in. And don't forget to upvote :) @DynamicSquid ive been stressing for the past 20 minutes because I have a 5MB file (the linux binary for a fixed version of dusk i need to roll out) that won't appear in the downloaded zip, and my linux dualboot has been borked, so what do I do? (yes, I know, I'll reported this to @amasad but really?) @DynamicSquid Well, to start with we are going to be middlemen (you did a wonderful dusk cdn, could I borrow THAT instead?) @firefish The windows thing works now! Now I have to do linux @DynamicSquid oh ye le zip tiny, oh wait i can create le deb and le rpm (basically upload it to aptitude and yum) If there's one that I missed, please let me know so I can add it in. All logical and bit-wise operators. I'm trying to get into the habit of using const. Nice! I make sure to use immutable data wherever possible. using namespace std; And... I just lost all respect for you! Also, this reminds me of D, which made operator overloading 100x easier, wanna see an example? Oh yeah, I forgot how to code in D... lol :( D > C++ > C I honestly think if the tutorial is too long and not interactive enough, people won't care. I'ma make an interactive C++ tutorial, how about that!? @StudentFires Oh thanks for letting me know, I'll try to add those in soon. Also, I used the standard namespace for readability. I don't use it when I'm actually coding. Also and interactive tutorial? Yeah that'd be great! @DynamicSquid I got the idea off of and they did pretty well. Nice! :) @DangHoang2 thanks!
https://repl.it/talk/learn/Overloading-Operators-in-C/35455
CC-MAIN-2021-10
refinedweb
1,444
56.76
Electric XMLTM is a Java toolkit for parsing and manipulating XML documents. Here are the main features that distinguish Electric XML from other XML toolkits: - It is simple, with an intuitive API. - It is small, packaged as a standalone 64K JAR file. - It is fast. - It is comprehensive, with support for namespaces, XPath and multiple encoding schemes. - It is standards-compliant, with native support for the W3C DOM and SAX interfaces. Electric XML+TM is a superset of Electric XML that includes the following additional features: - Transparent, bidirectional, XML serialization. - Command-line tools for generating Java from XML schema and XML schema from Java. - Unique annotated schema system allows default mappings to be overridden without coding. - Fast transactional persistence for storing Java objects as XML documents. - Flexible, easy-to-use XML pattern matching algorithms with support for constraints. - Electric XML and Electric XML+TM are both free for most commercial uses.
http://www.coderanch.com/t/125368/XML/beginning-xml
CC-MAIN-2015-40
refinedweb
151
50.73
Many Body Physics (Part 1) This is the first article in a series about at least one way to encode many-body quantum mechanics in python (and eventually Haskell too maybe). Why even do this? I think that understanding in principle how to encode the problem concretely into a computer let’s you have a deeper understanding of what the hell is going on. We’re not winning any awards for speed or efficiency here. Intentionally. A low level formulation of all this in C using GPU acceleration or something would be significantly less understandble. Let us unshackle ourselves from too many considerations of efficiency. import numpy as np import matplotlib.pyplot as plt %matplotlib inline So to start, let’s take a few moments to talk a very tiny bit about single body quantum mechanics. It is customary in solid state physics for the purposes of clarification to build simplified models of materials. One simplification is to say that electrons can exist on a lattice of sites with onsite energy $\epsilon$ and tunneling energy $t$. This lattice ultimately corresponds back to the crystal lattice of actual atoms and these mystery parameters can be related back closer (but not entirely. There really are huge gaps of deduction in our understanding of the chain of physics from the most fundamental to the large) to first principles by considering the Hamiltonian matrix elements $<\psi_mH\psi_n>$ of orbital wavefunctions of the atoms. Parametrizing the simplified model this way lets us cut a Gordian knot of complexity. For more info check out. For simplicity, let’s consider a periodic 1-d ring of sites. This is convenient programmatically and mathematically. We can then extend this to greater and greater realism by the inclusion of more realtstic boundaries or try to physically realize such 1-d models in reality using nanowires or other somewhat exotic things. A wavefunction $\psi$ with the particle sitting on the 0th site can be written like so NSites = 6 psi = np.zeros(NSites) psi[0] = 1 print(psi) plt.plot(psi) [ 1. 0. 0. 0. 0. 0.] [<matplotlib.lines.Line2D at 0x7f8ccc0e86a0>] Now let’s build the simple Hamiltonian as an explicit matrix acting on these wavefunctions. The Hamiltonian has the interpetation of giving the possible energies of the particle, but it is also useful as a way of thinking about where states go under time evolution. Any nonzero element $h_{ij}$ is a connection between site i and j. The tunneling element $t$ connects nearest neighbor sites. The periodic nature of the Hamiltonian makes it useful to use the circulant matrix construction function from scipy. from scipy.linalg import circulant eps = 1.0 t = 0.5 firstcol = np.zeros(NSites) firstcol[0] = eps firstcol[1] = t firstcol[-1] = t oneH = circulant(firstcol) #Takes first column and repeats it shifted print(oneH) [[ 1. 0.5 0. 0. 0. 0.5] [ 0.5 1. 0.5 0. 0. 0. ] [ 0. 0.5 1. 0.5 0. 0. ] [ 0. 0. 0.5 1. 0.5 0. ] [ 0. 0. 0. 0.5 1. 0.5] [ 0.5 0. 0. 0. 0.5 1. ]] It is then simple to ask for the energy (eigenvalues) levels of the matrix, or apply it to a wavefunction (which may be part of a single time step for example). dt = 0.1 # a discretized time step dt. I = np.eye(NSites) #identity matrix psi1 = (I - 1.j * dt * oneH) @ psi #@ is python3 notation for matrix product. I like it. print(psi1) plt.plot(np.real(psi1)) plt.plot(np.imag(psi1)) [ 1.-0.1j 0.-0.05j 0.+0.j 0.+0.j 0.+0.j 0.-0.05j] [<matplotlib.lines.Line2D at 0x7f8cc17e3588>] After that, let’s switch gears a bit. A first approach to many-body quantum mechanics is the occupation number representation. The states are labelled by a binary string, with 1s corresponding to filled states and 0s to empty states. For example the binary string 0b010001 would have a particle sitting on the 0th and the 4th site and empty everywhere else. Since you will need 1 bit per site, the total size of the vector space is $2^{# Sites}$. To label the states we’ll need a couple of bit twiddling tricks. A common idiom for getting a bit string with the nth bit set is to bit shift a 1 over by n. bin(1 << 3) '0b1000' n = 1 << 3 | 1 << 4 print(bin(n)) 0b11000 One way to count the number of bits set to one (the total occupation number of the lattice) is to use the following pythony code. bin(n).count("1") 2 However it will be nice to use another method. The Wikipedia article for Hamming Weight (a name for the operation of counting 1s in a binary string) has this code for a 64-bit unsigned integers. This is slightly inflexible and worrisome, however 64 sites using the methodology we’re using is totally impossible, so we might be okay. We’ll need to be careful in the future to cast as uint64 or we’ll get awful bugs unfortunately. This code vectorizes into numpy arrays. #from wikipedia article on hamming weight # works for 64 bits numbers m1 = 0x5555555555555555; #binary: 0101... m2 = 0x3333333333333333; #binary: 00110011.. m4 = 0x0f0f0f0f0f0f0f0f; #binary: 4 zeros, 4 ones ... m8 = 0x00ff00ff00ff00ff; #binary: 8 zeros, 8 ones ... m16 = 0x0000ffff0000ffff; #binary: 16 zeros, 16 ones ... m32 = 0x00000000ffffffff; #binary: 32 zeros, 32 one hff = 0xffffffffffffffff; #binary: all ones h01 = 0x0101010101010101; def popcount64c(x): x -= (x >> 1) & m1; #put count of each 2 bits into those 2 bits x = (x & m2) + ((x >> 2) & m2); #put count of each 4 bits into those 4 bits x = (x + (x >> 4)) & m4; #put count of each 8 bits into those 8 bits return (x * h01) >> 56; #returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ... Since 0 corresponds to the bit string 0b000000, this is the completely empty state, which we may call the vacuum. We need to set the amplitude of this index to 1.0 so that it accounts for the total quantum amplitude of being empty. NSites = 6 NStates = 2 ** NSites def vac(NStates): state = np.zeros(NStates) state[0] = 1.0 return state Now we get to the meat. How do we implement fermionic creation and annihilation operators commonly denoted $a_j^\dagger$ and $a_j$. The operators when applied to a state fill (create a particle) at an empty spot at site $j$, or empty it (annihilate the particle). There is some truly funky business with fermions that we have to anticommute these operators. This is part of the mathematical origin of the Pauli Exclusion principle and has some relation to determinants, which we will see an aspect of later. Don’t get me wrong. These minus signs are weird. To account for them, we pick a canonical ordering for the creation operators, in our case in descending order, for example $a_6^\dagger a_3^\dagger a_0^\dagger |0>$. We only need anti-commute sufficiently to get an operator into it’s canonical position in the expression representing the state for example $a_3^\dagger a_6^\dagger a_5^\dagger a_4^\dagger a_0^\dagger |0> = - a_6^\dagger a_5^\dagger a_4^\dagger a_3^\dagger a_0^\dagger |0> $. It’s complicated and it took me a couple tries to get the binary version of this right. reshapeSite is a convenience function for reshaping the state vector so that the middle index is now specifying the filled or unfilled nature of site n. def reshapeSite(site, state): #returns state reshaped as (leftstatechanges(msb), occupy/unoccupied, rightstatechanges(lsb)) return state.reshape((-1, 2,2**site)) def adag(site, state, copy=True): if copy: state = np.copy(state) state = reshapeSite(site,state) state[:,1,:] = state[:,0,:] state[:,0,:] = 0 state = state.flatten() return antiCommuteFactor(site,state) We haven’t yet seen how to implement the anticommuting factor. This is where we need the Hamming weight function. We need to count the number of occupied states the the left of the particle (bits that are more significant than bit n). This is the number of adag operators we need to anticommute through to put the state into canonical ordering. def antiCommuteFactor(site, state): indices = np.arange(state.size, dtype=np.uint64) rightBinary = indices >> site + 1 # shift out all the bits to the right isOdd = popcount64c(rightBinary) & 0x1 return np.where(isOdd, -1, 1) * state I don’t want to use a bare ‘a’ for the annihilation operator. I used agad. So sue me. Otherwise it is very similar to adag. def agad(site, state, copy=True): if copy: state = np.copy(state) state = reshapeSite(site,state) state[:,0,:] = state[:,1,:] #turns 1 into a zero state[:,1,:] = 0 #nothing comes into the occupied state state = state.flatten() return antiCommuteFactor(site,state) Some other useful routines. A pretty printer avoids printing a bunch of zeros and puts it in bra ket notation. def Num(site, state, copy=True): if copy: state = np.copy(state) state = reshapeSite(site,state) state[:,0,:] = 0 #zero out if unoccupied return state.flatten() def prettyPrint(state,nsites): #avoids printing nearly zero, and puts in ket notation + " return returnstr + "0" Here we can see that alternate orderings of applying the operators give opposite signs out front. state1 = adag(1,adag(0, vac(NStates))) state2 = adag(0,adag(1, vac(NStates))) print(prettyPrint(state1, NSites)) print(prettyPrint(state2, NSites)) 1.0 * |000011> + 0 -1.0 * |000011> + 0 Now using these operators we could implement the application of a Hamiltonian fairly easily. We use the second quantized formulation of the single site Hamiltonian. The sum does it very every possible site. def singleSiteH(i, state): eps = 1.0 t = 0.5 left = (i+1) % NSites #modulo NSites to make periodic return eps * Num(i,state) + \ t * adag(left, agad(i,state)) + \ t * adag(i, agad(left,state)) def H0(state): return sum([singleSiteH(i,state) for i in range(NSites)]) Here we can compare the new way of applying H to the way at the beginning. state = adag(0,vac(NStates)) print(prettyPrint((H0(state)), NSites)) print(oneH @ psi) 1.0 * |000001> + 0.5 * |000010> + 0.5 * |100000> + 0 [ 1. 0.5 0. 0. 0. 0.5] It is now possible to consider the interparticle interactions thought. This is something really new. We can unpack the binary string to a list of positions where it has a 1. def binaryToPositionList(occupation): pos = [] for site in range(NSites): if (occupation >> site) & 0x1: pos.append(site) return pos Given this position list it is striaghtforward to compute the energy of that configuration using a Coulomb $\frac{1}{r}$ potential for example. def V(poslist): U = 0 for i, pos1 in enumerate(poslist): for j in range(i): U += 1.0 / abs(pos1 - poslist[j]) return U In the occupation representation the potential V is actually a diagonal operator. This means we can use element wise multiplication to apply it. def applyV(state): return np.array([V(binaryToPositionList(occ)) for occ in range(NStates)]) * state We can try it out. Indeed the two particles have energy $\frac{1}{4}$ state = adag(4, adag(0,vac(NStates))) prettyPrint(applyV(state), NSites) '0.25 * |010001> + 0' The total Hamiltonian is the sum of the single particle part and the interaction def H(state): return H0(state) + applyV(state) prettyPrint(H(state), NSites) '0.5 * |000101> + 2.83333333333 * |001001> + 0.5 * |001010> + 2.75 * |010001> + 0.5 * |010010> + 0.5 * |100001> + -0.5 * |101000> + -0.5 * |110000> + 0' There we go. That’s a watershed moment! Now, we’ve only given ourselves the power to apply linear operators. True dense representation of the matrices would allow us to ask for inverse and eigenvalues and things. But we can also approach perturbation theory which is designed to use only easy operations like multiplication. We’ll examine that in the next part.
http://www.philipzucker.com/many-body-physics-part-1/
CC-MAIN-2021-10
refinedweb
1,981
57.37
Opened 23 months ago Closed 23 months ago #3628 closed Bug (Fixed) _WinAPI_GetCaretPos() does not work Description _WinAPI_GetCaretPos() is supposed to return an array. It only returns 0. #include <Debug.au3> #include <WinAPIRes.au3> _DebugSetup('Test', True) $aCaret = _WinAPI_GetCaretPos() _WinAPI_ShowLastError() _DebugReportVar('Caret:', $aCaret) Error 998 Invalid access to memory location. AutoIt: 3.3.14.5/X64, OS: WIN_10/X64, OSLang: 0409 @@ Debug(9) : {Int32} -> Caret: = 0 Attachments (0) Change History (2) comment:1 Changed 23 months ago by Jos Last edited 23 months ago by Jos (previous) (diff) comment:2 Changed 23 months ago by Jpm - Milestone set to 3.3.15.1 -. Looks like there is an error in the _WinAPI_GetCaretPos() UDF where the pointer used in the DllCall not the struct created ($tPOINT) but the string with the struct definition ($tagPOINT). COuld you try this update: Jos
https://www.autoitscript.com/trac/autoit/ticket/3628
CC-MAIN-2020-16
refinedweb
139
61.97
Question: I just want to set a node to sleep in "ns-2" and i have searched in protocols and i found a lot of objects and functions about sleep but i couldn't use them in other protocols to set a node to sleep. When i use them i get Segmentation fault or Floating point and i know what these errors mean but i can't find a way to solve them. Like when i use sleep() function from "SMAC". I have searched in google and after a week i still didn't find any solution...! could you guys please help me here...? Solution:1 I have found the solution months ago but i saw this question of mine so i said let's answer it so, people like me that couldn't find the answer until going through all that trouble, could easily find out how to solve it... Well first of all let me introduce you to protocol's codes in ns2. A protocol has been created with 2 main files(there is some protocols with only one file too but i'm talking about the most of them) in ns2 that one of them has .cc type that contains the protocol's name(like AODV.cc) for definition and the other one has the .h type for declaration and it also contains the protocols name(like AODV.h). There could be other files including the protocol but the main is protocolname.cc. We need to change/add some functions in the protocolname.cc so we could simulate our own protocol. For example : We need to use clustering for our protocol : AODV.h : public: AODV(); void CLUSTERING(); ... AODV.cc : void AODV::CLUSTERING(){ if(current_){ while(numberofNodes){ // Selecting clusters } } } Now we know how the mechanism of ns2 works.so let's get started with sleep nodes. First of all there is 4 functions in ns2 for turning a node to 'off', 'on', 'sleep', 'idle'. The difference between these are not so big. As you know the 'off' function turns a node to off but it still broadcasts something based on your protocol. $ns_ at 7.0 "$node(2) off" And you can turn it on like : $ns_ at 7.0 "$node(2) on" The base is : $simulator at $time "$Node_($number) off" I don't know how to set a node to sleep in scenario.tcl but you can do that in your protocol's codes. Now, to set a node to sleep we could do several things... - setting nodes to sleep from energy model - setting nodes to sleep from wireless physics First we'll try energymodel.cc and if it didn't work we'll use the other one. To set a node to sleep from energymodel.cc we can use this code in void Mac802_11::recv function in ns-2.35/mac/mac-802_11.cc : if(index_ == myNode){ EnergyModel *em = netif_->node()->energy_model(); if (em && em->sleep()) { em->set_node_sleep(1); //em->set_node_state(EnergyModel::INROUTE); } } Replace myNode with the number of the interface you want to set it to off. If you are not using MultiInterface for your simulation so the number of interfaces will be equal to the number of your nodes. example : Normal : node ---- > interface ----> channel MultiInterface : ---- > interface[0] -----| | ---------| | v node -------|---- > interface[1] --------- > channel | ^ | ----------| ---- > interface[2] -----| Open a terminal and cd to your ns2 directory, for example if you have ns-allinone-2.35, cd to /ns-allinone-2.35/ns-2.35/ and now type make and inter. After it finished try to simulate your scenario.tcl. Now if your simulation start and you see the nam file, when the nodes get the first packet, the shape of them must change from balck circle to black circle blue hexagon. From then on the nodes must not send or receive any data packet. If this way didn't work now it's the time to use the other option. Go to /ns-2.35/mac/ and open wireless-phy.cc. You'll see that at the end of the file it contains our 4 function that we need. we can simply use those function on the wireless-phy.cc to set a node to sleep or off by just calling those functions.But we may need to use them in another layer like in mac. To use those functions in mac-802_11.cc simply use the below code anywhere you want in mac-802_11.cc and add wireless-phy.cc to your mac headers: #include "wireless-phy.h" // at the header of mac-802_11.cc /* * Use the below code in any function you want in mac */ Phy *p; p=netif_; ((WirelessPhy *)p)->node_sleep(); And to use another one of those 4 function just change the function's name like ->node_sleep(); to ->node_wakeup();. Solution:2 A node can be "Off" and "On" by invoking WirelessPhy::command(int argc, const char*const* argv) of WirelessPhy.cc from Tcl script. To do this, say for Node_(0), once the node is defined in Tcl script, do: set Netif_0 [$Node_(0) set netif_(0)] Note that the variable netif_ is an array and hence we use netif_(0) to get the handle for the first Network Interface. netif_(1) and netif(2)... can be similarly used for Second and Third Network Interfaces, if the node was configured with multiple interfaces. Once the handles are brought to local scope, we can use any command that is defined in WirelessPhy and we can use $Netif_0 NodeOff to switch off the node to deactivate the Network Interface. Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2017/09/ubuntu-how-to-set-node-to-sleep-in-ns2.html
CC-MAIN-2017-43
refinedweb
945
73.68
What's the difference between SOAP and RESTful APIs? Unless you're a programmer, the distinction between SOAP and RESTful APIs can be confusing Application Programming Interfaces (APIs) allow you to access information (data, measurements, etc.) or use third-party services (e.g. sending emails or text-messages) via the Internet. SOAP and RESTful are both APIs and aim to fulfill the same goals, but use different software architecture. Both allow you to build more feature-rich applications - in a shorter timeframe than building everything yourself. APIs are a viable option for minimizing development time. Sometimes APIs are the only viable way to access certain services; sending SMS messages worldwide is a typical use-case. That being said, even if you could avoid using an API by simply implementing a scraper such as BeautifulSoup or PHP Scraper and access information from a website it is not recommended. An API should be your first choice before attempting to access the data using other ways. APIs change less frequently, are generally easier to integrate with and are more stable in long term. What are APIs used for? As the name “Application Programming Interface” suggests, allows you to interface with actions (functionality) within another program. In plain English, this means you can control actions such as creating, updating or deleting an entry within another program or database via the Internet or locally within your own intranet. These other programs are often called “services”, as they provide you with a service. Each functionality of a service is a so-called “API endpoint”. While APIs vary in functionality and scope, there are two main types of APIs: - APIs which provide access to services such as email sending, posting updates, processing of images or video, etc. Also real-world actions like issuing/buying tickets or items are accessible via APIs. - The second type of API provides access to information such as data, statistics measurements, etc. Besides the obvious use as data providers or external services, another advantage is the ability to break your application up into smaller parts. These parts can then interface with another via APIs. This allows you to split a part of your system and reuse it from any part of your system. Following this approach it is possible to increase the scalability and maintainability of your application. This approach can be taken to extremes by developing and hosting so-called microservices. These microservices allow you to abstract any function of your application into its own service. Depending on the nature of your project/application this might be a viable option. Consulting with a solution architect can help you find this out. To avoid costly re-development, the approach should be defined from the get-go in your requirements document. What is needed to work with an API? To use an API and access the service or data provided by it, the software often requires you to obtain an access key to use a set of API endpoints. The key is usually provided after signing up for the service. Access keys can vary in permitted actions and scopes. Your developer needs the access key to integrate the API into your application. Sometimes, services such as RapidAPI allow you to use one key for numerous APIs. And, if the API is not free to use, these services also process payments to API providers for you. From a business point of view, it makes sense to bundle APIs to ensure you are able to switch easily when one service is discontinued or doesn’t serve your needs. It also brings the benefit of easily testing APIs before committing. For any API, checking the documentation to understand the defined interface is crucial. Often API provides open-source libraries to connect to their services. Sometimes you also find an API definition such as the OpenAPI standard. These allow you to use a standard library and configuration file to connect to any API providing such a configuration file Apart from the different purposes of APIs mentioned above, there are also different technical implementations of APIs. In the following we will look more into these implementations: What are SOAP APIs? SOAP is short for “Simple Object Access Protocol” and appeared first in 1998. As the name suggests it was designed as a protocol to access objects (data) within a network. The standard relies heavily on the XML data-format. XML was originally intended to represent various types of documents, but it is also widely used to represent data structures thanks to SOAP APIs. What are RESTful APIs? The “REST” stands for “Representational State Transfer”. RESTful APIs are stateless APIs built on top of the HTTP protocol. This means the HTTP verbs “GET”, “PATCH”, “PUT”, “POST”, etc. are used to trigger actions in web-services. Each verb represents a particular action. JSON is the data format of choice for RESTful APIs. This makes RESTful APIs more performant. HTTP-based Caching can be used by setting the correct response headers. These should always be set pro-actively to ensure there aren’t any unexpected side-effects such as data not being reloaded. What are the advantages and disadvantages of the API types? Fulfilling the same purpose, both APIs are naturally in competition. So what are the advantages and disadvantages of both? SOAP API advantages: - SOAP APIs allow the use of different transport protocols through the Internet. It is built to work with both HTTP(S) and SMTP. This makes it suitable to work behind firewalls accessing the Internet. - Relying on XML, SOAP APIs out-of-the-box support internationalization using character sets defined in various XML namespaces. The only effort involved is ensuring the application behind the API can handle incoming unicode data. RESTful APIs advantages: - XML is, by default, more verbose and requires more effort aggregating, transmitting and, finally, parsing. When using a SOAP API, this makes it slower compared to the same data transferred using JSON on a RESTful API. This gives RESTful APIs the upper hand on the performance side. - RESTful APIs are built on HTTP and allow for caching using the regular HTTP caching methods. While both types have their advantages, in the end your decision needs to be made based on which one is provided to you. Summary As mentioned at the beginning, APIs provide viable shortcuts to reduce development time. If you integrate with APIs - be it SOAP or RESTful - you can shorten the time required to complete your project significantly, because you’re using code written and maintained by someone else. Maintenance is often not considered enough while planning a project.
https://www.my.freelancer.com/articles/web-development/soap-vs-rest-apis
CC-MAIN-2022-27
refinedweb
1,097
56.35
22 April 2009 08:40 [Source: ICIS news] By John Richardson SINGAPORE (ICIS news)--More than 52m tonnes of linear low density polyethylene (LLDPE) film grade have been traded on the Chinese futures market so far this month – in excess of double the global annual demand for the polyolefin. The volume traded on the Dalian Commodity Exchange (DCE) this month up until 21 April was 52.4m tonnes, according to the DCE website. This compares with only 166,330 tonnes during the same period last year and represents a massive increase, most of which has been in the last few weeks. The vast majority is paper trades, as global demand for LLDPE totals less than 24m tonnes/year, according to Paul Hodges, consultant with UK-based International e-Chem. Traders in all grades of polyolefins – as well as producers and buyers seeking to hedge their positions – are playing the market, said a Singapore-based polyolefins trader. “The financial players are also involved, who know little about plastics. They are trading off financial models,” said the trader. Nobody knows to what extent the DCE is influencing the physical market, although there are worries that speculation in general, both in physical and paper trades, has contributed to the rise in pricing. LLDPE was assessed at $1,050-1,100/tonne (€809-847/tonne) CFR China on 17 April, according to global chemical market intelligence service ICIS pricing. This was unchanged from the previous week, but was as much as $110/tonne higher than four weeks earlier. High density polyethylene (HDPE) film grade was also at $1,050-1,100/tonne CFR China and raffia polypropylene (PP) at $1,020-$1,070/tonne CFR China. These prices were again unchanged from the previous week, but PP was up to $170/tonne compared with mid-March. Domestic prices in ?xml:namespace> “I don’t understand why prices are where they are at. If you had told me at the start of the year that polyethylene (PE) and PP prices would be more than $1,000/tonne, I wouldn’t have believed you,” the trader said. Big refinery operating rate cuts by Sinopec and PetroChina in the fourth quarter last year and the first quarter of this year resulted in a naphtha shortage that had driven up petrochemical pricing in general, said a markets analyst with a major polyolefin producer. Extensive cracker and polyolefin operating rate cuts also took place, with many new start-ups delayed in the “This led to a supply gap and a great deal of speculation. I don’t see the current demand fundamentals sustaining the price hikes as plastics processors in The supply gap has been filled by imports with an apparent big rise in shipments from the West. More than 600,000 tonnes of PE was shipped to A similar volume is expected for March, with huge percentage increases in imports recorded by China Customs for all grades of PE and PP in January-February. North American and European producers are reported to have fixed significant volumes to But whether further fixtures will be made for arrival beyond April was not immediately clear. “ “If ($1 = €0.79/$1 = CNY6.83) Please visit the complete ICIS plants and projects database For more information
http://www.icis.com/Articles/2009/04/22/9209934/Heavy-trading-and-high-prices-for-Chinese-polyolefins.html
CC-MAIN-2014-23
refinedweb
543
57.61
Node.js vs Deno: What You Need to Know Free JavaScript Book! Write powerful, clean and maintainable JavaScript. RRP $11.95 Since its announcement, Deno has generated quite a lot of interest within the JavaScript community. As a JavaScript runtime designed by the creator of Node, you might expect there to be be a lot of similarities between the two projects, and there are. However, there are also important differences, meaning you can’t just substitute one for the other. This article will take a look at Deno in relation to its “older cousin” to help understand what they have in common, and what sets them apart. (If you want to get the skinny on Deno first, check out our recent introduction.) Language Support Both projects are JavaScript runtimes, allowing JavaScript code to be executed on a computer outside of a web browser. Let’s look at how they stack up in terms of language support. Node.js The current LTS release of Node (v12.18.1 as of writing) supports modern JavaScript syntax and features. It also supports about 75% of the ES2020 spec. ECMAScript modules are also supported, but are currently only classed as experimental: you need to use the .mjs file extension, or add the property "type": "module" to your project’s package.json file. In order to run TypeScript (or any other language) on Node, the code needs to be compiled to JavaScript that the V8 engine can execute. There are several different ways to do this, with different pros and cons, so getting up and running means having to choose one of these and follow the necessary setup process. Deno I was unable to find any mention of the JavaScript spec supported by Deno, but as it also uses V8 under the hood I would assume a similar level of support as in Node. My own tests show that Deno supports ES2020 features like Promise.allSettled() and the globalThis keyword. ECMAScript modules are the default, with CommonJS modules not supported unless you use the Node compatibility library (more about this later). TypeScript is supported as a first-class language in Deno, meaning that it works out-of-the-box: no installing additional tools to transpile to JavaScript first. Of course, the V8 engine doesn’t support TypeScript natively, so Deno is still transpiling the code under the hood, but this is all seamless and transparent to you as a developer. I also couldn’t find mention of which version of TypeScript Deno v1.0.1 uses, but it supports optional chaining and nullish coalescing (but not private class fields) which would peg it as TS 3.7. APIs Deno and Node both expose their own APIs to developers, allowing us to write programs that can actually do useful things like read and write files, and send and receive network requests. Node.js When Node was first released, there was no built-in support for Promises. As a result of this, most of the APIs for asynchronous operations were written to take an error-first callback: const fs = require('fs'); fs.readFile('readme.txt', (err, data) => { if (err) { // Handle the error } // Otherwise handle the data }); Even though Node developers now have access to Promises and the async/await syntax, the APIs still expect callbacks in order to maintain backwards compatibility. Deno Deno’s API has been designed to take advantage of modern JavaScript features. All the asynchronous methods return Promises. Deno also supports top level await, meaning you can use await in your main script without having to wrap it in an async function. try { const data = await Deno.readFile('readme.txt'); // Handle the data } catch (e) { // Handle the error } The development team also made the decision to use web standards where possible, which means they’ve implemented browser APIs where it’s practical to do so. Deno provides a global window object, and APIs such as addEventListener and fetch. Having access to fetch is particularly nice, as with Node you’d have to polyfill this or use a third-party library. The compatibility module Deno provides a compatibility layer with the aim of allowing you to reuse existing Node packages. It’s not yet complete, but it does currently support loading CommonJS modules via require(), among other things. Package Management Package management is one area where Deno represents a radical departure from Node’s way of doing things. As it’s still early days for Deno, it remains to be seen if its approach will prove to be advantageous. Node.js As you might be aware, Node comes with its own package manager called npm, which is used to install and manage third-party packages. npm is mainly used with the online npm registry, where most of the available third-party packages are listed. When you use npm to install a package into your project, a package.json file is used to specify the package name and acceptable version range. The package itself (plus any packages it depends on) are then downloaded into a node_modules folder inside your project. Deno Deno does away with the need for a package manager altogether. Instead, packages are linked to directly via a URL: import { Response } from ""; On the first run of your code, Deno fetches and compiles all the dependencies. They are then cached on the file system, separately from your project, so subsequent runs are much faster. Similar to npm’s package-lock.json file, Deno allows you to specify a lock file that will be used to ensure that only dependencies that match the exact version you originally imported will be used Third-party Packages A language can thrive or die on the vibrancy of its ecosystem, as productivity relies on not having to reinvent the wheel! Here, it seems that Node currently has the edge. Node.js Node has a large and varied ecosystem of libraries and packages available. In the 11 years since its release, over a million packages have been registered on the npm registry. Of course, the quality can vary a lot, and many are no longer actively maintained, but it’s still a big plus for Node developers. Deno As we saw in the previous section, Deno is actively trying to avoid the need for a package manager or registry, by allowing scripts to import modules directly from any public URL. Of course, it’s hard to import packages if you don’t know what’s out there, so the Deno website maintains a list of compatible third-party modules. As of writing, there are 707 modules in the list. Deno’s standard library One way that Deno attempts to improve the developer experience is by providing a standard library of helpers and utilities for common tasks. All modules are audited by the core developers to ensure high-quality, dependable code. There are modules for things like processing command-line arguments, and colorizing terminal output — both things that are only available as third-party packages for Node. Security Perhaps one of Deno’s most touted improvements over Node is the permissions system. Let’s look at why. Node.js The Node runtime is very permissive, allowing code full access to the computer’s network and file system. There’s the potential for third-party code to wreak havoc on your system if unchecked. Deno Improving the security model is something that Ryan Dahl specifically set out to do when designing Deno. By default, all code is executed in a secure sandbox environment. This prevents code from having access to things like the file system, network, and environment variables unless access is specifically granted with a command-line argument. # Allow script to make network requests deno run --allow-net server.ts Even better, when allowing read or write access to the file system, or access to the network, you can supply a whitelist. This means you could restrict a Deno program’s read/write access to the project’s data folder, for example, limiting any potential malicious damage. Deno: Batteries Included Before we wrap up, I just wanted to talk about one more thing. If you take a browse through the tools section of the manual, you’ll notice that Deno provides us with some nice “bonus features”! The following are built-in tools to make the developer experience that little bit nicer: - bundler: bundles up a specified script and its dependencies into a single file - debugger: allows debugging your Deno programs with Chrome Devtools, VS Code, and other tools (note: Node also comes with a debugger) - dependency inspector: running this on an ES module will list out all of the dependencies in a tree - documentation generator: parses JSDoc annotations in a given file and outputs documentation - formatter: auto-formats both JavaScript and TypeScript code - test runner: you can use this for testing your JS and TS code, in conjunction with the assertions module in the standard library - linter: a code linter (currently unstable) to help catch potential issues in your programs Verdict The purpose of this article is not to advocate for either Node or Deno, but rather to compare and contrast the two. You should now have an understanding of the similarities between the two runtimes and, perhaps more importantly, the differences. Deno presents some particular advantages to developers, including a robust permissions system and first-class TypeScript support. The design decisions and additional built-in tooling are aimed at providing a productive environment and a good developer experience. Node, on the other hand, has a massive and well-established ecosystem around it that’s been over a decade in the making. This, along with the plethora of documentation and tutorials out there, probably makes Node.js a safe bet for some time to come.!
https://www.sitepoint.com/node-vs-deno/
CC-MAIN-2021-21
refinedweb
1,625
51.28
Apache Spark's meteoric rise has been incredible. It is one of the fastest growing open source projects and is a perfect fit for the graphing tools that Plotly provides. Plotly's ability to graph and share images from Spark DataFrames quickly and easily make it a great tool for any data scientist and Plotly Enterprise make it easy to securely host and share those Plotly graphs. This notebook will go over the details of getting set up with IPython Notebooks for graphing Spark data with Plotly. First you'll have to create an ipython profile for pyspark, you can do this locally or you can do it on the cluster that you're running Spark. Start off by creating a new ipython profile. (Spark should have ipython install but you may need to install ipython notebook yourself). ipython profile create pyspark Next you'll have to edit some configurations. Spark/Hadoop have plenty of ports that they open up so you'll have to change the below file to avoid any conflicts that might come up. ~/.ipython/profile_pyspark/ipython_notebook_config.py If you're not running Spark locally, you'll have to add some other configurations. Cloudera's blog has a great post about some of the other things you can add, like passwords. IPython's documentation also has some excellent recommendations for settings that you can find on the "Securing a Notebook Server" post on ipython.org. You'll likely want to set a port, and an IP address to be able to access the notebook. Next you'll need to set a couple of environmental variables. You can do this at the command line or you can set it up in your computer's/master node's bash_rc/bash_profile files. export SPARK_HOME="$HOME/Downloads/spark-1.3.1" Now we'll need to add a file to make sure that we boot up with the Spark Context. Basically when we start the IPython Notebook, we need to be bring in the Spark Context. We need to set up a startup script that runs everytime we start a notebook from this profile. Setting startup scripts are actually extremely easy - you just put them in the IPython Notebook directory under the "startup" folder. You can learn more about IPython configurations on the IPython site. We'll create a file called pyspark_setup.py in it we'll put import os import sys spark_home = os.environ.get('SPARK_HOME', None) # check if it exists if not spark_home: raise ValueError('SPARK_HOME environment variable is not set') # check if it is a directory if not os.path.isdir(spark_home): raise ValueError('SPARK_HOME environment variable is not a directory') #check if we can find the python sub-directory if not os.path.isdir(os.path.join(spark_home, 'python')): raise ValueError('SPARK_HOME directory does not contain python') sys.path.insert(0, os.path.join(spark_home, 'python')) #check if we can find the py4j zip file if not os.path.exists(os.path.join(spark_home, 'python/lib/py4j-0.8.2.1-src.zip')): raise ValueError('Could not find the py4j library - \ maybe your version number is different?(Looking for 0.8.2.1)') sys.path.insert(0, os.path.join(spark_home, 'python/lib/py4j-0.8.2.1-src.zip')) with open(os.path.join(spark_home, 'python/pyspark/shell.py')) as f: code = compile(f.read(), os.path.join(spark_home, 'python/pyspark/shell.py'), 'exec') exec(code) And now we're all set! When we start up an ipython notebook, we'll have the Spark Context available in our IPython notebooks. This is one time set up! So now we're ready to run things normally! We just have to start a specific pyspark profile. ipython notebook --profile=pyspark We can test for the Spark Context's existence with print sc. from __future__ import print_function #python 3 support print(sc) <pyspark.context.SparkContext object at 0x10e797950> Now that we've got the SparkContext, let's pull in some other useful Spark tools that we'll need. We'll be using pandas for some downstream analysis as well as Plotly for our graphing. We'll also need the SQLContext to be able to do some nice Spark SQL transformations. from pyspark.sql import SQLContext sqlContext = SQLContext(sc) import plotly.plotly as py from plotly.graph_objs import * import pandas as pd import requests requests.packages.urllib3.disable_warnings() The data we'll be working with is a sample of the open bike rental data. Essentially people can rent bikes and ride them from one station to another. This data provides that information. You can snag the sample I am using in JSON format here.. Now we can import it. btd = sqlContext.jsonFile("btd2.json") Now we can see that it's a DataFrame by printing its type. print(type(btd)) <class 'pyspark.sql.dataframe.DataFrame'> Now RDD is the base abstraction of Apache Spark, it's the Resilient Distributed Dataset. It is an immutable, partitioned collection of elements that can be operated on in a distributed manner. The DataFrame builds on that but is also immutable - meaning you've got to think in terms of transformations - not just manipulations. Because we've got a json file, we've loaded it up as a DataFrame - a new introduction in Spark 1.3. The DataFrame interface which is similar to pandas style DataFrames except for that immutability described above. We can print the schema easily, which gives us the layout of the data. Everything that I'm describing can be found in the Pyspark SQL documentation. btd.printSchema() root |-- Bike #: string (nullable = true) |-- Duration: string (nullable = true) |-- End Date: string (nullable = true) |-- End Station: string (nullable = true) |-- End Terminal: string (nullable = true) |-- Start Date: string (nullable = true) |-- Start Station: string (nullable = true) |-- Start Terminal: string (nullable = true) |-- Subscription Type: string (nullable = true) |-- Trip ID: string (nullable = true) |-- Zip Code: string (nullable = true) We can grab a couple, to see what the layout looks like. btd.take(3) [Row(Bike #=u'520', Duration=u'63', End Date=u'8/29/13 14:14', End Station=u'South Van Ness at Market', End Terminal=u'66', Start Date=u'8/29/13 14:13', Start Station=u'South Van Ness at Market', Start Terminal=u'66', Subscription Type=u'Subscriber', Trip ID=u'4576', Zip Code=u'94127'), Row(Bike #=u'661', Duration=u'70', End Date=u'8/29/13 14:43', End Station=u'San Jose City Hall', End Terminal=u'10', Start Date=u'8/29/13 14:42', Start Station=u'San Jose City Hall', Start Terminal=u'10', Subscription Type=u'Subscriber', Trip ID=u'4607', Zip Code=u'95138'), Row(Bike #=u'48', Duration=u'71', End Date=u'8/29/13 10:17', End Station=u'Mountain View City Hall', End Terminal=u'27', Start Date=u'8/29/13 10:16', Start Station=u'Mountain View City Hall', Start Terminal=u'27', Subscription Type=u'Subscriber', Trip ID=u'4130', Zip Code=u'97214')] Now one thing I'd like to look at is the duration distribution - can we see how common certain ride times are? To answer that we'll get the durations and the way we'll be doing it is through the Spark SQL Interface. To do so we'll register it as a table. sqlCtx.registerDataFrameAsTable(btd, "bay_area_bike") Now as you may have noted above, the durations are in seconds. Let's start off by looking at all rides under 2 hours. 60 * 60 * 2 # 2 hours in seconds 7200 df2 = sqlCtx.sql("SELECT Duration as d1 from bay_area_bike where Duration < 7200") We've created a new DataFrame from the transformation and query - now we're ready to plot it. One of the great things about plotly is that you can throw very large datasets at it and it will do just fine. It's certainly a much more scalable solution than matplotlib. Below I create a histogram of the data. data = Data([Histogram(x=df2.toPandas()['d1'])]) py.iplot(data, filename="spark/less_2_hour_rides") /Users/bill_chambers/.virtualenvs/plotly-notebook/lib/python2.7/site-packages/plotly/plotly/plotly.py:187: UserWarning: Woah there! Look at all those points! Due to browser limitations, Plotly has a hard time graphing more than 500k data points for line charts, or 40k points for other types of charts. Here are some suggestions: (1) Trying using the image API to return an image instead of a graph URL (2) Use matplotlib (3) See if you can create your visualization with fewer data points If the visualization you're using aggregates points (e.g., box plot, histogram, etc.) you can disregard this warning. That was simple and we can see that plotly was able to handle the data without issue. We can see that big uptick in rides that last less than ~30 minutes (2000 seconds) - so let's look at that distribution. df3 = sqlCtx.sql("SELECT Duration as d1 from bay_area_bike where Duration < 2000") A great thing about Apache Spark is that you can sample easily from large datasets, you just set the amount you would like to sample and you're all set. s1 = df2.sample(False, 0.05, 20) s2 = df3.sample(False, 0.05, 2500) data = Data([ Histogram(x=s1.toPandas()['d1'], name="Large Sample"), Histogram(x=s2.toPandas()['d1'], name="Small Sample") ]) Plotly converts those samples into beautifully overlayed histograms. This is a great way to eyeball different distributions. py.iplot(data, filename="spark/sample_rides") What's really powerful about Plotly is sharing this data is simple. I can take the above graph and change the styling or bins visually. A common workflow is to make a rough sketch of the graph in code, then make a more refined version with notes to share with management like the one below. Plotly's online interface allows you to edit graphs in other languages as well. import plotly.tools as tls tls.embed("") Now let's check out bike rentals from individual stations. We can do a groupby with Spark DataFrames just as we might in Pandas. We've also seen at this point how easy it is to convert a Spark DataFrame to a pandas DataFrame. dep_stations = btd.groupBy(btd['Start Station']).count().toPandas().sort('count', ascending=False) dep_stations 69 rows × 2 columns Now that we've got a better sense of which stations might be interesting to look at, let's graph out, the number of trips leaving from the top two stations over time. dep_stations['Start Station'][:3] # top 3 stations 34 San Francisco Caltrain (Townsend at 4th) 47 Harry Bridges Plaza (Ferry Building) 0 Embarcadero at Sansome Name: Start Station, dtype: object we'll add a handy function to help us convert all of these into appropriate count data. We're just using pandas resampling function to turn this into day count data. def transform_df(df): df['counts'] = 1 df['Start Date'] = df['Start Date'].apply(pd.to_datetime) return df.set_index('Start Date').resample('D', how='sum') pop_stations = [] # being popular stations - we could easily extend this to more stations for station in dep_stations['Start Station'][:3]: temp = transform_df(btd.where(btd['Start Station'] == station).select("Start Date").toPandas()) pop_stations.append( Scatter( x=temp.index, y=temp.counts, name=station ) ) data = Data(pop_stations) py.iplot(data, filename="spark/over_time") Interestingly we can see similar patterns for the Embarcadero and Ferry Buildings. We also get a consistent break between work weeks and work days. There also seems to be an interesting pattern between fall and winter usage for the downtown stations that doesn't seem to affect the Caltrain station. You can learn more about Plotly Enterprise and collaboration tools with the links below:
https://plot.ly/python/apache-spark/
CC-MAIN-2017-17
refinedweb
1,950
64.2
Create new WebApplication Create new tag library Create new tag handler and add the taglibrary import taglibrary into JSP page and use the library tag set breakpoint at the line of usage of the library tag invoke debug JSP, project is deployed, debugger attached, IDE stops on breakpoint invoke "Step Into" once -> nothing happens invoke Step Into few times -> Logger.java file is open and you can debug it while trying to get out of this class Using Set Out, System.java and HashMap.java got openned, but my tag handler got open as probably fifth file, but I was not navigated in the "doTag" method but in the class declaration and I had to press some more Step Out, Step Next, Step Into to navigate to my code in tag handler this is regression - it worked better in 6.5.1 - I need to press Step Into for few times to navigate to my code, but at least no other files from JDK got opened Martin, any idea what could be wrong? Thanks. Created attachment 80221 [details] Application that reproduces this bug I am able to reproduce (with GlassFish v2.1 as the target server). I attached the application that reproduces the issue. When I try Shift-F7, there is an exception, see attached. Created attachment 80263 [details] Stack trace The attached exception is already submitted as issue #162740. I'll try to reproduce and hopefully find out what's wrong... I've reproduced the behavior. This is mostly caused by enabled stepping into JDK classes, which is now on by default. Stepping filters should help here, ClassLoader is correctly skipped, but it looks like the "Step through" option is not correctly interpretted and execution ends up in Logger. Also, the first Step Into goes into the same location, but in the next frame. It looks like nothing has happened, but execution actually stepped into in the Java code that is underneath. Is it possible to see the generated Java code somewhere? If you mean generated code of JSP page, use ViewServlet action on JSP file Yes, thanks. View Servlet was what I need. Having that on a context menu in Editor would be handy. I believe that the major problem was fixed in changeset: 127653:d638dc946f45 You should not end up in JDK code now. However, the behavior is still not perfect, first Step Into ends up on the same line, second goes to the non-existent constructor and finally third goes into the doTag() method. This is a subject of further investigation... Integrated into 'main-golden', will be available in build *200904180201* on (upload may still be in progress) Changeset: User: mentlicher@netbeans.org Log: #162293 - Stepping options are better interpretted, handling of step requests improved. Integrated into 'main-golden', will be available in build *200904201507* on (upload may still be in progress) Changeset: User: mentlicher@netbeans.org Log: #162293 - Stepping options are better interpretted, handling of step requests improved. Is this still P2 after the fix? I tend to downgrade it to P3 now. Jindro, can you please verify it? Thanks. I can verify that the behavior is better than before. Once I was redirected into Class.java file for unknown reason, but it could be threated as P3 for 6.7 After agreement with QE and mentlicher downgrading to P3.
https://netbeans.org/bugzilla/show_bug.cgi?id=162293
CC-MAIN-2015-22
refinedweb
555
64
Timer Class Provides a mechanism for executing a method at specified intervals. This class cannot be inherited. using the Change method.. example demonstrates the features of the Timer class. This example creates a timer, uses the Change method to change its interval, and then uses the Dispose method to destroy; // The following Imports are not required for the timer. They merely simplify // the code. using System.Windows.Controls; using System.Windows.Input; // The Example class holds a reference to the timer, and contains the // event handler for the MouseLeftButtonUp events that control the demo. // public class Example { // The static Demo method sets the starting message and creates an // instance of Example, which hooks up the handler for the MouseLeftButtonUp // event. public static void Demo(TextBlock outputBlock) { outputBlock.Text += "Click to create the timer.\n"; Example dummy = new Example(outputBlock); } // Instance data for the demo. private int phase = 0; private Timer t; public Example(TextBlock outputBlock) { // Hook up the mouse event when a new Example object is created. Note // that this keeps garbage collection from reclaiming the Example // object. outputBlock.MouseLeftButtonUp += new MouseButtonEventHandler(this.MouseUp); } private void MouseUp(object sender, MouseButtonEventArgs e) { TextBlock outputBlock = (TextBlock) sender; if (phase==0) { // On the first click, create the timer. outputBlock.Text += "\nCreating the timer at " + DateTime.Now.ToString("h:mm:ss.fff") + ", to start in 1 second with a half-second interval.\n" + "Click to change the interval from 1/2 second to 1 second.\n\n"; // Create a timer that invokes the callback method after one second // (1000 milliseconds) and every 1/2 second thereafter. The TextBlock // that is used for output is passed as the state object. C# infers the // delegate type, as if you had typed the following: // new TimerCallback(MyTimerCallback) // t = new Timer(MyTimerCallback, outputBlock, 1000, 500); } else if (phase==1) { outputBlock.Text += "\nChanging the interval to one second.\n" + "Click to destroy the timer.\n\n"; t.Change(0, 1000); } else { // On the last click, destroy the timer and shut down the demo. outputBlock.Text += "\nDestroying the timer.\n" + "Refresh the page to run the demo again."; outputBlock.MouseLeftButtonUp -= new MouseButtonEventHandler(this.MouseUp); t.Dispose(); } phase += 1; } // The static callback method is invoked on a ThreadPool thread by the Timer. // The state object is passed to the callback method on each invocation. In this // example, the state object is the TextBlock that displays output. In order to // update the TextBlock object, which is on the UI thread, you must make the // cross-thread call by using the Dispatcher object that is associated with the // TextBlock. private static void MyTimerCallback(object state) { TextBlock outputBlock = (TextBlock) state; string msg = DateTime.Now.ToString("h:mm:ss.fff") + " MyTimerCallback was called.\n"; outputBlock.Dispatcher.BeginInvoke(delegate () { outputBlock.Text += msg; }); } } /* This example produces output similar to the following: Click to create the timer. Creating the timer at 3:40:17.712, to start in 1 second with a half-second interval. Click to change the interval from 1/2 second to 1 second. 3:40:18.820 MyTimerCallback was called. 3:40:19.335 MyTimerCallback was called. 3:40:19.849 MyTimerCallback was called. Changing the interval to one second. Click to destroy the timer. 3:40:20.317 MyTimerCallback was called. 3:40:21.331 MyTimerCallback was called. Destroying the timer. Refresh the page to run the demo again. */ For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.
http://technet.microsoft.com/en-us/library/system.threading.timer(v=vs.95).aspx
CC-MAIN-2014-23
refinedweb
576
60.92
Clang 2.9 fails to link the executable. For example: fads@extensa /tmp $ cat main.c #include <stdio.h> int main (){ printf("Hello, bugzilla!\n"); return 0; } fads@extensa /tmp $ clang main.c -o main -v clang version 2.9 (tags/RELEASE_29/final) Target: x86_64-pc-linux-gnu Thread model: posix "/usr/bin/clang" -cc1 -triple x86_64-pc-linux-gnu -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -main-file-name main.c -mrelocation-model static -mdisable-fp-elim -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -target-linker-version 2.21.1 -momit-leaf-frame-pointer -v -resource-dir /usr/bin/../lib/clang/2.9 -ferror-limit 19 -fmessage-length 170 -fgnu-runtime -fdiagnostics-show-option -fcolor-diagnostics -o /tmp/cc-dkk4Zj.o -x c main.c clang -cc1 version 2.9 based upon llvm 2.9 hosted on x86_64-pc-linux-gnu ignoring nonexistent directory "/usr/local/include" #include "..." search starts here: #include <...> search starts here: /usr/bin/../lib/clang/2.9/include /usr/include /usr/lib/gcc/x86_64-pc-linux-gnu/4.6.1/include End of search list. "/usr/bin/ld" --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o main /usr/lib/../lib64/crt1.o /usr/lib/../lib64/crti.o crtbegin.o -L -L/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/../../.. /tmp/cc-dkk4Zj.o -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed crtend.o /usr/lib/../lib64/crtn.o ) Reproducible: Always The same bug on debians bugzilla The same bug on official llvm bugzilla Created attachment 282355 [details, diff] patch from Sebastian Andrzej Siewior <sebastian@breakpoint.cc> Clang works as expected after applying this patch, and modifying clang-2.9.ebuild: src_prepare() { mv "${WORKDIR}"/clang-${PV} "${S}"/tools/clang || die "clang source directory not found" + # Fix bug #377949, troubles with GCC 4.6 + epatch "${FILESDIR}"/${PN}-2.9-gcc-4.6.patch While you're at it you can also at "4.5.3" to this list. Man, this is broken … Created attachment 282867 [details, diff] Updates the GCC version list for all GCC releases since Clang 2.9 was tagged as of August 8, 2011 Here is a patch that covers GCC 4.4.6, GCC 4.5.3, GCC 4.6.0, GCC 4.6.1 and GCC 4.6.2. I can verify that this fixes Clang linker issues with GCC 4.4.6. I have no reason to think that it won't fix equivalent issues with GCC 4.5.3, GCC 4.6.0, GCC 4.6.1 and GCC 4.6.2. Other people can/should test this, but I think this patch is ready for inclusion into portage. It isn't a big change and anyone with GCC 4.5.3 could verify that this patch fixes the problem. I don't have commit privileges, so I can't commit it myself. It only takes 3 commands to apply this patch to an affected system: ebuild $(equery which sys-devel/clang-2.9) unpack wget -O - "" | patch -d/var/tmp/portage/sys-devel/clang-2.9/work -p1 ebuild $(equery which sys-devel/clang-2.9) merge Created attachment 283263 [details, diff] modifed patch to fix clang's search path I had the same crtbegin.o error in clang and I have gcc version 4.5.3. After applying the patch, clang now works correctly. The patch didn't seem to match the clang directory structure I saw however, so I modified it to match; the modifed patch is attached. Thanks guys, this is now fixed in 2.9-r1. Let's hope upstream will fix this properly at some point. GCC 4.5.4 is unmasked on x64, maybe we should add it to the list. I had to change the patch manually.
https://bugs.gentoo.org/show_bug.cgi?id=377949
CC-MAIN-2022-05
refinedweb
645
63.05
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. Can´t write file on Linux server Hello! A freelancer build a module to write information on a FTP server. He generate the file local and copy after on the FTP. But on my odoo Server the Phyton script can´t write on filesystem: Traceback (most recent call last): File "/opt/odoo/odoo-server/openerp/http.py", line 536, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "/opt/odoo/odoo-server/openerp/http.py", line 573, in dispatch result = self._call_function(**self.params) File "/opt/odoo/odoo-server/openerp/http.py", line 309, in _call_function return checked_call(self.db, *args, **kwargs) File "/opt/odoo/odoo-server/openerp/service/model.py", line 113, in wrapper return f(dbname, *args, **kwargs) File "/opt/odoo/odoo-server/openerp/http.py", line 306, in checked_call return self.endpoint(*a, **kw) File "/opt/odoo/odoo-server/openerp/http.py", line 802, in __call__ return self.method(*args, **kw) File "/opt/odoo/odoo-server/openerp/http.py", line 402, in response_wrap response = f(*args, **kw) File "/opt/odoo/odoo-server/addons/web/controllers/main.py", line 941, in call_button action = self._call_kw(model, method, args, {}) File "/opt/odoo/odoo-server/addons/web/controllers/main.py", line 929, in _call_kw return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs) File "/opt/odoo/odoo-server/openerp/api.py", line 241, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/odoo-addons/ftp_connection/ftp_connect.py", line 60, in create_file f = open(filename, 'w') IOError: [Errno 13] Keine Berechtigung: 'WHOUT00023.txt' It seems not a problem with unsuffient permisson on Linux. It seems that Python cannot write because of odoo. Has some an idea, or need you more code from the python script? Thank you!! If you will save a temporary file better use a named file that is a temporary file so permissions are not involved. if you need the file in an specific folder then you need to check permission for the user that runs Odoo server, but if you will save the file in an FTP location better use a temporary file, I deal with this before. An Example of using NamedTemporaryFile from tempfile import NamedTemporaryFile named_zip = NamedTemporaryFile( suffix=".tmp", prefix="tmp__h2h__", delete=False )# or default True for delete the file after the first use #to get filename named_zip.name named_zip
https://www.odoo.com/forum/help-1/question/cant-write-file-on-linux-server-88221
CC-MAIN-2017-09
refinedweb
419
52.76
. L. OpenID Mini-rant/follow-up: It has almost been two years since I wrote about my issues interfacing with OpenID, and since I have recently been getting deprecation warnings from Google, I finally put in the work to optionally support password authentication. That will teach me to try to do the right thing. Similar Projects to SandboxOS When I started working on SandboxOS, I was somewhat in disbelief that nobody was doing this already. Since then, I have discovered a handful of projects with similar goals, but as far as I can tell, it is still unique enough to continue pursuing. JavaScript Contenders There are a handful of JavaScript-related projects with similarities. node.js + io.js Node.js, and by extension io.js, are essentially another runtime environment similar to those of Perl, Python, and Ruby. node.js popularized using JavaScript outside of the web browser, especially web server-side, allowing web application to be built completely in JavaScript. But ultimately node.js and io.js compete in an already overpopulated niche. SandboxOS is different, because it introduces a security model and an application model. node-os node-os is an operating system built from node.js running on a Linux kernel. This seems to be the result of taking the package manager from node.js, npm, to its extreme and using it for managing all system files. There is not really much comparison with SandboxOS. It is just another interesting projects in the same area. Runtime.JS Runtime.JS is an operating system kernel built using V8 and JavaScript. It is an attempt at eliminating one layer of the stack commonly present in node.js applications. SandboxOS, for better or worse, adds another layer. Linux Container-based Contenders I am not especially familiar with recent developments in Linux containerization. I've gather that it is a step beyond virtualization, allowing some amount of isolation without sacrificing performance. SandboxOS different from all of them in that it attempts to make it easy to host web applications on all sorts of devices - anything where web browsers are found. While I have yet to measure the performance implications, the goal is to move toward having many more servers with many fewer (often just one?) users. Docker / Rocket Docker is the current dominating presence in this area. It appears to be tailored primarily toward sysadmins. Rocket is an alternative being built for CoreOS. Sandstorm Sandstorm is the first project that actually concerned me that I might be stepping on somebody's toes. Their goals are very much aligned with mine, but they're taking a completely different approach, using Linux containerization. Interestingly, Sandstorm does a good job explaining why containers are great, but they don't solve enough of the problem. They aim to make it trivial to run servers and make a better future for open source webapps, and I wish them luck. Editing Apps It may just be because programmers like strange loops, but being able to edit applications from an application which is itself editable is a fundamental assumption in SandboxOS. SandboxOS targets the most devices by far. OLPC Develop Activity I think I first heard such a goal proposed for the One Laptop per Child project. Their Develop activity seemed to be down-prioritized pretty quickly, but it was a neat concept and it is a neat project. Wiki OS I'm not clear on the origins of Wiki OS, but it seems to be an attempt at reproducing a traditional desktop environment on the web on devices where Silverlight can be run, and it allows modifying applications with an interface that I would compare to Visual Basic. Android AIDE I encountered AIDE while in the middle at marveling at how seemingly unnecessarily difficult mobile development is made by the available toolchains. That project puts all of the tools necessary to build Android applications on-device. Decentralization One final theme I am watching for activity on is decentralization. This recent article hints at future tech to decentralize web applications "like BitTorent does" without any information on how that can work. Unhosted web applications are another trend of building web applications without a server component altogether. Conclusion There is a lot of activity in this area. So far, SandboxOS seems to be going in the right direction and not stepping on anybody's toes, so I'm going to charge forward with it! SSPI WTF This is a continuation of TLS WTF. I added SSPI / SChannel support to my list of supported TLS backends. It was not a pleasant experience, so I am taking another moment to document my grievances. SSPI is a shining example of an API that is hard to use correctly. - Microsoft documents that rather than linking against an export library, you must load security.dll dynamically and look up a symbol. - To begin the TLS handshake, you call InitializeSecurityContext or AcceptSecurityContext, depending on whether you are the client or server. The credentials already know which direction we're going at this point, so this seems redundant. - One argument to those functions is a pointer to a handle that is populated when the call succeeds, and a pointer to that handle must be passed back as a different argument on subsequent calls. But not before it succeeds once. - InitializeSecurityContext, AcceptSecurityContext, EncryptMessage, and DecryptMessage all take arrays of input and output SecBuffer structs. After working with two other libraries that had much simpler mechanisms for passing data in and out, this just seemed wrong. - Data is encrypted and decrypted in-place. While it might seem sort of clever, as though it's saving something or destroying no-longer-needed sensitive information, due to the way it works and the lack of any apparent guarantees, I found I needed an extra copy of the data anyway in order to properly restore the remaining unencrypted/decrypted bytes for the next pass. - Each particular type of invocation has special requirements on the number and type of buffers it takes as input and returns as output. It's basically deliberately throwing away all parameter/type safety. Or conversely it's requiring the user to know quite a lot about the specifics of the protocol. - One type of SecBuffer contents that is returned is the number of data bytes passed in that haven't been consumed. But not a pointer to the bytes like every other buffer. - Shutting down a connection is bizarre. Call ApplyControlToken and then proceed as though you're starting a new handshake. I realize only now that I'm doing this incorrectly. - I was pleased that I was pretty quickly able to load a PEM certificate and private key. And then it took me the better part of a day to be able to associate them with each other to be able to use them. - A certificate context (container?) seems to be necessary. There is a way to get an anonymous one, but it doesn't seem to work for this purpose. I haven't found a way to get one if it exists and create it otherwise except by trying one and if it fails, trying the other. - It is necessary to open a certificate store with the name "MY". What? - A property "CERT_KEY_PROV_HANDLE_PROP_ID" on the certificate context looks exactly like what I would want to set to associate a key with a certificate, but it has no apparent effect. "CERT_KEY_PROV_INFO_PROP_ID" is the only one that apparently actually works, but it requires jumping through a bunch more hoops. - All of this leaves some key/certificate data in some system location. I haven't found any way to avoid that. - Most of the API worked with multi-byte or wide characters. One or two functions didn't. - I've completely lost track of which things are opaque data types, handles, pointers to handles, or pointers to pointers to handles. It's out of control. Again, I just hope someone stumbles on this or browser:projects/sandboxos/trunk/src/Tls.cpp, and is saved some of the hassle I went through. I realize I am not done, but I really need to put this aside for now. Some future tasks include: - Support allowing individual certificates whose signing authority isn't otherwise respected (self-signed certificates). - Need to separate the certificate and key setup from the connection. I'm probably adding an awful amount of overhead for each connection by re-importing them each time. - Need to expose error messages. I've just been instrumenting the code as I go to discover what I've been doing wrong, but the actual errors are useful, so I need to make them available. - Need actual tests. - I want to be able to generate self-signed certificates on all platforms. TLS WTF This is my recollection of my misadventures in trying to support TLS for SandboxOS. The Goal I have a JavaScript runtime environment. I want it to be able to do these things: - Run a web server that supports HTTPS to secure or even just obfuscate my traffic. - Connect to web servers over HTTPS to post to Twitter and whatnot. - Connect to XMPP and IRC servers requiring secure connections to run chat clients and bots. I want it to be able to do those things on Linux, OS X, and Windows, and I don't have a very high tolerance for complicated build steps or large dependencies. Background "I want to use SSL," I thought to myself. Apparently what I wanted is called TLS these days. I scratched my head and moved on, because this was the least of my problems. Going in, I knew that OpenSSL had recent vulnerabilities, leading it to be forked into LibreSSL. I knew that GnuTLS was a thing. Outside of that, I did not have much knowledge about what was available. I did some research and found that I should look into Mozilla's NSS as something that could potentially work on all the platforms I cared about. I also learned that if I wanted to support the most common libraries on each platform, I would need to look into SSPI on Windows. I also saw that node.js uses OpenSSL on all platforms. I'm using libuv for doing all of my socket I/O, and I'm pretty happy with it. But it poses a challenge here, because these libraries tend to prefer being used as a wrapper on top of native BSD-style sockets and I didn't want TLS interfering with libuv's event loops at all. I chose to try to pass data around myself in order to avoid that scenario. It looks like NSS creates unnecessary intermediate sockets to abstract away that interface. Getting Started: Build the Libraries I believe it went like this: - Look at Mozilla NSS (Network Security Services). - GPL-compatible license. Good. - Supports the platforms I care about. Good. - Get it and try to build it. They have a non-trivial custom build harness. Not a great sign, but OK. - Try to build it for win32/x64. Discover this note: Note: Building for a 64-bit environment/ABI is only supported on Unix/POSIX platforms. - Looked at the API a bit. It looks like it really wants to be bound to system sockets. That will incur unnecessary overhead the way I want to use it. Lame. - That was enough strikes for me. I wan't about to maintain my own builds of this for three platforms, and I certainly wasn't about to let this constrain me to Win32/x86, if that note was correct. - Look at LibreSSL. - GPL-compatible license. Good. - It looks like the latest release is expected to be usable. Great. - It only builds on Windows through MinGW. Ugg. - By this time I had some OpenSSL code. I tried it on OS X and found that the OpenSSL system library on OS X was supported but has deprecated for some time. Crap. I Wrote a TLS Wrapper I resolved to support OpenSSL on Linux, the Secure Transport API on OS X, and SSPI on Windows, and all in code that could be easily extracted to use for other projects. Currently the entirety of the public API looks like this, though I haven't yet tackled SSPI: class Tls { public: static Tls* create(const char* key, const char* certificate); virtual ~Tls() {} virtual void startAccept() = 0; virtual void startConnect() = 0; virtual void shutdown() = 0; enum HandshakeResult { kDone, kMore, kFailed, }; virtual HandshakeResult handshake() = 0; enum ReadResult { kReadZero = -1, kReadFailed = -2, }; virtual int readPlain(char* buffer, size_t bytes) = 0; virtual int writePlain(const char* buffer, size_t bytes) = 0; virtual int readEncrypted(char* buffer, size_t bytes) = 0; virtual int writeEncrypted(const char* buffer, size_t bytes) = 0; virtual void setHostname(const char* hostname) = 0; }; Implementation Rants I don't know where to begin. - There are not enough good examples. If you are an engineer at Apple who worked on the Security framework, where did you put your ~100 line C file test case that fetches and fails if you try to reach the same server by a different name? - Do not pretend TLS connections are BSD-style sockets. TLS is a terribly leaky abstraction. Socket calls that ought not to block might need to block so that TLS handshaking can finish. New errors can occur at every turn. A TLS session can close without the network connection going away. Stop pretending it's not a separate layer. - Verify hostnames. TLS without hostname verification isn't secure. OpenSSL did not make verifying hostnames easy. The headers I have on debian jessie required me to extract the names from the certificate and do my own pattern matching to account for wildcard certificates. I had several implementations where it appeared the default verification would check names, but only testing showed that it wasn't happening. Apple made it a fair bit easier, but it still didn't happen by default. - So far I have not yet found how to load my certificate and private key from PEM files on OS X without calling this private function from the Security framework:All other attempts I've made at getting a SecIdentityRef from my key and certificate have failed. I could keep them in the login keychain, but I want to support PEM on all platforms for consistency. extern "C" SecIdentityRef SecIdentityCreate(CFAllocatorRef allocator, SecCertificateRef certificate, SecKeyRef privateKey); Results So SandboxOS does what I need for TLS for now. It took me five times longer to write than I had hoped, and doesn't support TLS on Windows yet. It can connect to secure servers. It verifies hostnames when you do that. I can run a secure web server with it. It might be fun to support client certificates, but that is about as far as I want this to go, and that can happen later. I'm hoping somebody searching for some of these words will stumble upon this and either show me how stupid I've been or benefit from browser:projects/sandboxos/trunk/src/Tls.cpp. Update I added SSPI support. Sandbox. Ludum Dare Compo 30 Post-Mortem Recently I took the opportunity to participate in the Ludum Dare 48-hour Game Jam Compo #30. I was overall pretty happy with my last entry, so I took the same basic approach with JavaScript and WebGL. When I learned that the theme was "connected worlds," I decided that Zelda games embodied that theme best in my mind, and I should do my best to riff off of that. I wanted to explore multiple worlds connected in multiple ways. In the end this meant two worlds which you could take rockets between that needed some sort of network connection between then uncovered and repaired. I had meant to build up the dungeon, which is what I called the area starting with the rats, into its own world, and I meant to have one or two Mario-style warp pipes as another means of connecting areas, but I ran out of steam to set up all of that. My changelog this time was only slightly less distraught than last time: 2014-08-23 08:08:09 Connected worlds. 2014-08-23 10:50:46 What am I doing? 2014-08-23 11:30:02 Hrm. Tiles? 2014-08-23 12:42:41 I am the worst at collision. 2014-08-23 12:43:13 Forgotten file. 2014-08-23 14:10:51 Bah, collision.h 2014-08-23 16:14:52 This is...something? 2014-08-23 16:19:49 Fix the end of the line. 2014-08-23 17:24:26 Augh, doors. 2014-08-23 18:37:19 Something about rockets? 2014-08-23 19:21:48 Stubs for lots of levels. 2014-08-23 21:03:13 Fonts and shovels? 2014-08-23 22:10:12 Push the push blocks. 2014-08-24 07:49:19 Minor fixes. 2014-08-24 09:04:29 Rats. 2014-08-24 09:30:28 Yeah, cats. 2014-08-24 09:44:12 It's almost like a puzzle. 2014-08-24 09:57:19 More puzzly. What's up with the wire now? 2014-08-24 10:22:44 Fixes. 2014-08-24 10:57:59 More bombs. 2014-08-24 11:28:55 Something about blcoks. Restarting levels. 2014-08-24 11:29:04 Forgotten file. 2014-08-24 11:29:16 Forgotten files. 2014-08-24 12:02:56 I think everything is wired up? 2014-08-24 12:56:26 More rocket. 2014-08-24 13:28:03 This is really something. 2014-08-24 13:58:28 Finally, the worlds are different. 2014-08-24 14:24:19 Ugg, digg animation. 2014-08-24 14:28:52 Oh man oh man. 2014-08-24 15:32:33 Content content content. Fix fix fix. 2014-08-24 16:00:29 Cats... 2014-08-24 16:20:36 WWW HTTP WWW HTTP 2014-08-24 16:25:57 Faster digging. Wire fix. 2014-08-24 17:28:19 What have I done? 2014-08-24 17:42:30 Some fixes. 2014-08-24 18:05:56 I'm some kind of monster. 2014-08-25 20:49:46 Ported to my arcade cabinet? 2014-08-26 18:40:39 Hide cursor for the arcade cabinet. 2014-08-29 09:11:29 Some optimizations so that I can run this thing on the arcade cabinet better. 2014-08-29 09:38:37 Faster still. The "some kind of monster" comment referred to adding in title music. Results Overall I was pretty pleased with how things turned out. I stopped a few hours early, just because I was tired of staring at it, and I didn't think there was anything dramatic I could change at that point without breaking something. Things that Made Me Happy - Music and sound - I set out to use a ukulele to make all of the sound effects and music for the game. As anticipated, this was one of the last things I did, but I felt like I had enough time to give it an acceptable treatment. I ended up having to tap on my desk for more effect than I expected. - Scale - It takes me about ten minutes to play through the game. It's admittedly rather tedious, and it won't help me with ratings among the 2500+ other entries, but I'm happy that I made something big enough that it can't be fully understood in 15 seconds. - Base code - This time I reused some of the base code from my last entry. This might have easily saved me half a day. Things that Made Me Sad - Collision response - I have written collision response code many times and have reasonable awareness of the problems that come up, but it always trips me up. Every time. This time I went down a path that wasn't working and pretty quickly switched to something naive enough to work. I could use an existing solution next time, but I'd like to come to terms with this, so I will probably continue to try doing it myself. - Fun - I knew the scope of work for this project was going to be significant, but I naively left "making it fun" and "making interesting puzzles" to near the very end (or never). I'm glad I challenged myself the way I did, but it didn't work out like I had hoped it would. - Font - At the end of the first night, I found myself implementing textured font rendering. This seemed like a mistake. It cost me a fair amount of time getting the math right, and I could have spent that time making something else better if I had just use HTML to display text. - Balance - I said I would pay more attention to balance this time, but one of the last things I did was adjust digging speed, and I think this made the game way more tedious than I intended. Conclusion 10/10 would participate again. In the mosaics, my title screen appears in the middle of the parrot's tail and somewhere around Turkey. L. Good Riddance to Google Reader I am a little bit surprised at the response I have seen to Google's announcement that they are shutting down Google Reader. For me, they killed Google Reader in October of 2011 when they broke sharing. A little over a year later, I wrote my own replacement just to get proper sharing again. - I don't want to hear about any silly petition to bring Google Reader back. It was already a husk of what it should have been. If it somehow returned by popular demand, it would not be run and maintained with the care it deserved. Let it go. Find an alternative. - To the multiple projects that claimed you were going to produce a replacement following the crippling sharing, you are the worst kind of projects for giving hope and not following through. Releasing a bad alternative would have been better. Saying "oops, never mind" would have been better. - There is no reason why something like an RSS reader needs to be centralized and run by a big company like Google. Let's see some competition. Applying OpenID I have written a fair number of webapps. They are virtually all quick and dirty things mostly for myself and immediate friends, but there are more than a few. I am pretty sick of implementing authentication. I have two previous go-to approaches to authentication: - Collect a username, password, and email address. The email address is used for password recovery/resets. - Avoid collecting any user data. Generate some random value and stick it on the URL. If someone wants to return as the same person, they need to save that URL. For my last project, I decided to take OpenID for a spin. There is already plenty written on the failings of OpenID. - - - - But my experience was slightly difference from what I have read, so I want to elaborate. Background I wanted to make my webapp, but I knew I wanted to try something like !OpenID for authentication. I say "something like," because going into this, I had no preconceptions about whether OpenID, OAuth, or some other proprietary thing I had never heard of was what I wanted. That probably should have been enough to stop me. I decided I would be using OpenID via python-openid. As far as I can tell, the included examples are the only documentation of that library. The django example did not help me much, as I was not using django and am not very familiar with it. I focused mostly on consumer.py, but it has a number of configurable parameters that only confused me, and I did not find it helpful at all that it only functioned as a standalone web server. I fought with it for a while and eventually ended up with something which purported to authenticate me. I also found and hooked up a reasonably nice frontend for encouraging people to use well-known providers. Surprises I eventually went on to work on actually implementing my web app and started showing it to people. Several things happened. These things surprised me. Authentication is not a place where I want to be surprised. - People associate authenticating with third parties with leaking information from those third parties. - My app deals with RSS feeds. People authenticated with their Google accounts. People were disappointed that their Google Reader RSS feeds did not show up. - People do not like leaking information. I'm not sure why, but whenever I see "login with Facebook" or similar stuff, I tend to close the tab and move on. - I misinterpreted what guarantees !OpenID was making. I may still be doing so. The biggest example of this is that Google returned a different ID depending on the realm I specified. - I initially had generated the realm from the HTTP request, which meant that the domain people used to get to the site and whether they included a trailing slash on the URL would cause them to authenticate as different users. - I experimented with moving the site to a different host, but that would have required changing the realm and therefore somehow re-authenticating everybody. Results This little adventure was not all failure. It is still in operation, and people use it. Probably the coolest thing to me is that I am storing so little personal identifying information. In general, I would say that people should care about this more than they do. I store OpenIDs. I store no email addresses. Names are optional. If someone gets access to the database, they get a list of Google OpenID URLs that are specific to my site and therefore pretty worthless. Google tends to remember that I have logged in, so I can get into my site just by clicking on the Google provider logo. But OpenID has not really solved any problems I have, and it has been a big hassle to integrate correctly. Passing. :) Tank Xing I was observing someone make a tiled terrain system earlier in the week, and I was reminded of an old project of mine: Tank Xing. Much to my shock, I didn't have a build of it handy, and I couldn't so much as find any screenshots. I remedied this today. A brief write-up as well as binaries are available here. The relevant part to my original recollection is the function Terrain::generateTexture, which takes a height map and picks textures for each tile, inserting a border of hand-crafted transition textures between particular different heights. The result looks something like this. Uh, disregard the texture sampling issues in between tiles. It doesn't look like much. I never made any better art than some colored checkerboard textures to test it. It was nifty, to me, at the time.. Map Statistics Speed Graph. Winter Simulator 1.1 We had a snow day from work today, which prompted me to update Winter Simulator. Plus I can link to it in the Android Market now that it is finally web-accessible. Changes were minor, adding on-screen controls and icons. I suspect some people tried the previous version, could not get it to do anything cool, and immediately removed it from their devices. Now it's pretty obvious what it can do as long as people poke at the visible icons. I would also like to elaborate on the porting process, having brought several of my old OpenGL 1.x/GLUT demos to Android NDK. Getting a skeleton application working went relatively smoothly, working from the documentation and hello-jni example. The source to Winter Simulator can be explored here. The Java portion does minimal work to set up an OpenGL viewport and then forwards GLUT-like events to the C++ part. I reused essentially the same Java code for several projects, now. In Gingerbread I will supposedly be able to create C++-only applications, but I don't want to limit distribution to only phones with the latest OS, and this was easy enough. My biggest problem was the difference between the version of OpenGL I had been using and OpenGLES. It was some relief when I realized OpenGLES 1.0 existed, as it shielded me from having to completely redo all of my code to use shaders and my own matrix code. Things that failed to build included: - All of the drawing code. I didn't have GLUT solids. I didn't have GLU quadrics. I used both heavily. - Everything STL-related. I didn't have STL. - I had only glColor4f, not glColor3f. Fog was different. There were a handful of other things that I just had to change slightly. I addressed the simple things and did the more complicated things one at a time. For all drawing code, I had previously hard-coded immediate-mode commands to do most of what I wanted, often using GLU and GLUT primitives to assemble complex shapes like trees and cabins out of cylinders and cubes. I looked into either libraries available for Android or grabbing GLU and GLUT code to run on the phone. Neither appealed to me, so I ended doing something quite strange. I pasted all of my drawing code into a python script and started implementing missing methods. The syntax use between my C++ code and Python was close enough that I didn't have to make many changes to get it executing. The most annoying part was stripping the trailing f off of floating point constants. I then naively implemented all of the functions I needed to support my drawing code. I made all of the immediate mode GL commands generate vertex buffer data and output a C++ source file with big blobs of data and the code to draw that data. I implemented the basic solids I needed by drawing them out on paper and making slow Python code to generate the triangles. The code didn't need to execute efficiently. It was a one-time process and generated relatively efficient vertex buffers. That all took some effort, but it was quite easy to approach incrementally, and the end result is just what I wanted. Parallel. Continuous Integration The end of the year is for reminiscing, right? I recently discovered I have more old projects sitting around gathering dust than I remembered. A handful are documented on this page, but quite a few are missing. I also discovered that almost all of them fail to build with recent compilers. First step: continuous integration. I opted for Bitten for Trac for a few reasons. Trac has hardly ever let me down. Bitten seems to have been developed in the same vein with a similar set of developers, so it's more likely to just work in my environment and have surprisingly cool integration with other parts of this web site. We use Zutubi Pulse at work, but not only is it overkill, but I don't want to deal with the license, and I'm not thrilled with everything about how it works. In the end, my needs are pretty minimal, so pretty much anything will do. My next step was getting things building. This was for the most part pretty easy. Problems across all projects have been pretty consistent so far. I had some heinous invalid code that previous versions of gcc let slide but recent versions rejected. I'm using SCons 2.0.1 instead of 0.9.6, which is what I used previously. I also had a ton of missing #includes. This change demonstrates a little of all of that. My next step was to expand into some of the non-Linux platforms that I had previously supported. This was kind of tricky, because I don't own any computers running Windows or Mac OS X. A quick poll of friends directed me toward VirtualBox, and it wasn't too long before I had Windows 7 Home Premium 64 Bit and Mac OS X Server / Snow Leopard running. My first confusion came from documentation not lining up with what I was seeing. It looks like new versions of VirtualBox use RDP to give access to otherwise headless systems. The version I started with used VNC. Not a big deal, but when I ran into other problems, the uncertainty of whether I was doing anything right didn't help. I ended up upgrading to the latest 4.0 build, and things seemed to be working until I noticed that both of my machines were hanging from time to time. I didn't resolve this before realizing that I hadn't gained anything but instability since 3.2.8, so I downgraded, juggled some files to get it to use the virtual machine I had created in the newer version, and now things seem to be working better. Remaining issues with the virtual machines: - I haven't found the right VNC graphical quality balance between sluggishness and being able to see the screen without terrible artifacts. - The mouse in OS X is badly behaved. It doesn't follow my cursor in the VNC client. - The OS X virtual machine won't boot off of its disk. I need to use a boot ISO which I also needed to use to kick off the installation. - I haven't yet rigged them to start themselves automatically when the host machine boots and to log in to the client OS and start the bitten slave script. Probably some other things, too. But my intention is to just let them be for a while. I got multiple branches of Notebook Ninja building on Windows. I found Flag Fu was the project with the most interesting configuration that I could get running on all three platforms the most easily. It builds a client, server, and editor, depending on what libraries are available, and now I have that working again on Linux, OS X, and Windows. This is still far short of what I want to do: - Everything I'm building should be packaged up and shared in binary form. - I'm still missing a bunch of projects. - I'm still missing easily supportable platforms for a bunch of projects. - I should have documented all of the setup I had to do on the build machines to get each project building. At the very least, list required libraries. - I haven't done much runtime testing of anything on Windows or OS X. - I don't have any sort of nightly or otherwise regular builds, so this won't really prevent bit rot, but bitten developers are aware of the desire for that feature. Summary: There's a Build Status link at the top right there. It's neat! Winter Simulator Seven years ago, in a computer graphics class at RPI, I tried to make my last project winter-themed and highly demo-able. I think I wanted to submit it for a NeHe contest, but I never did. I took some time recently and ported it to Android. The original project lives here. Source and executables are attached to that page. Here is a link to it in the Android Market: Note: The controls are terrible. It's pretty ugly. But I did it in a short time in college and ported it in just a few days. Vicarious Visions Game Jam At work, we had our first ever game jam last Saturday. It's hard to share my team's resulting game, so here's a video: After the 14 hours, I was exhausted, and it seemed like everything we had worked so hard on had fallen apart. Minutes before the judging we were able to quickly fix some bugs, and I'm pretty happy with the results. It may not look it, but it was a substantial effort to arrive at this from what we started with (not much). The lesson I took away from this is that the ideal length of time for making a game is less than a year and more than a day. I propose game jams of every length in between to find the sweet spot. Pin Map I got it in my head that I wanted a map with all of the places I've gone kayaking. I wanted not just a Google Maps map but a physical map on my wall where I could mark off places and see the big picture in person. I got a cork board and the biggest state map I could easily find. Upon closer inspection, the map I got was not at all what I wanted, and I couldn't find any better. I know the USGS makes lots of map data available, but after playing with their web site for some time, I just couldn't figure out how to get what I wanted, and they kept wanting me to put things in shopping carts to download them. Bleh. I ended up using Google Maps. I remember reading that Google gets their topographical data from USGS anyway, so I didn't feel bad about stealing it. Here's how it went. I went to Google Maps, zoomed into the rough area I was interested in at the zoom level I thought I wanted, and opened resource tracking in Google Chrome to get the URL for one of the map tiles. The parameters in it were obvious enough. I wrote this code: from urllib2 import urlopen import os from PIL import Image from StringIO import StringIO def get_tile(x, y, zoom=12): path = os.path.join('tiles', '%d,%d,%d.jpg' % (x, y, zoom)) if os.path.exists(path): tile = open(path).read() else: url = '' % (x, y, zoom) print 'Fetching', url tile = urlopen(url).read() open(path, 'wb').write(tile) return Image.open(StringIO(tile)) tl = (1203, 1500) br = (1218, 1510) tile_width = 256 tile_height = 256 tiles_wide = br[0] - tl[0] + 1 tiles_high = br[1] - tl[1] + 1 width = tile_width * tiles_wide height = tile_height * tiles_high mosaic = Image.new('RGBA', (width, height)) for x in range(tl[0], br[0] + 1): for y in range(tl[1], br[1] + 1): tile = get_tile(x, y) mosaic.paste(tile, ((x - tl[0]) * tile_width, (y - tl[1]) * tile_height)) mosaic.save('mosaic.jpg') I fetched a block of tiles, being sure to cache them on disk so I wasn't hammering Google every time I reran my script. With my starting tile set, it was a quick matter of trial and error to get the exact area I wanted. It didn't take much code with PIL to combine the tiles into one big JPEG. Next I needed to print the big image on a bunch of sheets of paper as big as I could for my cork board. I used PosteRazor to accomplish this without much hassle, though there are a handful of other similar tools available. I did some arts and crafts, cutting out the prints and taping them together. Then I started throwing in some pins, using big red pins to mark my launch points and small black pins to mark roughly the maximum distances I went from the launch points. The end result: Not too shabby. Needs more pins in it!
https://www.unprompted.com/projects/blog/category/code
CC-MAIN-2020-29
refinedweb
6,556
73.58
Chapter 7 Chapter 7 Expressions An expression tells JavaScript what to do with the data you provide. For example, an expression can be used in an if statement to test for a certain condition -- if the user's name is Fred, for instance, the script displays a personalized message just for him. Everyone else gets a standardized greeting. Expressions are also used to perform basic math functions using JavaScript (additional math functionality is provided with the JavaScript Math object, detailed in Chapter 4, "Objects.") For example, a typical expression adds a value to another value stored in a variable. In this way, JavaScript can keep track of what's going on around it, storing important information it might need later. This chapter describes using expressions in JavaScript, including expressions to create variables, expressions for use in conditional statements (like if), and expressions for use in math calculations. Creating Expressions An expression tells JavaScript what you want to do with information given to it. An expression consists of two parts: - One or more values, called operands - An operator that tells JavaScript what you want to do with these values. Sounds complex at first, but all we're really talking about is 2+2. In JavaScript programs, expressions can be used when defining the contents of variables, as in Test1 = 1+1; Test2 = (15*2)+1; Test3 = "This is" + " a test"; JavaScript processes the expression, and places the result in the variable. Expressions can also be part of a more elaborate scheme using other JavaScript constructs. Used in this way, expressions provide a way for your scripts to think on their own (although they may seem to act on their own more than you'd like them to!). Expressions are most commonly used with the for, if, and while JavaScript statements. Following is a list of operators, and how they are used to construct expressions. Most of the operators work with numbers only, but some can also be used with strings. The list is divided into three parts: - Assignment operators, which assign values to variables - Math operators, which apply to number values only, with one exception - Relational operators, which apply to both numbers, and some of which apply to strings. In all cases, you substitute the operands v1 and v2 as your values or variables, as described below. Assignment Operators These operators assign values to variables. You are likely to only use the = assignment operator for the bulk of your JavaScript programs, but it's nice to know the others are available in case you need them. If you're new to the concept of variables be sure to read Chapter 9, "Variables." Additional assignment operators are provided for bitwise operations. These are detailed separately in "Using the Bitwise Operators", later in this chapter. Using the = (Equals)Assignment Operator Use the = (equals sign) assignment operator whenever you wish to assign a new value to variable. If the variable previously contained a value, that value is replaced. Examples: MyStringVar = "This is a string" // assign text to variable MyNumverVar = 100 // assign number to variable MyObjectVar = document.form[0] // assign document.form[0] object to variable Using the Shorthand Assignment Operators The shorthand assignment operators let you add, subtract, multiply, and divide values to values already in a variable. The most commonly used shorthand assignment is +=. - If the value in the variable and the value to append are numbers, += adds the values. - If the value in the variable and the value to append are strings, += combines them into one long string. A number example: Var = 1; Var += 5; // Var now contains 6 Another way you could write the above: Var = 1; Var = Var + 5; A text string example: Var = "Java"; Var += "Script"; // Var now contains "JavaScript Another way you could write the above: Var = "Java"; Var = Var + "Script"; The remaining shorthand operators let you subtract, multiply, and divide values. - x = val for subtracting x times val. Equivalent to x = x - val. - x *= val for multiplying x times val. Equivalent to x = x * val. - x /= val for dividing x into val. Equivalent to x = x / val. - x %= val for dividing x into val, leading the remainder (modulus). Equivalent to x = x % val. Examples (the variable Val contains 5 in each case): Val -= 3 // result: 2 Val *= 3 // result: 15 Val /= 3 // result: 1.666 (etc.) Val %= 3 // result: 2 Math Operators These operators perform math calculations with one or more numbers. The + operator is dual use. When used with numbers, the + operator adds them together. When used with strings, the + operator connects the strings (called concatenation) and makes them one. The ++ and -- operators (borrowed from C, C++, and Java) can be used in a number of ways. The most common is v1++ where you increment the value already in v1 by 1. (Similarly, the instruction v1-- decrements the value already in v1 by 1.) You can actually use the ++ and -- increment/decrement operators before or after the value. - When used after the value (postfix), JavaScript returns the original value, then increments. Example: Var++ or Var--. - When used before the value (prefix), JavaScript increments the value and returns the incremented result. Example: ++Var or --Var. Suppose the Var variable contains the number 10. In each of the following Var is incremented by 1. But the RetVal variable will contain different values, because of the order JavaScript uses in incrementing and returning the value. RetVal = Var++ // returns 10 RetVal = ++Var // returns 11 The similar postfix/prefix technique works with the -- decrement operator. RetVal = Var-- // returns 10 RetVal = --Var // returns 9 Relational Operators Relational operators compare two values to see if they are equal, not equal, greater than, or less than (and sometimes a combination of these). Relational operators are also known as Boolean or true/false operators. Whatever they test, the answer is either yes (true) or no (false). For example, the expression 2==2 would be true, but the expression "2==3" would be false. How to Use the && (AND) and || (OR) Relational Operators The && and || (AND and OR) operators work with numbers and expressions that result in a true/false condition. They are not used with strings, unless the strings are a part of a true/false expression. JavaScript balks if you try to use the operators with a string alone. For example, the following is not allowed. This = "Java"; That = "Script"; Result = This && That; This results in an error. Instead of combining the This and That variables into Result, JavaScript responds with a not-too-kind error message. As you've read earlier in this chapter, the correct way to combine the two strings is to use the + operator, as in This+That. - Use the && (AND) operator to determine if both values in an expression are true. If both A AND B are true, then the result is true. But if A or B is false, then the result of the AND is false. - Use the || (OR) operator to determine if either value in an expression is true. If at least one of them is true, then the result is true. Only when both values are false is the result of the OR expression false. It's helpful to view the action of the AND and OR operators with the use of something called a "truth table." The table shows all the possible outcomes given to values in an expression. Truth values are shown for Boolean true and false, and also for the numeric digits 0 and 1. JavaScript's Boolean operators work the same with either kind of value. (Note: In JavaScript, true/false values are distinct from 1/0.) AND Truth Table OR Truth Table Using the AND and OR Operators in More Complex if Expressions A common use of the && (AND) and || (OR) relational operators is in if expressions (and also in expressions using the while statement). These expressions are sometimes built to test for one of several conditions, or a number of conditions together. When at least one of the conditions is true, that portion of the script is complete and JavaScript proceeds to the next. An example: if (Var1 == 100) { isTrue(); } else if (Var1 == 200) { isTrue(); } else if (Var1 == 300) { isTrue(); } else { isFalse(); } The structure of the routine is referred to as OR logic. If Var1 is equal to 100 OR 200 OR 300, the script executes the isTrue function. Any other condition causes the script to execute the isFalse function. Many of the scripts in this book revolve around OR logic for if expressions. What if you want to build expressions that executes the isTrue function only if ALL of the conditions are met? This structure is more commonly called AND logic, and it can be easily done in scripts by moving the instructions around a bit. Following are four test scripts that you can use to experiment with the operation of AND and OR logic. The following examples show how to create AND and OR logic by using multiple if statements, as well as using the && (AND) and || (OR) operators. You will find that in general, using the AND and OR operators is the easier method. You can practice with all four examples by including them in the following script: <HTML><HEAD> <TITLE>And/Or test</TITLE> <SCRIPT> function doTest() { // insert AND/OR script segment here } function isTrue() { alert ("It is true") } function isfalse() { alert ("It is false") } </SCRIPT> </HEAD> <BODY> <FORM> <INPUT TYPE="button" VALUE="Test" onClick="doTest()"> </FORM> </BODY></HTML> AND -- Separate if Statements var Var1=1, Var2=1; if (Var1 == 1) { if (Var2 == 1) isTrue(); else isFalse(); } else isFalse(); OR -- Separate if Statements var Var1=1, Var2=1; if (Var1 == 1) { isTrue(); } else if (Var2 == 1) isTrue(); else isFalse(); AND -- Single IF Statement var Var1=1, Var2=1; if ((Var1 == 1) && (Var2 == 1)) isTrue(); else isFalse(); OR -- Single if Statement var Var1=1, Var2=1; if ((Var1 == 1) || (Var2 == 1)) isTrue(); else isFalse();Important! Be sure to format the expression with parentheses and brace characters (the { and } characters) as shown; otherwise JavaScript might have trouble parsing it into a meaningful function. Here's an example of a real-world application of OR/AND in testing the response from the user. RetVal=prompt("Go again (Y/N)?", "Y") if ((RetVal == "Y") || (RetVal == "y")) alert ("You pressed Y or y") The && (AND) and || (OR( operators are not limited to if expressions. Here is an example of how to use the AND operator in a while loop. The example ensures that the value entered at the prompt dialog box is between 100 and 200. CtrlLoop=true; Value=0; while (CtrlLoop) { Value=prompt ("Enter a value between 100 and 200", Value); if ((Value>=100) && (Value<=200)) CtrlLoop=false; } alert (Value) The ! (NOT) Operator The ! (NOT) operator is used whenever you want to negate a true or false expression. The statement !true becomes false, and !false becomes true. Ordinarily, you use this to reverse the outcome of an expression that results in a true/false answer. You might want to test if a certain condition is NOT met, so you can write a more efficient if statement (you can also apply the ! (NOT) operator in for and while loops for additional flexibility. Let's try an example of the ! (NOT) operator. Suppose you want to ask the user to respond to a prompt. You do not want them to respond with a blank entry, so you write the following code to allow your JavaScript to redisplay the prompt dialog if the entry blank is, er, blank. Notice also the extra if statement that determines if the user chooses the cancel button. This returns a null value, and the loop ends with a break statement. CtrlLoop=true; Value=""; while (CtrlLoop) { Value=prompt ("Type something", Value); if (Value == null) break; if (Value != "") { CtrlLoop=false; alert (Value) } } Using the ? Conditional Expression Statement JavaScript supports an alternative method to creating conditional expressions. It is a "shorthand" method used in C and some other languages, and is useful if you want to construct a quick and simple test. The syntax is: (condition) ? istrue : isfalse - condition is the expression you want to test - istrue is what happens if the condition is true - isfalse is what happens if the condition is false Note: You must include statements for both the true and false outcomes, and include the colon character. For example the following displays an alert box depending on what you type in response to the prompt box: Ret = prompt ("Type something or click Cancel", ""); (Ret == null) ? alert ("You clicked cancel") : alert ("You typed: "+Ret);While the conditional expression can aid as a shortcut, I personally feel it makes for hard-to-read code. The logic of the if statement, though a bit more "bulky," is generally easier to decipher, especially when reading other people's scripts. Of course, adopt or ignore the JavaScript conditional expression as you choose. The Bitwise Operators JavaScript supports a unique operators that work with numbers only. These are the bitwise operators, because they actually deal with the individual bits that make up each number. The bitwise operators have only occasional use in JavaScript programs. If you have a programming background, the following operators may be of use to you in creating more complex scripts. The bitwise operators are: For example, the following displays 8, which is the value of 2 when shifted to the left four bits (binary 10 to binary 1000): Temp = 2; Temp = Temp << 2; alert (Temp); Using the Bitwise Operators Bitwise operators manipulate numbers one bit at a time. Suppose you put a 9 into variable This and 14 in variable That. Use the bitwise AND operator with them and you get 8 as a result. In the following discussion, I use the words AND, OR, and XOR to denote the names of the bitwise operators, rather than their symbols as used in a script: &, | and ^. Refer to the tables earlier in this chapter for the AND and OR truth tables. Notice what happens when you AND two binary digits together (recall that a binary digit is a 0 or a 1). Only when both digits are a 1 does the result equal 1. All other instances the result is 0. That's where the name AND comes in: "If A AND B..." With the logical OR expression, the output is 0 when both input digits are 0. In all other instances, the output is 1. Finally, with the logical XOR (which means eXclusive OR) expression, the output is 1 if either digit is a 1, and the other is a 0. But if both digits are a 1 or a 0, then the output is 0. To visualize how JavaScript come up with a result of 8 when it ANDed the numbers "9" and "14" together, you have to reduce those numbers to their binary equivalents. Using the truth table, manually compute what happens when you AND these two numbers together. 1001 = 9 1110 = 14 AND ____ 1000 = 8. Decimal Number Binary Equivalent 0 0000 1 0001 2 0010 3 0011 4 0100 5 0101 6 0110 7 0111 8 1000 9 1001 10 1010 11 1011 12 1100 13 1101 14 1110 15 1111 How can bitwise operations be used in a JavaScript program? One way is to combine more than one numeric value in a single variable, then use the AND bitwise operator (&) to determine what numbers are in the variable. This process uses "powers of two" numbers; that is, 1, 2, 4, 8, 16, 32, 64, and so forth. Each of these numbers contains a single 1 bit; the other bits are 0. Consider for example the numbers 2, 8, and 16. Here are the binary representations of these numbers: Number Binary Equivalent 2 00010 8 01000 16 10000 Add these numbers together, and you get 26 (2+8+16). The binary equivalent of 26 is 11010. Notice that there's a 1 in the binary equivalent for every 1 in the numbers that were summed. This is very important. Now comes the task of finding out what powers-of-two numbers are contained in 26. This is done by ANDing the number with 26. Let's take each powers-of-two number in turn to see what the result is. If the answer is 0, then the powers-of-two number used in the expression is not part of the value 26. 00001 = 1 11010 = 26 AND ____ 00000 = 0 -- no match 00010 = 2 11010 = 26 AND ____ 00010 = 2 -- a match! 00100 = 4 11010 = 26 AND ____ 00000 = 0 -- no match 01000 = 8 11010 = 26 AND ____ 01000 = 8 -- a match! 10000 = 16 11010 = 26 AND ____ 10000 = 16 -- a match! As you can see from the above tests, the answer is 0 for the values that are not contained (1 and 4) within the number 26. The other tests result in the same number used as the testing value. Now for a practical use. Suppose you want to pass a single variable to a user-defined procedure you have created. This function displays any of a combination of four messages in a JavaScript alert box dialog box. You specify which message you want to appear by using the values 1, 2, 4, and/or 8. You can use these values, or add them together if you want to show multiple messages. function test () { Ret=showMessage (15); alert (Ret); } function showMessage (MessageVal) { OutputString = "\n"; if (MessageVal & 1) OutputString += "You've just won a million dollars!\n"; if (MessageVal & 2) OutputString += "Payment will begin next Monday!\n"; if (MessageVal & 4) OutputString += "We'll pay you in cash!\n"; if (MessageVal & 8) OutputString += "You will be audited by the IRS!\n"; return (OutputString); } Some example single message results: MessageVal String 0 Nothing 1 You've just won a million dollars! 2 Payment will begin next Monday! 4 We'll pay you in cash! 8 You will be audited by the IRS! Some sample multiple message results: MessageVal Strings 3 You've just one a million dollars! Payment will begin next Monday! 10 Payment will begin next Monday! You will be audited by the IRS! Note: A MessageVal of 15 displays all four messages. Operators and Strings Recall that in a JavaScript program a string is any assortment of text characters. You can't perform math calculations with text, but you can compare one string of text against another. With the exception of && (AND) and || (OR), the relational operators can be used with strings for the purpose of comparing them. For instance, you may want to see if two strings are the same, as in: if ("MyString" == "StringMy"); This results in false, because they are not the same. In a working script, no doubt you'd construct the string comparison to work with variables, as in if (StringVar1 == StringVar2); JavaScript compares the contents of the two variables, and reports true or false, accordingly. JavaScript considers the case of the characters when you compare strings. The strings must match exactly, including the case of the string. Examples: While the == (equals) operator is used extensively in comparing strings, you can use !<, !>, <, >, <=, and >= as well. The != (not equal) operator is an obvious choice -- you can use it to check if one string is not equal to another. But why the others? Don't they check if one value is greater or lesser than the other? How can one string have "less" or "more" value than the other? The < and > operators do indeed test for greater than and less than, and while they will work with strings, they don't work in exactly the way you may think. Strings -- whether they are composed of one character or many -- have a numeric value in JavaScript. - If there is one character in the string, the value is the ASCII equivalent of the character. For example, the ASCII equivalent of the letter "A" is 65. - If there is more than one character in the string, the value is a composite of the ASCII equivalents of all the characters. String comparisons using the < and > operators are not often used, except when performing certain special operations, like sorting. See Chapter 13, "Plug and Play Routines," for a sort routine that uses comparisons to put strings in alphabetical order. Multiple Operators JavaScript can handle more than one operator in an expression. This allows you to string three or more numbers, strings, or variables together to make complex expressions, such as 5+10/2*7. With this feature of multiple operators comes a penalty: You must be careful of the order of precedence, the order in which JavaScript evaluates an expression. Like many programming languages and electronic spreadsheets programs, JavaScript doesn't merely start at the left side of the expression and calculate to the other side. Rather, it calculates multiplication and division first, then addition and subtraction, and so forth, following a general left-to-right progression.. Here is the order in which JavaScript evaluates an expression, from highest to lowest: JavaScript doesn't distinguish between operators on the same level or precedence. If it encounters a + for addition and a - for subtraction, it will evaluate the expression by using the first operator it encounters, going from left to right. You have to be careful, though, and discern the difference between subtraction and a number that you have identified as negative. As you can see, you can get some wild results if you let the "natural" order or precedence JavaScript uses take control. You can specify another calculation order by using parentheses. Values and operators inside the parentheses are evaluated first. You can write complex expressions using parentheses inside other parentheses. JavaScript always starts at the innermost parentheses, and works outward, such as Ret=2*((45+2)/10) This expression is evaluated as follows (the answer is 9.4, with rounding). - Add 45 plus 2 - Divide the result obtained in step 1 by 10. - Multiply the result obtained in step two by 2. Logical (true/false) expressions also use parentheses to control the order of evaluation. Controlling the order of evaluation is particularly important in logical expressions, as leaving out parentheses, or using them incorrectly, can cause JavaScript to evaluate a true expression as false, and vice versa. The general syntax is ((true/false test1) && (true/false test2)) Note the parentheses around the two true/false tests, and a third set around everything. JavaScript doesn't mind if you put extra spaces between the parenthesis of your expressions. An expression with ( ( is just as valid as ((. The spaces can help you visualize the structure of the expression. Use whatever method is the most comfortable for you. Here is the basic rule of thumb for setting the order of precedence for logical expressions: Each complete logical expression should be enclosed in its own parentheses. You can then apply additional logical operators. The entire expression is then enclosed in parentheses for the script state (if, while, for, etc.). Examples: // If MyVar equals 10, AND YourVar equals 30, then true if ((MyVar == 10)&& (YourVar == 30)) // If either Path or MyPath is "", then true if ((Path == "") || (MyPath == "")) // If Name is either "Fred" or "John," then true if ((Name == "Fred") || (Name == "John")) Revised: October 29, 1996 URL:
http://www.webreference.com/content/jssource/chap7.html
CC-MAIN-2017-17
refinedweb
3,867
62.88
1.4 Beta -); - marceltrapman Mod last edited by ")); - marceltrapman Mod last edited by. I think we agree. Only problem is that I haven't split up the structure in mysensors-transportation/mysensors-header/mysensors-payload yet but if you look from the sniffer side this would not matter. Please post you suggested structure (but in a new thread). I got this question from a friend and since I dont know the answer either; I'm trying to figure out the sleep mode and if the radio module wakes up or not (via INT pin 2) .. but for me it does not seam to do this. Which sleep-modes does 1.4b have and how do I see if the message is for me, and if not continue sleep? The radio interrupts is not used at the moment. It uses the following sleep modes LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); or LowPower.powerDown(SLEEP_XXXXS, ADC_OFF, BOD_OFF); Depending on if you want timer to wake up or not. Radio is always put to sleep. For more details, check out MySensor.cpp. I'm trying to create my own controller in Node-Red. My setup is as followed: Motion Sensor arduino with standard example sketch <--> SerialGateway arduino with standard example sketch <--> USB <--> Node-Red (installed on Raspberry PI) My SerialGateway receives the request for a node ID (255;255;3;0;3;) I then return a serial command: 255;255;3;0;4;1 You can see my Node-Red output below: For some reason my SerialGateway is not broadcasting my command. It's only repeating the above commands sevral times; Am i using the correct protocol values or is there something else I should do? My Node-Red is configured to send a newline after every command. But just to make sure I also tried adding it to the string. Same result. If it's working from your gateway Serial Monitor in IDE you must be doing something wrong in your program. Got it working, but my solution is not very satisfying. I swapt the sketches on my 2 arduino's. Original arduino setup was: SerialGatway - Arduino pro mini 3.3v (including Decoupling-Capacitor) Motion Sensor - Arduino Uno (including Decoupling-Capacitor) Now the sketches are switched and it works. Eventually I will be working with only Arduino pro mini's but still the original setup should have worked. @warawara did you try clearing using clear eeprom? That helped me some times. Dont really know why some nodes just wont want to recieve packages.. @Damme Thanks for the tip. I will try that in the future. But I don't think it was a problem of not receiving on the sensor part. I think it was a problem with not sending on the Serial Gateway part. But I got it working now! Ok, So I took the plunge and upgraded to 1.4.b1, and everything went "OK" with one glaring exception...... All temperatures display in Celsius. No matter what I do, I can't seem to get it to display in Fahrenheit.. Any Idea's? @hek I'd like to ask for a small change to be made to the sleep function. When we call gw.sleep(x) or gw.sleep(x,y,z) then the arduino disables the interrupt timer (to save power) that triggers the counter that drives millis(). So the value returned from millis() stalls when we sleep. This is ok on our battery powered devices, since it's saving power, but makes it hard to determine how long it's been since we sent values to the gateway. For example, if I use this code: if ((unsigned long)(millis() - timeOfLastSensorSend) >= MIN_SAMPLING_INTERVAL) { // read sensors and send to gateway timeOfLastSensorSend = millis(); } gw.sleep(SLEEP_TIME); Then it doesn't work because millis() does not increment while the the sketch is asleep. I have a thought on how we can solve this but I have a to get to a work meeting. Ok, back from meeting. So, for sketches that don't need to sleep on interrupt, then things are ok because I can code around it like this: if ((unsigned long)(millis() - timeOfLastSensorSend) >= MIN_SAMPLING_INTERVAL) { // read sensors and send to gateway timeOfLastSensorSend = millis(); } gw.sleep(SLEEP_TIME); timeOfLastSensorSend -= SLEEP_TIME; My rationale here is that if millis doesn't increment then I should make my variable decrement by the same amount. Same effect. However, the catch is when sleeping with interrupt. My thinking was to modify MySensors.cpp to change the return value of sleep. Something like this: unsigned long MySensor::internalSleep(unsigned long ms) { unsigned long origMs = ms; while (continueTimer && ms >= 8000) { LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF); ms -= 8000; } if (continueTimer && ms >= 4000) { LowPower.powerDown(SLEEP_4S, ADC_OFF, BOD_OFF); ms -= 4000; } ... if (continueTimer && ms >= 16) { LowPower.powerDown(SLEEP_15Ms, ADC_OFF, BOD_OFF); ms -= 15; } return (origMs - ms); } unsigned long MySensor::sleep(unsigned long ms) { // Let serial prints finish (debug, log etc) Serial.flush(); RF24::powerDown(); continueTimer = true; return internalSleep(ms); } unsigned long MySensor::sleep(int interrupt, int mode, unsigned long ms) { // Let serial prints finish (debug, log etc) unsigned long sleptFor = 0; Serial.flush(); RF24::powerDown(); attachInterrupt(interrupt, wakeUp, mode); //Interrupt on pin 3 for any change in solar power if (ms>0) { continueTimer = true; sleptFor = sleep(ms); } else { Serial.flush(); LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); } detachInterrupt(interrupt); return sleptFor; } So rather than return a boolean on sleep(x,y,z), return the amount of time it slept for before it was interrupted. The check of the boolean is replaced with a check if return code > 0. Hopefully my ramblings make some kind of sense. @ServiceXp The sensor fetches the unit setting from Vera at startup. Something probably fails during this data exchange. You'll have to look at the debug logs to see what happens. This behavior might change in 1.4 with sensors just reporting SI-units and controller makes the necessary conversion/scaling. @hek This is the first time I've ssh into vera, so I have no idea what I'm looking for.. I have 2 Everspring ST-814's that display correctly, and of course 2 MySensor sensor which did in 1.3, but not in 1.4b1. I found this, but not sure if this is what you need. 02 08/22/14 7:47:04.914 luup_log:87: Arduino: Incoming internal command '0;0;3;9;read: 2-2-0 s=1,c=1,t=0,pt=7,l=5:22.6' discarded for child: nil <0x2f8b3680> 50 08/22/14 7:47:04.916 luup_log:87: Arduino: Set variable: 2;1;1;0;0;22.6 <0x2f8b3680> 50 08/22/14 7:47:04.916 luup_log:87: Arduino: Setting variable 'CurrentTemperature' to value '22.6' <0x2f8b3680> 50 08/22/14 7:47:04.916 luup_log:87: Arduino: urn:upnp-org:serviceId:TemperatureSensor1,CurrentTemperature, 22.6, 92 <0x2f8b3680> 06 08/22/14 7:47:04.917 Device_Variable::m_szValue_set device: 92 service: urn:upnp-org:serviceId:TemperatureSensor1 variable: CurrentTemperature was: 22.5 now: 22.6 #hooks: 3 upnp: 0 v:0xda4620/NONE duplicate:0 <0x2f8b3680> 01 08/22/14 7:47:04.918 LuaInterface::CallFunction_Variable func: w_switch Device_Variable 92 urn:upnp-org:serviceId:TemperatureSensor1:CurrentTemperature failed [string "..."]:14: bad argument #1 to 'sub' (string expected, got nil) <0x2f8b3680> 01 08/22/14 7:47:04.919 LuaInterface::CallFunction_Variable func: w_switch Device_Variable 92 urn:upnp-org:serviceId:TemperatureSensor1:CurrentTemperature failed [string "..."]:14: bad argument #1 to 'sub' (string expected, got nil) <0x2f8b3680> @ServiceXp The node will be transferring celsius data until it manage to receive settings from controller (this is done in the background) by setup(). Attach your failing sensor to the computer. Upload sketch with debug enabled. And look at the Serial monitor. Restart a sensor a few times . Thanks, I'll do that when I get home later. Just so I'm clear.. To enable debugging: I Remove the "//" before the #define DEBUG ** in and ONLY in** the /libraries/MySensors/Config.h file ? Then upload the sketch again to the sensors? (I don't have to upload the gateway sketch also do I?) @ServiceXp Yes correct! I can only find MyConfig.h file, and DEBUG was already without the "//". So I noticed something VERY strange. It seems when I have the sensors connected to the computer, they start reading in Fahrenheit, and once I pull the USB cable it reverts back to Celsius with-in 30-60 seconds.. Yep, I have no idea how to debug this. The debug window reads in Fahrenheit, (and in Vera), but 30-60 seconds after I disconnect the usb cable from my computer (at which point I can't use the serial com window) it reverts back to Celsius. I've deleted one of the sensor nodes and child from Vera, cleared the eEPROM and re-install sketch and re-incuded back into Vera... I just don't understand why it works while connected to my computer... @ServiceXp No, this seems strange. The unit settings should get stored in eep); }
https://forum.mysensors.org/topic/168/1-4-beta/100
CC-MAIN-2019-09
refinedweb
1,496
59.19
yeah I'm searching on the Internet to see if I find anything. What about saving a word that the user inputs to the dictionary file? How can I do this? yeah I'm searching on the Internet to see if I find anything. What about saving a word that the user inputs to the dictionary file? How can I do this? This part of the code searches for every word in the text file and saves it to an ArrayList. It searches for the word if its valid of not. How can I offer a list of similar words when the word... Can I load two files like this? package spellChecker.project1; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.HashSet; When you say list do u mean something like this? List<String> list = new ArrayList<String>(); Yes the code reads the lines from the file. I'm stuck on the second part I don't know how to code and put each word in the list. Can you show me how this is done please? Thank you to be honest I don't know what I'm doing Ive tried everything but nothing seems to be working. I've tried to understand how to read the words and store them in the list but I don't know how to do... How can I read each line into a set<Sting>? The words are stored line by line, the file contains all the words in the dictionary. ok so I read the first file like shown below but how do I separate out the words and save them in a collection ? spellChecker.project1; import java.io.FileNotFoundException; import... I think Ive done this wrong what it suppose to do is ask the user to enter a name of a file and for every word in that file i need to check if the word is contained in the file. :-s How can I do this? sorry if I sound annoying but I'm trying to learn at the same time. If you could show me a small example I think I would understand better. I think this code is easier to read but how can I check if the word is contained in the file? package spellChecker.project1; import java.io.FileNotFoundException; import... No it does not execute I'm still trying to fix that error that you picked up. At what line would i need to test the length of the array using the .length attribute? Thanks for your help. Would the above code work to help me check for a word in a file or offer similar words that the user inputs. Hello guys, I'm creating this small JAVA programme thats checks for a word in the dictionary but when I run it I get an error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0...
http://www.javaprogrammingforums.com/search.php?s=4acbb94b779904a5425db9c0775c44da&searchid=1461148
CC-MAIN-2015-14
refinedweb
483
83.25
This tutorial will teach you the fundamentals of building Android interface layouts with XML. Read on! When you’re getting started with developing Android apps using Eclipse and the ADT plugin, Eclipse’s powerful graphical layout editor is a great place to start visually designing your user interface. However, this "what you see is what you get" approach has its limitations, and at some point you'll need to switch to XML. One of the major benefits of declaring your UI in XML is the ability to keep the UI and the behavior of your app separate, giving you the freedom to tweak your app’s presentation without disrupting its underlying functionality. In this article, I’ll show you how to design a basic XML layout from scratch, including defining the root element, specifying height and width parameters, and adding some basic UI elements. Finally, I’ll use this basic layout to demonstrate some advanced XML options, such as allocating different amounts of space to different objects, and getting started with string resources. Note: In Android, XML layouts should be stored in the res/layout directory with the .xml extension. Part 1: XML Layout Basics First, we’ll get used to XML by creating a very basic Android UI that uses the LinearLayout view group to hold a checkbox element. Open the res/layouts/activity_main.xml file and let’s get started. Step 1: Specify Your Root Element The UI must contain a single root element that acts as a visual container for all your other items. The root element can either be a ViewGroup (i.e LinearLayout, ListView, GridView) a merge element or a View, but it must contain the XML namespace. In this example, I’ll be using LinearLayout, a ViewGroup that aligns all children in a specified direction. A LinearLayout consists of opening and closing XML tags: < LinearLayout ....... > In the opening tab, you’ll need to define the XML namespace, which is a standard recommended by the W3C. Defining the XML namespace in Android is easy, simply enter the following code and URL as part of the opening LinearLayout tag: xmlns:android="" Step 2: Width and Height Next, specify the width and height parameters for your root element. In most instances, you’ll use the "fill_parent" value for the root element, as this instructs it to take up the device’s entire screen. Enter the following XML for the height/width parameters: android: Your XML should now look like this: <LinearLayout xmlns:android=”” android:layout_width="fill_parent” android:layout_height="fill_parent” > </LinearLayout> Step 3: Creating a Checkbox It’s time to add something to that blank canvas! Enter the opening tag for your checkbox. Because this is a UI element, some additional XML is required: 1) Identify Your Item Eclipse uses an integer ID to identify different UI elements within a tree. This should be referenced as a string, using the 'id' attribute and the following syntax: android:id="@+id/name" In this example, we’ll refer to this UI element as 'CheckBox:' android:id="@+id/CheckBox" 2) Width/Height Parameters: wrap_content Once again, you’ll need to enter the height/width parameters. Setting this attribute to ‘wrap_content’ will display the corresponding item large enough to enclose the content resize. We can re-use the height/width syntax structure from earlier, replacing 'fill_parent' with ‘wrap_content:’ android:layout_width="wrap_content" android:layout_height="wrap_content" 3) Set Your Text Finally, you’ll need to specify the text that should appear alongside the checkbox. We’ll set the checkbox to display 'Yes': android: Your XML should now look like this: <LinearLayout xmlns: </LinearLayout> Run your code in the Android Emulator to see your XML in action! Part 2: Create Your Second UI with XML In the second part of this tutorial, we’ll look at some more advanced XML for fine-tuning your UI. We’ll create a layout consisting of two buttons, and then use the 'weight' attribute to change the percentage of layout space allocated to each before briefly covering the basics of string resources. Step 1: Create Your Layout The first step is to create the barebones of your layout. We’ll re-use the LinearLayout root element from the previous example, along with the width/height parameters and, of course, the XML namespace: <LinearLayout xmlns: </LinearLayout> Step 2: Create Your Buttons To create the first button, add the 'Button' opening tag, and the integer ID using the element name 'button1.' <Button android:id="@+id/button1" Set the width and height attributes to ="wrap_content." We’ll be creating a 'Yes' and a 'No' button, so specify 'Yes' as the accompanying text: android:text="Yes" Finally, close button1: /> Now you have the code for one button, you can easily create another by making a few adjustments: 1) Change the ID to 'button2' 2) Specify that the text should be 'No' (android:text="No") Your XML should now look like this: <LinearLayout xmlns: <Button android: <Button android: </LinearLayout> Step 3: Check the Emulator To preview how this will look on a real-life Android device, boot up the emulator and take a peek! Part 3: Advanced XML Options Now you have your basic UI, we’ll use some more advanced XML to refine this simple layout. Set Layout_Weight The 'android:layout_weight' attribute allows you to specify the size ratio between multiple UI elements. Put simply, the higher the weight value, the greater proportion of allocated space, and the more the UI element expands. If you don’t specify a weight, Eclipse will assume the weight for all items is zero, and divide the available space up equally. The space ratio can be set with the following XML: android:layout_weight="?" In this example, we will assign ‘button1’ with a value of 1, and ‘button2’ with a value of 2. Note, this is purely an addition; you do not need to change any of the existing code. <LinearLayout xmlns: <Button android: <Button android: </LinearLayout> The above XML will create two buttons of different sizes: An Intro to String Resources A string resource can provide text strings for your application and resource files. In most instances, it’s good practice to store all your strings in the dedicated ‘strings.xml’ folder, which can be found by: 1) Opening the ‘Res’ folder in Eclipse’s project explorer. 2) Opening the ‘Values’ folder. 3) Opening the ‘strings.xml’ file. To create a new string in your Android project: 1) Open the ‘strings.xml’ file and select ‘Add.’ 2)Select ‘String’ from the list and click ‘Ok.’ 3) Select your newly-created string from the ‘Resources Elements’ menu. 4) In the right-hand ‘Attributes for string’ menu, enter a name for the string, and a value (Note, the ‘name’ attribute is used to reference the string value, and the string value is the data that will be displayed.) In this example, we will give the string the name of ‘agree’ and enter the value ‘I agree to the terms and conditions.’ 5) Save this new string resource. 6) Open your ‘activity_main.xml’ file. Find the section of code that defines ‘button1’ and change the ‘android:text’ attribute to call this new string resource. Calling a string resource, uses the following syntax: android:text="@string/name-of-resource" So, in this example, the code will be: android:text="@string/agree" For ease of viewing the output, delete ‘button2.’ Your code should now look like this: <LinearLayout xmlns: <Button android: </LinearLayout> Check the visual output of your code - the text should have been replaced with the value of your ‘agree’ string. This is a very basic string, without any additional styling or formatting attributes. If you want to learn more about string resources, the official Android docs are a great source of further information. Conclusion In this article, we’ve covered the XML essentials of creating a root element for your layout and coded a few basic UI elements, before moving onto some more advanced XML that gives you greater control over your UI. You should now be ready to create your own simple user interfaces using XML! Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/getting-started-with-xml-layouts--mobile-12749
CC-MAIN-2018-22
refinedweb
1,367
58.21
Microsoft.SqlServer.Management.Smo.Wmi Namespace Updated text: 17 July 2006 The Microsoft.SqlServer.Management.Smo.Wmi namespace contains all the classes that represent the SQL Server Windows Management Instrumentation. The classes in this namespace do not require a connection to an instance of SQL Server. The classes in this namespace control the SQL Server service and the SQL Server Agent service as represented by the Server class and the JobServer class. In effect, WMI is hierarchically above the SMO Server class. The WMI classes are also used to set the network protocols and libraries for client and server installations of SQL Server. The Microsoft.SqlServer.Management.Smo.Wmi namespace resides in the Microsoft.SqlServer.Smo.dll assembly file. Also, some of the enumeration classes are in the Microsoft.SqlServer.WmiEnum.dll assembly file. You will have to import both files to access the classes in the Microsoft.SqlServer.Management.Smo.Wmi namespace. By using the Microsoft.SqlServer.Management.Smo.Wmi namespace, you can do the following: Stop, start, and pause both the instance of SQL Server and SQL Server Agent. Set protocols, network libraries, and IP address information for SQL Server services and clients. Manage SQL Server aliases.
http://technet.microsoft.com/en-US/library/microsoft.sqlserver.management.smo.wmi(v=sql.90).aspx
CC-MAIN-2013-48
refinedweb
199
51.34
1.) Willingness to learn 2.) Know the basics of a computer Instructions: Before we begin your going to need a program to start programming with go to you will be presented with a bunch of downloads, but should download you one that is presented in this picture and you will know which is the right one to download. Assuming you have done the installation process we can now begin ! Part 1.) Let's begin: Before we begin, you should have Eclipse open and start a New project Then we're going to need classes which i will explain later When creating classes, we allways need 1 main class so the project knows where to begin Once were done we should automatically have what looks like this Part 2.) Lesson: Here are some things you should know before you continue onto our exercise! Definitions: Variable - is a facility for storing data. Class - Java is class-based programming, which refers to the style of object-oriented programming in which inheritance is achieved by defining classes of objects. Primitive data types: int - aka Integer, you've probably heard if you have ever been in a Math class but in programming it's a little bit different. It can be a negative, neutral or positive number. been in a Math class but in programming it's a little bit different. It can be a negative, neutral or positive number. String - Is basically a string of words or letters example: "Hello world!" example: "Hello world!" Boolean - Your probably thinking "Wow boolean thats a weird word". It really just has one of two values; true or false. It really just has one of two values; true or false. Note* - There are more data types but they will not be discuss as this is a begineer lesson. Statement structure: A class is made up of a bunch of different statement, the structure for creating a statement goes like this... (data type) (variable name) = (data value); Your probably woundering what the ";" semicolon is doing there, in Java we allways end our statements with semicolon. An example of assignment statements are: int tax = 10; String str = "Hello world!"; Strings should allways have quotations marks around them. To print something to the console to the user can see it we type "System.out.println();" and inside the parenthesis we have what we want to display. Part3.) Exercise: Let's begin making our very first console program ! This is a prime example of a very simple console program named "Hello world!" Input: public class NameOfClasshere { public static void main(String[] args) { int anumber = 10; String hi = "Hello World! "; // Creating a variable named "hi" that hold the text "Hello world!" System.out.println(hi + anumber); // Calling "hi" and "anumber" variable to display to the user } } Output:
http://www.dreamincode.net/forums/topic/158905-introduction-to-java-with-eclipse/
CC-MAIN-2017-30
refinedweb
464
63.59
The interviewer asked me how to find the entrance in the linked list. I thought it was simple but I wanted to be silly on the spot The question of whether there is a link in the linked list seems simple, but there are a lot of things to pay attention to in actual handling. This question is a very high-frequency written test interview question. If the memory is not strong, it is easy to forget. You can take a serious look at the study! A small partner met in a certain hand interview. Determine whether the linked list has a ring Title description: Given a linked list, determine whether there are loops in the linked list. If there is a node in the linked list that can be reached again by continuously tracking the next pointer, there is a ring in the linked list. If there is a ring in the linked list, return true. Otherwise, it returns false. Can you solve this problem with O(1) (ie, constant) memory? Analysis: For this problem, if there is no memory space limitation, the first thing that comes to mind is to use a hash method, use a hash storage node, and then enumerate the linked list nodes down: If it is found to be in the hash, then it means that there is a ring and return true. If the enumeration ends at the end, then there is no loop But this does not meet the O(1) space complexity requirement, how should we deal with it? If there is a loop at the end of the linked list, and if a node is enumerated later, it will continue to enumerate in a closed loop. How can it be efficiently judged that there is a loop and can be terminated quickly? There is a ring. In fact, it is the second or third time to walk this way to say that it has a ring. A pointer cannot effectively judge whether there is a ring without using too much space in the storage state (the list may be very long, it may be already in the cycle), we can make use of the speed of the pointer (the double pointer) ah. The core idea is to use two pointers: fast and slow. They both traverse the linked list from the head of the linked list at the same time, but the speed of the two is different . If there is a ring, it will eventually meet in the circular linked list. In our concrete implementation, we can use fast pointers (fast) to take two steps at a time, and slow pointers (slow) to take one step at a time. If there is a ring, the fast pointer enters the ring first, and then the slow pointer enters the ring. The fast pointer will catch up with the slow pointer before the slow pointer reaches the end. If the fast and slow pointers meet, it means there is a ring, if the fast pointer is null first, it means there is no ring. The specific implementation code is: /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { ListNode fast=head; ListNode slow=fast; while (fast!=null&&fast.next!=null) { slow=slow.next; fast=fast.next.next; if(fast==slow) return true; } return false; } } Improve: find the entrance to the ring Given a linked list, return the first node where the linked list starts to enter the loop. If the linked list has no rings, null is returned. In order to represent the rings in a given linked list, we use the integer pos to indicate the position where the end of the linked list is connected to the linked list (the index starts from 0). If pos is -1, then there is no ring in the linked list. Note that pos is only used to identify the ring, and will not be passed to the function as a parameter. Note: It is not allowed to modify the given linked list. Can you solve this problem using O(1) space? This question is a bit more difficult than the previous one, because if the linked list is in a loop, you need to find the entrance. analysis: If you don't consider memory usage, I will definitely consider hashing first, save the node and then if it appears a second time, it means that there is a loop and return directly. The implemented code is also very simple, and you can use this method if you are desperate: /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { int pos=-1; Map<ListNode,Integer>map=new HashMap<ListNode, Integer>(); ListNode team=head; while (team!=null) { if(map.containsKey(team)){ pos=map.get(team); return team; } else map.put(team,++pos); team=team.next; } return null; } } But how to use O(1) space complexity to complete this operation? The idea of the above question is to use fast and slow pointers to determine whether there is a ring, but how to lock the entry of the ring? This question looks like an algorithm question, but it is actually a mathematical reasoning question. The key to this question is also the speed indicator, but more details are needed . Recall the details that quick and slow pointers can dig out: Knowing that the slow pointer has taken x steps and the fast pointer has taken 2x steps, but only knowing these two conditions can not derive anything, we can only perform some operations in O(1) methods. But the difference between the speed pointer and the previous one is that we start counting with a head node. What else can we do? Now that we know that the point we met is inside the ring, we can use a new node to enumerate a circle to see how long the ring is! Here, we can know the number of fast steps 2x, the number of slow steps x, and the ring length y. We know that the slow pointer enters the ring for the first time, but the fast pointer may have walked several times, but the number of steps must be an integer multiple of the ring (otherwise it is impossible to meet at the same position). It can be obtained quickly slow pointer number of steps = the number of fingers rings length + n steps . Of course, I don’t know how much it is. Converted into a formula, that is, 2x=x+ny and eliminate one x to get: x=ny . In the above figure, I also mark that the faster pointer moves more than an integer number of turns. The difficulty lies here and needs to be worked around: the x of the fast pointer is an integer multiple of the ring length y n, and the x of the slow pointer is also an integer multiple of the ring length y n. So what's the use of this? If a node starts from the starting point and walks to the fast, slow meeting point, it takes x steps (n*y steps). At this point, if a pointer starts from the intersection of fast and slow, if it travels an integral multiple of the loop length, it will still be in the original position. That is to say, starting from the head node team1 by taking x steps, from the fast and slow junction node team2 taking x steps, they will eventually reach the fast and slow junction node, but on the way of enumeration, once the team1 node traverses into the ring, Then it coincides with the team2 node, so once they are equal, it will be the first point of intersection. The implementation code is: /** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { boolean isloop=false; ListNode fast=new ListNode(0);//头指针 ListNode slow=fast; fast.next=head; if(fast.next==null||fast.next.next==null) return null; while (fast!=null&&fast.next!=null) { fast=fast.next.next; slow=slow.next; if(fast==slow) { isloop=true; break; } } if(!isloop)//如果没有环返回 return null; ListNode team=new ListNode(-1);//头指针 下一个才是head team.next=head; while (team!=fast) { team=team.next; fast=fast.next; } return team; } } Conclusion At this point, the problem of finding the link in the linked list is solved. The code analysis may not be well written. Please point out any problems and make persistent efforts! Come on! About the author: bigsai is mainly dedicated to the sharing of knowledge of Java, data structures and algorithms. There is an original public account of the same name:, the bigsaifirst time to harvest dry goods!
https://ideras.com/the-interviewer-asked-me-how-to-find-the-entrance-in-the-linked-list-i-thought-it-was-simple-but-i-wanted-to-be-silly-on-the-spot/
CC-MAIN-2021-25
refinedweb
1,486
67.89
16.02.2012 19:13, Myklebust, Trond пишет:> On Thu, 2012-02-16 at 19:06 +0400, Stanislav Kinsbursky wrote:>> Local tranports uses UNIX sockets and connecting of these sockets is done in>> context of file system namespace (i.e. task file system root).>> Currenly, all sockets connect operations are performed by rpciod work queue,>> which actually means, that any service will be registered in the same rpcbind>> instance regardless to process file system root.>> This is not containers, which usually have it's own nested root. There are 2>> approaches, how to solve the problem. First one is to store proper root in>> tranport and switch to it in rpciod workqueue function for connect operations.>> But this looks ugly. The second one is to connect to unix sockets>> synchronously. This aptch implements the last one.>> That approach can fall afoul of the selinux restrictions on the process> context. Processes that are allowed to write data, may not be allowed to> create sockets or call connect(). That is the main reason for doing it> in the rpciod context, which is a clean kernel process context.>Thanks for explanation, Trond.So, this connect have to be done in kernel process context.Now I can see 2 ways how to meet this requirement and reach the goal:1) Change the fs root for rpciod while connecting.2) Do not touch rpciod and launch special "connect" kernel thread to perform connect operations for unix sockets.What do you think about this 2 ways above? Which one is less worse from your POW?Maybe you have even a better solution for the problem?-- Best regards,Stanislav Kinsbursky--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/2012/2/17/42
CC-MAIN-2015-22
refinedweb
301
74.9
Slingshot Yourself Into Hibernate 3.5 and JPA 2.0 with this Tutorial By Andrew Tee TheServerSide.com Do you want to learn Hibernate 3.5, and work with the first release of Hibernate that fully supports JPA 2.0, but you don't want to be led by the nose through any lengthy or long winded tutorials. Well, here it is - the best tutorial you're going to find for getting you started with Hibernate 3.5 in a hurry. Get The Required Hibernate JAR Files To work with Hibernate 3.5, you need to link your runtime and design time Java environments to the following JAR files: - antlr-2.7.6.jar - commons-collections-3.1.jar - dom4j-1.6.1.jar - hibernate3.jar - hibernate-jpa-2.0-api-1.0.0.Final.jar - javassist-3.9.0.GA.jar - jta-1.1.jar - slf4j-api-1.5.8.jar - slf4j-simple-1.5.8.jar You will find all of these JAR files, with the exception of the slf4j-simple-1.5.8.jar file, in the Hibernate 3.5 distribution download. Here's where you can download it: When you download this zip file, the hibernate3.jar file will be in the root folder of the download. The hibernate-jpa JAR file will be in a subfolder named jpa. The other JAR files, with the exception of slf4j-simple-1.5.8.jar, will be in a folder named required. Create a folder off the root of your C:\ drive named _hiblib3.5 and chuck these JAR files into it. Find the Darn slf4j-simple-1.5.8.jar File I'm not sure what the crazy licensing restriction is that allows Hibernate to distribute the slf4j-api jar file, but not the implementation file, but the fact is, the JAR file that provides an actual implementation of the interfaces defined in the slf4j-api-1.5.8.jar file is not provided with the Hibernate distribution download, so you're required to head over to and download the 1.5.8 implementation of slf4j. Now, as of writing, the latest implementation of slf4j is 1.6, and if you download that one and link to it at design time, you'll get a runtime error, so make sure you get an implementation that matches the version of the slf43-api JAR file that came with the Hibernate distribution you have downloaded (for me it's 1.5.8). Unzip the downloaded file from slf4j.org, and find the slf4j-simple-1.5.8.jar file, and throw it into your C:\_hiblib3.5 folder. You should now have all nine of the required JAR files in there. Make Sure You Have Your JDBC Drivers What? You thought you could learn Hibernate but avoid the database? Yeah...Right... We're going to connect to a database, so that means you need a database and the JDBC drivers that go along with it. I'm using MySQL, so that means I'm using the mysql-connector-java-5.1.12-bin.jar file, which can be obtained from the Connector/J download page at dev.mysql.com/downloads/connector/j/ This JAR file, or whatever JAR file you use to connect to your database of choice, must be on your Java runtime and design time classpaths. To make life simple, I'm adding this JAR to my C:\_hiblib3.5 folder as well, taking the JAR count in there to an even ten. Create Your rps Schema in the MySQL Workbench You'll also need to configure a logical database within your RDBMS system. For MySQL, that means going into the MySQL Workbench and creating a new schema name rps. I'm naming the schema rps, because this database will be holding the results of our online Rock-Paper-Scissors game. Create & Configure the hibernate.cfg.xml File You need to tell the Hibernate framework how to connect to your database, and that is done by creating a file named hibernate.cfg.xml, and placing it on your classpath. This file contains the credentials for connecting to your database, the JDBC URL, the dialect, the name of the JDBC driver, and a couple of other tidbits just to keep things interesting. Here's what my hibernate.cfg.xml file looks like, although you may need to tweak yours depending on how your personal environment is configured: <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" ""> <hibernate-configuration> <session-factory> <property name="connection.url"> jdbc:mysql://localhost/rps </property> <property name="connection.username"> root </property> <property name="connection.password"> </property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="current_session_context_class"> thread </property> <!-- this will show us all sql statements --> <property name="hibernate.show_sql"> true </property> <!-- mapping files NOTICE WE HAVE NONE--> </session-factory> </hibernate-configuration> Save that file with the name hibernate.cfg.xml, and put it on both your runtime and designtime classpath. People always shove it on their design-time classpath, and then it never gets picked up at runtime, and they get errors stating that the environment can't find the hiberante.cfg.xml file. For me, I'm just creating a simple folder named _mycode off the root of C:\ and I'm placing the file right in there. I will reference this location at both runtime and design time. Write Some Java Code Hibernate is a persistence framework that saves the state of your Java objects (POJOs) to the database. So, if you want to use Hibern the Hibernate framework needs some type of identifier that represents its uniqueness, otherwise JPA based persistence simply won't work. Here's what our JPA annotated GameSummary class looks like: package com.mcnz.model; import javax.persistence.*; import org.hibernate.*; import org.hibernate.cfg.*; import org.hibernate.tool.hbm2ddl.*; @Entity public class GameSummary { @Id @GeneratedValue private Long id; private String result; public Long getId() {return id;} public void setId(Long id) { this.id = id; } public String getResult() {return result;} public void setResult(String result) { this.result = result; } public String toString() { return "id: " + id + " result: " + result ; } } We have been a bit progressive with our imports, as they are not all needed right now, but they will be soon. For now, focus on the annotations that come from the JPA 2.0 API. The @Entity annotation indicates to the persistence framework that the GameSummary is indeed a persistent class whose state can be managed by Hibern hibernate.cfg.xml file will be on your runtime and design time classpaths. Write Some Test Code So, does all of this work? Well, that really is the question, isn't it? Add the following main method to your GameSummary class and run it. public static void main(String args[]) { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(GameSummary.class); config.configure(); new SchemaExport(config).create(true, true); } File and Sanity Check At this point, we have talked about a number of differernt JARs, folder and files. Here's what your environment should look like, if you've been following along: Run Your Stand Alone Hibernate:\_hiblib3.5\*" C:\_mycode\com\mcnz\model\GameSummary.java To run this code, I run the following command: C:\>c:\_jdk1.6\bin\java -classpath "C:\_hiblib3.5\*";C:\_mycode com.mcnz.model.ameSummary Now it doesn't get any more hard-core and old-school than using the old JDK to compile and run your code. But the point is, if you have followed these instructions, your code will compile and run, and you don't need any fancy-dancy or expensive IDE like Eclipse or NetBeans to do it. And with that said, if I can get this to work with nothing other than a JDK and a few folders containing various JAR files, if you do have a funky development environment, then you shouldn't have any problem getting this tutorial to run there as well. When the code runs, the Hibernate configuration, which is in essence the instance of the AnnotationConfiguration object, adds the GameSummary.class to its list of classes whose persistence it manages, and the it configures itself, making sure that the Hibernate framework really understands all of the various classes it is tasked with managing. From there, the config object is passed to the SchemaExport's constructor, and a create call is issued. This call looks at the Hibernate AnnotationConfiguration object and creates all of the underlying tables that are needed to support all of the persistent classes it is managing. So, if you run this code, you will see the following output in your console window: drop table if exists GameSummary create table GameSummary (id bigint not null auto_increment, result varchar(255), primary key (id)) And if you look at your database, the following table and columns will have been added to your rps database schema: And if all this happens, well, that means you followed these instructions properly, and your Hibernate environment is up and running! And that's it for getting your environment configured. If you got that to work, you're ready to move on to the next, much easier step, which is actually persisting some data to the database. Part II: Performing CRUD Operations with Hibernate 3.5 and JPA Annotations 20 Jun 2010
http://www.theserverside.com/tutorial/Slingshot-Yourself-Into-Hibernate-35-and-JPA-20-with-this-Tutorial
CC-MAIN-2013-20
refinedweb
1,567
56.66
- . You will see that SAX Is an event-based API. Operates at a lower level than DOM. Gives you more control than DOM. Is almost always more efficient than DOM. But, unfortunately, requires more work than DOM. Why Another API? Don't be fooled by the name. SAX may be the Simple API for XML but it requires more work than DOM. The rewardtighter communicates with the application by explicitly building a tree of objects in memory. The tree of objects is an exact map of the tree of elements in the XML file. DOM is simple to learn and use because it closely matches the underlying XML document. It is also ideal for what I call XML-centric applications, such as browsers and editors. XML-centric applications manipulate XML documents for the sake of manipulating XML documents.. Event-Based Interfaces As the name implies, an event-based parser sends events to the application. The events are similar to user-interface events such as ONCLICK (in a browser) or AWT/Swing events (in Java). Events alert the application that something happened and the application needs to react. In a browser, events are typically generated in response to user actions: a button fires an ONCLICK event when the user clicks. With an XML parser, events are.1: pricelist.xml <?xml version="1.0"?> <xbe:price-list xmlns: <xbe:product>XML Training</xbe:product> <xbe:price-quote <xbe:price-quote <xbe:price-quote <xbe:price-quote </xbe:price-list>Figure 8.4: The structure of the price list. The XML parser reads this document and interprets it. Whenever it recognizes something in the document, it generates an event. When reading Listing 8.1, the parser first reads the XML declaration and generates an event for the beginning of the document. When it encounters the first opening tag, <xbe:price-list>, the parser generates its second event to notify the application that it has encountered the starting tag for a price-list element. Next, the parser sees the opening tag for the product element (for simplicity, I'll ignore the namespaces and indenting whitespaces in the rest of this discussion) and it generates its third event. After the opening tag, the parser sees the content of the product element: XML Training, which results in yet another event. The next event indicates the closing tag for the product element. The parser has completely parsed the product element. It has fired five events so far: three events for the product element, one event for the beginning of document, and one for price-list opening tag. The parser now moves to the first price-quote element. It generates two events for each price-quote element: one event for the opening tag and one event for the closing tag. Yes, even though the closing tag is reduced to the / character in the opening tag, the parser still generates a closing event. There are four price-quote elements, so the parser generates eight events as it parses them. Finally, the parser meets price-list's closing tag and it generates its two last events: closing price-list and end of document. As Figure of the two APIs intrinsically better; they serve different needs. The rule of thumb is to use SAX when you need more control and DOM when you want increased convenience. For example, DOM is popular with scripting languages. The main reason to adopt SAX is efficiency. SAX does fewer things than DOM but it gives you more control over the parsing. Of course, if the parser does less work, it means you (the developer) have more work to do. Furthermore, as already discussed, SAX consumes fewer resources than DOM, simply because it does not need to build the document tree. In the early days of XML, DOM benefited from being the official, W3C-approved API. Increasingly, developers trade convenience for power and turn to SAX. The major limitation of SAX is that it is not possible to navigate backward in the document. Indeed, after firing an event, the parser forgets about it. As you will see, the application must explicitly buffer those events it is interested in. Of course, whether it implements the SAX or DOM API, the parser does a lot of useful work: It reads the document, enforces the XML syntax, and resolves.
http://www.informit.com/articles/article.aspx?p=26332&amp;seqNum=3
CC-MAIN-2018-17
refinedweb
720
65.62
Trying to find the centroid of Polygon with Shapely but I do not understand how to tell the library that the vertices are (lon, lat). Perhaps I need to set a projection? Here is my code: from shapely.geometry import Polygon, Point # LON, LAT vertices = [ Point(-79.8726944444444, 8.68505555555556), Point(-79.8733888888889, 8.50419444444444), Point(-79.54552777777779, 8.68386111111111), Point(-79.54622222222221, 8.503), Point(-79.8726944444444, 8.68505555555556), ] p1 = Polygon(vertices) centroid = p1.centroid print(centroid) # POINT (-1805804163717.8823 6592764402.930745) The result is clearly wrong. >Solution : It’s a degenerate shape. It’s bowtie that crosses itself. Shapely can’t handle that.
https://devsolus.com/2022/06/24/find-polygon-centroid-with-shapely-given-vertices-with-lat-lon/
CC-MAIN-2022-27
refinedweb
105
71.71
Microsoft. It is not a question of if, but a question of when. When will async let me down and give me a headache? The headaches usually fall into one of these categories. Last fall I was working on a project where I needed to execute code during a DocumentProcessed event. Inside the event, I could only use async APIs to read from one stream and write into a second stream. The delegate for the event looked like: public delegate void ProcessDocumentDelegate(MarkdownDocument document); If you’ve worked with async in C#, you’ll know that the void return type kills asynchrony. The event handler cannot return a Task, so there is nothing the method can return to encapsulate the work in progress. The bigger problem here is that even if the event handler could return a Task, the code raising the event is old code with no knowledge of Task objects. I could not allow control to leave the event handler until my async work completed. Thus, I was facing the dreaded "sync over async" obstacle. There is no getting around or going over this obstacle without feeling dirty. You have to hope you are writing code in a .NET Core console application where you can hold your nose and use .Result without fear of deadlocking. If the code is intended for a library with the possibility of execution in different environments, then the saying abandon hope all ye who enter here comes to mind. When working with an old code base you can assume you’ll run into problems where async code needs to interact with sync code. But, the situation can happen in new code, and with new frameworks, too. For example, the ConfigureServices method of ASP.NET Core. public void ConfigureServices(IServiceCollection services) { // ... } There are many reasons why you might need async method calls inside ConfigureServices. You might need to obtain an access token or fetch a key over HTTPs from a service like Key Vault. Fortunately, there are a few different solutions for this scenario, and all of them we move the async calls out of ConfigureServices. The easiest way out is to hope you are using a library designed like the KeyVault library, which moves async code into a callback, and invokes the callback later in an async context. AuthenticationCallback callback = async (authority,resource,scope) => { // ... var authResult = await authContext.AcquireTokenAsync(resource, credential); return authResult.AccessToken; }; var client = new KeyVaultClient(callback); Another approach is to move the code into Program.cs, where we finally (after waiting for 2.1 releases of C#) have an async Main method to start the process. Finally, you can use one of the approaches described in Andrew Lock’s three part series on Running async tasks on app startup in ASP.NET Core. The Task class first appeared in .NET 4.0 ten years ago as part of the Task Parallel Library. Task was an abstraction with a focus on parallelism, not asynchrony. Because of this early focus, the Task API has morphed and changed over the years as Microsoft tries to push developers into the pit of async success. Unfortunately, the Task abstraction has left behind a trail of public APIs and code samples that funnel innocent developers into a pit of weeping and despair. Example - which of the following can execute compute-bound work independently for several minutes? (Choose all that apply) new Task(work); Task.Run(work); Task.Factory.StartNew(work); Task.Factory.StartNew(work).ConfigureAwait(false); Task.Factory.StartNew(work, TaskCreationOptions.LongRunning); Answer: all of the above, but some of them better than others, depending on your context. Another disappointing feature of async is how good code can turn bad when using the code in an async context. For example, what sort of problem can the following code create? using (var streamWriter = new StreamWriter(context.Response.Body)) { await streamWriter.WriteAsync("Hello World"); } Answer: in a system trying to keep threads as busy as possible, the above code blocks a thread when flushing the writer during Dispose. Thanks to David Fowler’s Async Guidance for pointing out this problem, and other subtleties. After all these years with tasks and async, there are still too many traps to catch developers. There is no single pattern to follow for common edge cases like sync over async, yet so many places in C# demand synchronous code (constructors, dispose, and iteration come to mind). Yes, new language features, like async iterators, might shorten this list, but I’m not convinced the pitfalls will disappear. I can only hope that, like the ConfigureAwait disaster, we don’t have to live with the work arounds sprinkled all through our code. Someone asked me why dependency injection is popular in .NET Core. They told me DI makes code harder to follow because you never know what classes and objects the app will use unless you run with a debugger. The argument that DI makes software harder to understand has been around for a long time, because there is some truth to the argument. However, if you want to build flexible, testable, decoupled classes in C#, then using a container and constructor injection is still the simplest solution. The alternative is to write code like the ASP.NET MVC AccountController (not the .NET Core controller, but the MVC 4 and 5 controllers). If you've worked with the framework over the years, you might remember a time when the project scaffolding gave us the following code. public AccountController() : this(new UserManager<ApplicationUser>( new UserStore<ApplicationUser>( new ApplicationDbContext()))) { } then public AccountController(UserManager<ApplicationUser> userManager) { UserManager = userManager; } public UserManager<ApplicationUser> UserManager { get; private set; } The two different constructors do provide some flexibility. In a unit test, you can pass in a test double as a UserManager, but when the application is live the default constructor combines a DbContext with a UserStore to provide a production implementation. The problem is, the production implementation becomes hard-coded into the default constructor. What if you want to wrap the UserStore with a caching or logging component? What if you wanted to use a non-default connection string for the DbContext? Then you need to scour the entire code base to find all the dependencies hardcoded with new. Later versions of the scaffolding tried to improve the situation by centralizing dependency registration. The following is code from today's Startup.Auth.cs. Notice how the method is similar to ConfigureServices in ASP.NET Core.); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); // ... } While the central registration code is an improvement, the non-Core ASP.NET framework does not offer DI as a native service. The application needs to manually resolve a dependencies via an OwinContext reference. Now, the AccountController looks like: public AccountController() { } public AccountController(ApplicationUserManager userManager) { UserManager = userManager; } public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } The problem is, every dependency requires a developer to write a property and follow the service locator anti-pattern. So, while the indirection of DI in ASP.NET Core does have some downsides, at least DI doesn’t add more code to a project. In fact, an AccountController in ASP.NET has a simpler setup. public class AccountController { public AccountController(ApplicationUserManager userManager) { UserManager = userManager; } // … } As always, software is about tradeoffs. If you want the flexibility of testable classes, go all in with dependency injection. The alternative is to still face uncertainties from indirection, but in a code base that is larger and harder to maintain. My trip to the Software Design and Development conference came only a few days after returning home from NDC Minnesota, so I should have written this post 6 months ago. Life took some unexpected turns, so better late than never. History My first SDD was over 10 years ago. The opportunity came about when the Pluralsight founders opted to step out of the conference circuit and encouraged myself and others to step in. Back then the conference ran under a different name, but the organizer and the feel of the conference hasn't changed. Both are some of my favorites. On all my trips to London I’ve always arrived on an overnight flight from Washington D.C. For this trip I took a daytime flight, leaving Washington at 9 am and reaching a dark and rainy Heathrow at 9 pm. I was bored with overnight flights into Europe and hoped the shift would allow me a quicker adjustment to the time change (it did). I’ve always found London to be comfortable and familiar. I grew up in an old house by American standards, in an old town and near the older east coast cities. In the black cab from Paddington station, at night and in the rain, the Georgian architecture of London made me feel like I was riding through Northwest D.C. The terraced housing passed by like row houses in Baltimore. The smell of old wood near the river, and the Sunday roast. These are childhood experiences. London is closer to home than Chicago or Seattle. If I’m ever in London when a cyclone hits, I’ll want to be at the Barbican Centre, the usual home for SDD. The brutalist architecture of the surrounding estate places concrete beneath your feet, above your head, and around you on all four sides. Razed to the cellars by bombs during World War II, the area today lives up to the old Latin meaning of the word barbican, which implies a residence that is “well-fortified”. The first day of SDD for me was a C# workshop. It’s been a long time since I’ve taught a pure language workshop, and the experience was wonderful. In recent years, my workshops revolved around Angular. In December of 2017, after running an Angular workshop at NDC, I made the decision to escape from the asylum. I didn’t want to work with Angular, and I was tired of teaching students how to shave yaks. I especially didn’t want to shave my own yaks only to hear them bleat WARN deprecated with breaking changes the following week. In this workshop, I felt rewarded by teaching topics with significance in software development, and showed how to use patterns with staying power. My final session at SDD was one of the most enjoyable sessions I’ve presented in a few years. I was able to open an editor and vamp on a .NET Core web app for 90 minutes. This type of presentation doesn’t work as a keynote, or in front of a huge audience, but on this day I had the perfect room and time slot. Before I arrived in London, I knew I would eat well during the week. Brian Randall was also speaking at the conference. No matter where I am in the world, I can call Brian, tell him what city I’m in, and he’ll have restaurant recommendations. When I’m in the same city as Brian, the culinary adventures are fantastic. Highlights from the past include Vivek Singh’s Cinnamon Club (in London), Bobby Flay’s Mesa Grill (in New York city at the time), and a couple dozen other fine restaurants over the years. The SDD organizer, Nick Payne, is also a foodie. Nick organizes a speaker’s dinner every year, and not only does the restaurant exceed expectations, but the company and conversation does, too. This years dinner was at Rök, a restaurant with a rural Nordic influence in the décor, as well as the food. This year’s highlight, though, was the Duck and Waffle. There’s only three buildings in all of London that can look down at The Gherkin, and the Duck and Waffle is at the top of one of those buildings. Brian and I had breakfast here one morning, and yes, the duck leg confit was tasty. The views, however, were breathtaking. There's a chill of insignificance that settles over me when I'm looking over the sprawl of 8 million people. Fortunately, breakfast day was a rare sunny morning in London. The warmth of the sun was a good counterbalance. As much as I enjoy London, though, I had to cut this trip short. Wall Street beckoned. Up next in this travel series: Pluralsight IPO day. Over the years I’ve noticed that application startup code tends to attract smaller bits of code in the same way that a protostar accretes cosmic material until reaching the point where nuclear fusion begins. I’ve seen this happen in the main function of C programs, and (back when we never had enough HRESUTs to hold the HINSTANCEs of our HWINDOWs), in the WinMain function of C++ programs. I’ve also seen this happen inside of global.asa in classic ASP, and in global.asax.cs for ASP.NET. It’s as if we say to ourselves, "I only have two new lines of code to execute when the program starts up, so what could it hurt to jam these two lines in the middle of the 527 method calls we already have in the startup function?" This post is a plea to avoid nuclear fusion in the Startup and Program files of ASP.NET Core. There is a lengthy list of startup tasks for modern server applications. Warm up the cache, create the connection pool, configure the IoC container, instantiate the logging sinks, and all of this happens before you getting to the actual business of application startup. In ASP.NET Core, I used to see most of this logic end up inside of Startup.cs. Some of this code is moving over to Program.cs as developers start to recognize Program.Main as a usable entry point for a web application. The next few opinionated posts will discuss strategies for organizing startup and entry code, and look at approaches you can use for clean startup code. To get started, let’s talk about the Startup class in ASP.NET Core. If you believe every class should have a single responsibility, then it is easy to think the Startup class should manage all startup tasks. But, as I’ve already pointed out, there is a lot of work to do when starting up today’s apps. The Startup class, despite its name, should not take responsibility for any of these tasks. In Startup, there are three significant methods with specific, limited assignments: The constructor, where you can inject dependencies to use in the other methods. ConfigureServices, where you can setup the service provider for the app Configure, which should be limited to arranging middleware components in the correct order. public class Startup { public Startup(IConfiguration configuration) { // ... } public void ConfigureServices(IServiceCollection services) { // ... } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // ... } } Of course, you can also have environment specific methods, like ConfigureDevelopment and ConfigureProduction, but the rules remain the same. Initialization tasks like warming the cache don’t need to live in Startup, which already has enough to do. Where should these tasks go? That’s the topic for the next post. I’ve kept most of my workshop and conference materials in a private GitHub repository for years. I recently made the repository public and added a CC-BY-4.0 license. The material includes slides, and hands-on labs, too. Some of the workshops are old (you’ll find some WinJS material inside [shudder]), but many of the workshops have aged well – C#, LINQ, and TDD are three workshops I could open and teach today. Other material, like the ASP.NET Core workshop, is recently updated. Actually, I think the ASP.NET Core material is the most practical and value focused technology workshop I’ve ever put together. Ten years ago, Pluralsight decided to stop instructor led training and go 100% into video courses. As an author, I was happy to make video courses, but I also wanted to continue meeting students in face-to-face workshops. I still prefer workshops to conference sessions. I started making my own workshop material and ran classes under my own name and brand. Over the last 10 years I’ve been fortunate to work with remarkable teams from Mountain View in Silicon Valley, to Hyderabad, India, and many places in between. Four years ago on this day, actually, I was in Rotkruez, Switzerland, where I snapped the following picture on the way to lunch – one of numerous terrific meals I’ve shared with students over the years. The memory of being driven through the snowy forests of Switzerland is enough to spike my wanderlust, which for several reasons I now need to temper. I still enjoy the workshops and conferences, and seeing good friends, but I don’t need the stress and repetition of traveling and performing more than a few times a year. If I see a place I’d like to visit, I’m in the privileged position of being able to go without needing work as an excuse. For that, I’m thankful that Pluralsight decided to go all-in with video training. I don’t advertise my workshops or publicize the fact that I offer training for sale. I still receive regular request for private training, and again I am lucky to choose where I want to go. Conferences still ask me for workshops, but conferences can also be political and finicky (thanks to Tibi and Nick P for being notable exceptions). What I’m saying is that I’m not using my workshop material enough to justify keeping the material private. Besides, training on some of my favorite topics is a commodity these days. Everyone does ASP.NET Core training, for example. And, if there is one lesson I’ve learned from years of training in person and on video, it’s that the training materials are not the secret sauce that can make for a great workshop. The secret sauce is the teacher. Maybe, someone else can find something useful to do with this stuff. Imagine you have a unit test that depends on an environment variable. [Fact] public void CanGetMyVariable() { var expected = "This is a test"; var actual = Environment.GetEnvironmentVariable("MYVARIABLE"); Assert.Equal(expected, actual); } Of course the dependency might not be so explicit. You could have a test that calls into code, that calls some other code, and the other code needs an environment variable. Or, maybe you have a script or tool that needs an environment variable.. In other words, I can make the above test pass by defining a variable in my pipeline YAML definition: resources: - repo: self variables: MyVariable: 'This is a test' pool: vmImage: vs2017-win2016 steps: - task: DotNetCoreCLI@2 displayName: Test inputs: command: test projects: '**/*[Tt]ests/*.csproj ' arguments: '--configuration $(BuildConfiguration)' ... Or in the DevOps pipeline GUI: Also included are the built-in variables, like Build.BuildNumber and System.AccessToken. Just be aware that the variable names you use to reference these parameters can depend on the context. See Build Variables for more details. In a previous post I said to be wary of GUI build tools. In this episode of .NET Core Opinions, let me show you a "configuration as code" approach to building software using Azure DevOps. Instead of the trivial one project demo you’ll see everywhere in the 5 minute demos for DevOps, let’s build a system that consists of: An ASP.NET Core project that will run as a web application A Go console project that will run once-a-week as a web job An Azure Functions project Let’s also add some constraints to the scenario (and address some common questions I receive). We need to deploy the web and Go applications into the same App Service. We need to deploy the functions project into a second App Service that runs on a consumption plan. The first step in using YAML for builds is to select the YAML option when creating a new pipeline instead of selecting from the built-in templates that give you a graphical build definition. I would post more screen shots of this process, but honestly, the UI will most likely iterate and change before I finish this post. Look for “YAML” in the pipeline options, then click a button with affirmative text. I should mention that the graphical build definitions are still valuable, even though you should avoid using them to define your actual build pipelines. You can fiddle with a graphical build, and at any time click on the "View YAML" link at the pipeline or individual task level. I found this toggle view useful for migrating to YAML pipelines, because I could look at a working build and see what YAML I needed to replicate the process. In other words, migrating an existing pipeline to YAML is easy. Once you get the feeling for how YAML pipelines work, the docs, particularly the YAML snippets in the tasks docs, give you everything you need. Also, there is an extension for VS Code that provides syntax highlighting and intellisense for Pipelines YAML. The YAML you’ll create will describe all the repositories, containers, triggers, jobs, and steps needed for a build. You can check the file into your source code repository, then version and diff your builds! The essential building blocks for a pipeline are tasks. These are the same tasks you’d arrange in a list when defining a build using the GUI tools. In YAML, each task consists of the task name and version, then the task parameters. For example, to build all .NET Core projects across all folders in Release mode, run the DotNetCoreCLI task (currently version 2), which will run dotnet with a default command parameter of build. - task: DotNetCoreCLI@2 displayName: 'Build All .NET Core Projects' inputs: projects: '**/*.csproj' arguments: '-c Release' Ultimately, you want to run dotnet publish on ASP.NET Core projects. In YML, the task looks like: - task: DotNetCoreCLI@2 displayName: 'Publish WebApp' inputs: command: publish arguments: '-c Release' zipAfterPublish: false Notice the zipAfterPublish setting is false. In builds where a repo contains various projects intended for multiple destinations, I prefer to move files around in staging areas and then create zip files in explicit steps. We’ll see those steps later*. I’m throwing in the Go steps because I have a Go project in the mix, but I also want to demonstrate how Azure Pipelines and Azure DevOps is platform agnostic. The platform wants to provide DevOps and continuous delivery for every platform, and every language. Building a Go project was easy with the built in Go task. - task: Go@0 displayName: 'Install Go Deps' inputs: arguments: '-d' command: get workingDirectory: '$(System.DefaultWorkingDirectory)\cmd\goapp - task: Go@0 displayName: 'go build' inputs: command: build arguments: '-o cmd\goapp\app.exe cmd\goapp\main.go' The first step is go get, which is like using dotnet restore in .NET Core. The second step is building a native executable from the entry point of the Go app in a file named main.go. If you want to use Azure Functions and the C# language, then I believe Functions 2.0 is the only way to go. The 1.0 runtime works, but 1.0 is not as mature when it comes to building, testing, and deploying code. Building a 2.0 project ( dotnet build) places everything you need to deploy the functions into the output folder. There is no dotnet publish step needed. Once all the projects are built, the assemblies and executables associated with each project are on the file system. This is the point where I like to start moving files around to simplify the steps where the pipeline creates release artifacts. Release artifacts are the deployable bits, and it makes sense to create multiple artifacts if a system needs to deploy to multiple resources. Based on the requirements I listed at the beginning of the post, we are going to need the build pipeline to produce two artifacts, like so: The first step is getting the files into the proper structure for artifact 1, which is the web app and the Go application combined. The Go application will execute on a schedule as an Azure Web Job. It is interesting how many people have asked me over the years how to deploy a web job with a web application. The key to the answer is to understand that Azure uses simple conventions to identity and execute web jobs that live inside an App Service. You don’t need to use the Azure portal to setup a web job, or find an obscure command on the CLI. You only need to copy the Web Job executable into the right folder underneath the web application. - task: CopyFiles@2 displayName: 'Copy Go App to WebJob Location' inputs: SourceFolder: cmd\goapp TargetFolder: WebApp\bin\Release\netcoreapp2.1\publish\App_Data\jobs\triggered\app Placing the Go .exe file underneath App_Data\jobs\triggered\app, where app is whatever name you want for the job, is enough for Azure to find the web job. Inside this folder, a settings.job file can provide a cron expression to tell Azure when to run the job. In this case, 8 am every Monday: {"schedule": "0 0 8 * * MON"} The final steps consist of zipping up files and folders containing the project outputs, and publishing the two zip files as artifacts. Remember one artifact contains the published web app output and the web job, while the second artifact consist of the build output from the Azure Functions project. The ArchiveFiles and PublishBuildArtifacts tasks in Azure do all the work. - task: ArchiveFiles@2 displayName: 'Archive WebApp inputs: rootFolderOrFile: WebApp\bin\Release\netcoreapp2.1\publish includeRootFolder: false archiveFile: WebApp\bin\Release\netcoreapp2.1\WebApp.zip - task: ArchiveFiles@2 displayName: 'Archive Function App inputs: rootFolderOrFile: FunctionApp\bin\Release\netcoreapp2.1 includeRootFolder: false archiveFile: FunctionApp\bin\Release\netcoreapp2.1\FunctionApp.zip - task: PublishBuildArtifacts@1 displayName: 'Publish Artifact: WebApp inputs: PathtoPublish: WebApp\bin\Release\netcoreapp2.1\WebApp.zip ArtifactName: WebApp - task: PublishBuildArtifacts@1 displayName: 'Publish Artifact: FunctionApp' inputs: PathtoPublish: FunctionApp\bin\Release\netcoreapp2.1\FunctionApp.zip ArtifactName: FunctionApp Currently, YAML is not available for building a release pipeline, but the roadmap says the feature is coming soon. However, since we arranged the artifacts to simplify the release pipeline, all you should need to do is to feed the artifacts into Deploy Azure App Service tasks. Remember function projects, even on a consumption plan, deploy just like a web application, but like web jobs, use some conventions around naming and directory structure to indicate the bits are for a function app. The build output of the function project will already have the right files and directories in place. Having build pipelines defined in a textual format makes the pipeline easier to modify and version changes over time. Unfortunately, this YAML approach only works in Azure. There is no support for running, testing, or troubleshooting a YAML build locally or in development. For systems with any amount of complexity, you will be in better shape if you automate the build using command line scripts, or a build system like Cake. Then you can run your builds both locally and in the cloud. Remember, your developer builds need to be every bit as consistent and well defined as your production builds if you want a productive, happy team. * Note that I’ve simplified the YAML in the code samples by removing actual project names and “shortening” the directory structure for the project.
https://odetocode.com/blogs/all?page=5
CC-MAIN-2019-51
refinedweb
4,575
63.59
by Jeffrey Kantor (jeff at nd.edu). The latest version of this notebook is available at. This Jupyter notebook describes the modeling of vapor-liquid equilibrium with Antoine's equation, including the calculation of saturation pressure, saturation temperature, relative humidity, and normal boiling points. The Gibb's phase rule tells us how many independent thermodynamic variables (such as $T$, $P$, $\hat{V}$, or $x_i$) are required to completely specify the state of a substance. $$ F = C + 2 - \Pi $$ where $$ \begin{align*} F & = \mbox{Thermodynamic Degrees of Freedom} \\ C & = \mbox{Number of Components} \\ \Pi & = \mbox{Number of Phases} \end{align*} $$ This is a deep and profound rule that has many implications for engineering analysis that you will study this more in your thermodynamics courses. For a pure component $C = 1$, so the Gibb's phase rule reads $$ F = 3-\Pi$$ which tells that two independent thermodynamic variables, such as $T$ and $P$, are sufficient to specify the state of a single phase. Furthermore, if two phases are in coexistence, then there must be a relationship between $T$ and $P$. And that the coexistence of three phases completely specifies the thermodynamic state. These observations are conveniently summarized in a 2-dimensional phase diagram for a pure substance. The following figure shows a typical phase diagram. By Matthieumarechal, CC BY-SA 3.0 The green line shows the solid/liquid coexistence (the dashed green line showing the anomolous special case of water). from IPython.display import YouTubeVideo YouTubeVideo("BLRqpJN9zeA",560,315,rel=0) from IPython.display import YouTubeVideo YouTubeVideo("-gCTKteN5Y4",560,315,rel=0) Antoine's equation is used to estimate the saturation pressure (also called vapor pressure) of pure substances between the triple and critical points. Louis Charles Antoine, an engineer working in the French Navy, in 1886 published the equation as method for representing the vapor pressure of water. A common form of the equation is $$\log_{10}P^{sat} [mmHg]= A - \frac{B}{T[^{\circ}C] + C}$$ where pressure is units of millimeters of mercury (mmHg, also called torr), and temperature in degrees Celcius. An alternative form of the equation is to calculate the saturation temperature as a function of pressure $$T^{sat}[^{\circ}C] =\frac{B}{A-\log_{10}P[mmHg]} - C$$ Values for the constants $A$, $B$, and $C$ are tabulated in various references, including the NIST Chemistry Webbook. The values of the constants depend on the units used for pressure and temperature, and whether the logarithm is computed for base $e$ or base 10. Standard practice is to specify a range of temperatures over which a particular set of constants is known to offer an accurate representation. Multiple ranges may be pieced together to obtain saturation pressure over wider ranges. import numpy as np import matplotlib.pyplot as plt %matplotlib inline def log10Psat(T): return 7.96681 - 1668.21/(T + 228.0) def Psat(T): return 10**log10Psat(T) def Tsat(P): return 1668.21/(7.96681 - np.log10(P)) - 228.0 Psat(100.0) Psat(37.0)*1013.35/760.0 62.60713122755462 P= 25.96*25.4 print(P) print(Psat(96.4)) print(Tsat(P)) 659.384 667.363429722238 96.0707898963 # Antoine's equation for water from 1 to 374 degrees C def Psat(T): if (1 <= T < 100): return 10**(8.07131 - 1730.63/(T + 233.426)) elif (100 <= T <= 374): return 10**(8.14019 - 1810.94/(T + 244.485)) else: return float('nan') # Use Psat(T) to construct to show the vapor-liquid equilibrium diagram T = np.linspace(1,374) plt.figure(figsize = (10,6)) plt.semilogy(T,[Psat(T) for T in T],linewidth=2) plt.xlabel('Temperature $^{\circ}C$') plt.ylabel('Pressure [mmHg]') plt.title('Vapor Pressure of Water') # Additional annotations plt.semilogy(0.01,4.58,'o',markersize=10) plt.annotate('Triple Point', xy=(10,4.58), xytext=(20,3)) plt.semilogy(100,760,'o',markersize=10) plt.annotate('Normal Boiling Point', xy=(100,760), xytext=(110,500)) plt.semilogy(374,1.67e5,'o',markersize=10) plt.annotate('Critical Point', xy=(374,1.67e5), xytext=(300,2e5)) plt.text(250,200,'Vapor',fontsize=16) plt.text(75,100000,'Liquid',fontsize=16) plt.xlim([-10,400]) plt.grid() The barometric pressure at the top of Mount Everest is about 260 mmHg. What is the boiling point of water? # Through trial-and-error, we find Psat(72.5) 259.590244400894 The catapults on aircraft carriers require steam at 520 psig. What is the minimum operating temperature? # import a root-finding algorithm from scipy.optimize import brentq as fzero # convert pressure to absolute mmHg P = (400+14.7)*760/14.696 # function to solve f = lambda T: Psat(T) - P # solve T = fzero(f,1,374) print("Operating Pressure (absolute) = {:7.1f} mmHg".format(P)) print("Minimum Operating Temperature = {:7.2f} deg C".format(T)) Operating Pressure (absolute) = 21446.1 mmHg Minimum Operating Temperature = 230.97 deg C On a summer morning you notice dew on the grass. The temperature is $58^{\circ}F$. What is the mole fraction of water in the air? In the afternoon the air temperature reaches $80^{\circ}F$. What is the relative humidity? Applying the ideal gas law, we set the partial pressure of water to the observed dew point temperature. $$y_{H_2O}P = P^{sat}_{H_2O}(T_{dew})$$ which can be solved for $y_{H_2O}$. The relative humidity is just the ratio of teh partial pressure of water to the saturation pressure. $$RH\% = \frac{y_{H_2O}P}{P^{sat}_{H_2O}(T)}\times 100\%$$ def f2c(T): return 5*(T-32.0)/9 Tdew = f2c(58) P = 760 y = Psat(Tdew)/P print("Mole fraction water = {:7.4f}".format(y)) T = f2c(80) RH = y*P/Psat(T) print("Relative humidity at {:.1f} deg C = {:.1f}%".format(T,100*RH)) Mole fraction water = 0.0162 Relative humidity at 26.7 deg C = 47.0% A simple database of Antoine equations for a set of chemical compounds is easily implemented with a Python dictionary. The unique names for each compound form keys for dictionary. Then for each key, Antoine's equation is implement as an anonymous function. Piecewise functions are implemented using standard Python logical statements. The supplementary dictionaries Psat_Tmin and Psat_Tmax represent upper and lower limits on the range of validity for the corresponding entry in Psat. Psat = dict() Psat_Tmin = dict() Psat_Tmax = dict() Psat['benzene'] = lambda T: 10**(6.90565 - 1211.033/(T + 220.790)) Psat_Tmin['benzene'] = 8 Psat_Tmax['benzene'] = 103 Psat['ethanol'] = lambda T: 10**(8.04494 - 1554.3/(T + 222.65)) Psat_Tmin['ethanol'] = -2 Psat_Tmax['ethanol'] = 100 Psat['methanol'] = lambda T: \ (T <= 65) and 10**(7.89750 - 1474.08/(T + 229.13)) or \ (T > 65) and 10**(7.97328 - 1515.14/(T + 232.85)) Psat_Tmin['methanol'] = -14 Psat_Tmax['methanol'] = 110 Psat['toluene'] = lambda T: 10**(6.95464 - 1344.8/(T + 219.48)) Psat_Tmin['toluene'] = 6 Psat_Tmax['toluene'] = 137 Psat['water'] = lambda T: \ (T <= 60) and 10**(8.10765 - 1750.286/(T + 235.0)) or \ (T > 60) and 10**(7.96681 - 1668.21/(T + 228.0)) Psat_Tmin['water'] = 0 Psat_Tmax['water'] = 150 Generate a report of chemical compounds and temperature ranges for which saturation pressure can be computed. print("{:15s} {:7s} {:7s}".format('Species','Tmin[C]','Tmax[C]')) print("{:15s} {:7s} {:7s}".format('-------','-------','-------')) species = Psat.keys() for s in species: print("{:15s} {:7.1f} {:7.1f}".format(s,Psat_Tmin[s],Psat_Tmax[s])) Species Tmin[C] Tmax[C] ------- ------- ------- toluene 6.0 137.0 benzene 8.0 103.0 water 0.0 150.0 ethanol -2.0 100.0 methanol -14.0 110.0 P = Psat['water'](25) print("Vapor pressure of water at 25 deg C = {:4.1f} mmHg".format(P)) Vapor pressure of water at 25 deg C = 23.8 mmHg # Select a list of species species = Psat.keys() # Plot the saturation pressures over the individual temperature ranges for s in species: T = np.linspace(Psat_Tmin[s],Psat_Tmax[s]) plt.plot(T,[Psat[s](T) for T in T]) plt.legend(species,loc='best') plt.xlabel('Temperature $^{\circ}C$') plt.ylabel('mmHg') plt.title('Vapor Pressure by Antoine\'s Equation'); Tsat = dict() Tsat_Pmin = dict() Tsat_Pmax = dict() from scipy.optimize import brentq as fzero for s in Psat.keys(): Tsat_Pmin[s] = Psat[s](Psat_Tmin[s]) Tsat_Pmax[s] = Psat[s](Psat_Tmax[s]) Tsat[s] = lambda P,s = s: fzero(lambda T: Psat[s](T)-P,Psat_Tmin[s],Psat_Tmax[s]) # Select a subset of species s = ['methanol','ethanol'] s = Psat.keys() # Plot the saturation pressure over the individual pressure ranges for k in s: P = np.linspace(Tsat_Pmin[k],Tsat_Pmax[k]) plt.plot(P,[Tsat[k](P) for P in P]) plt.legend(s,loc='best') plt.xlabel('mmHg') plt.ylabel('Temperature $^{\circ}C$') plt.title('Saturation Temperature by Antoine\'s Equation'); species = Psat.keys() print("{:12s} {:>7s}".format('Species','Tb [C]')) print("{:12s} {:>7s}".format('-------','------')) for s in species: Tb = Tsat[s](760) print("{:12s} {:7.2f}".format(s,Tb)) Species Tb [C] ------- ------ toluene 110.63 benzene 80.10 water 100.00 ethanol 78.33 methanol 64.71
http://nbviewer.jupyter.org/github/jckantor/CBE20255/blob/master/notebooks/Vapor-Liquid%20Equilibrium%20for%20a%20Pure%20Component.ipynb
CC-MAIN-2017-43
refinedweb
1,503
52.97
constrather than #define. There's plenty of utilities I see used in C++ that came from C though. I could be wrong, but it seems that those who start in C++ eventually get better at coding and are more ready to use C in their code. If people like to accuse C++ of being dangerous though, well C is just as ( and to some more) tedious. I don't use C a whole lot but I have found it useful from time to time. I know a guy who's a hobbyist game programmer though, and he uses A LOT of C, even though he started out in C++. #defineand const, defines run the risk of adding hard to find bugs into you program due to them not having a type. It is better practice to use const instead due to them having a type. #include <cstdlib>1. #defineand const, actually a const is better to make constants that will actually be USED in you program, but define is still usable in conditional compilation. /*...*/would be better than using #ifdefs
http://www.cplusplus.com/forum/beginner/103362/
CC-MAIN-2017-26
refinedweb
180
78.99
How to import a web font into your React App with styled components 4 Sibylle Sehl ・3 min read Tired of being limited to requesting fonts over a CDN? Look no further. You might be required to import a font for a number of reasons - ranging from buying corporate licenses for certain fonts, to availability concerns or even because your favourite font isn't available through a CDN (Content Delivery Network). Since I've started working as a developer, I've learned how to import a web font directly rather than linking to a CDN where the font might be hosted. Since I didn't really know where to start, I thought I'd write up this quick tutorial to show you how you can accomplish this in a React setting using styled components version 4 - my favourite way of writing CSS in React apps. Let's get down to business First of all, you need select the font you want to import and download it in woff and woff2 format. Woff (and later Woff2) stands for Web Open Font Format and is the recommended font format by the World Wide Web Consortium (W3C). Its format specific compression ensures its performance in all browsers and furthermore reduces web font latency as opposed to requesting fonts from a CDN. There are a few sites where you can download these, for example: Pick anything you like! I'd advise you to import at least those two font formats, woff and woff2, since they have been recommended by the W3C and are widely supported on all browsers. In your React project, create a folder in your src folder and name it 'fonts'. In this folder create a file which you call fonts.js - this will contain the imports for your fonts and will later make them available to the rest of your app. In the same folder, now place the two font files you have just downloaded. This will make them accessible for your app to import them correctly. After doing this, your file structure should look similar to this: src |__fonts |__fonts.js |__nameOfYourFont.woff2 |__nameOfYourFont.woff Now, let's actually write some code into the fonts.js file so 'styled components' can import them as a Global Font. In your fonts.js file import the { createGlobalStyle } from 'styled-components'. This is a handy little helper that handles global css styles in your app. If you want to to dive in, visit createGlobalStyle on the styled components documentation. After doing that, you have to import the fonts into your file and declare them in a font-face declaration. import { createGlobalStyle } from 'styled-components'; import NameOfYourFontWoff from './nameOfYourFont.woff'; import NameOfYourFontWoff2 from './nameOfYourFont.woff2'; export default createGlobalStyle` @font-face { font-family: 'Font Name'; src: local('Font Name'), local('FontName'), url(${NameOfYourFontWoff2}) format('woff2'), url(${NameOfYourFontWoff}) format('woff'); font-weight: 300; font-style: normal; } `; This will import your chosen font in both woff and woff2 formats and make it accessible through the fonts file. But that's only half of the battle done. While we have imported the specific fonts, we haven't actually imported these in our App yet. At the top of the App.js file, after importing React, write import GlobalFonts from './fonts/fonts'; // assuming you places fonts in your src folder as described above. Somewhere in the App.js file, preferably just below a normal styled component that would typically contain site layout or similar and doesn't need any font styles, place the GlobalFonts component in your return of the render: render() { return ( <Wrapper> <GlobalFonts /> // ... </Wrapper> ); } After doing this, you are free to use your font anywhere in your styles as you choose. In any styled-components file, just declare (for example): const AwesomeHeadline = styled.h1` font-family: 'Font Name'; `; export default AwesomeHeadline; Et voila, you just imported your web font and used it in a Headline! I hope this helps you to import fonts in the future, be it for work or that awesome personal project with that personal touch! How do you come up with new side projects? Side projects are great ways to grow our knowledge and skill, but where do you start? How do you get your ideas for new side projects? Free Angular Training during JavaScript Marathon with This Dot Labs This Dot Media - What’s your alternative solution? Challenge #1 Adrian - What’s your alternative solution? Challenge #2 Adrian - Interesing approach! Thanks for share it. Nice Article Great tutorial. It has helped me a lot!
https://practicaldev-herokuapp-com.global.ssl.fastly.net/alaskaa/how-to-import-a-web-font-into-your-react-app-with-styled-components-4-1dni
CC-MAIN-2020-16
refinedweb
752
64.2
Overview Some of the steps needed to setup a development environment includes: Operating system - e.g Linux / Mac Project structure - project structure Virtualenv - isolated installation of the project Pip - a tool for installing and managing Python packages Git - source control Webserver - where we can manage our applications Fabric - automated deployment Project Structure Create an empty top-level directory for our new project. helloflask/ -static/ -css -font -img -js -templates -routes.py Then cd into the directory cd helloflask Virtualenv Many developers uses virtualenv (virtual environment) on their computer, which is useful when you want to run several applications on the same computer. Virtualenv will manage all dependencies and enables multiple side-by-side installations of Python, one for each project. It doesn't install separate copies of Python, but provides a way to keep different project environments isolated. If we want to run more than one (which is often the case) web application on that host, then you should really install 'Virtualenv'. If you don't use virtualenv , you will have it all globally installed. Installing Virtualenv Download and Install Virtualenv into a virtual environment # If you are using Linux/Mac: sudo pip install virtualenv Setup a new project Navigate to the directory you want your project in: $ virtualenv venv # this creates the folder venv $ source venv/bin/activate # start working on your new project (venv)$ pip install Flask # installs Flask For more information on how to download install virtualenv, see this article. Pip PIP is a tool for installing and managing Python packages. PIP comes with a command-line interface, which makes installing Python software packages as easy as issuing one command pip install some-package-name Users can also easily implement the package's subsequent removal pip uninstall some-package-name Pip has a feature to manage full lists of packages and corresponding version numbers through a "requirements" file. This permits the efficient re-creation of an entire group of packages in a separate environment (e.g. another computer) or virtual environment. This can be achieved with a properly formatted requirements.txt file pip install -r requirements.txt This makes dependencies easy, you can create a requirements file based on a set of packages installed in your virtual environment. pip freeze > requirements.txt When deploying to a server it is important to register which requirements we need. The requirements file can be done automatically using the freeze command for pip. This command will generate a plain text file that contains the names of the required Python packages and their versions, for example Flask==0.9 To do this we freeze the installed packages and store this setup in a requirements.txt file $ cat requirements.txt Flask==0.9 Jinja2==2.6 Werkzeug==0.8.3 The requirements file can be used to rebuild a virtual environment or to deploy a virtual environment into the machine. Start coding Now that we have a clean Flask environment to work in, we'll create our simple application. The simplest Flask App looks something like this: Put this code into the file and name it 'hello.py' from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hello World!' Github – Central Repository Now it's time to create the repository on Github. The purpose of setting up a Github project, is so that we can push files from our local computer to Github and then pull the files from Github to our web server. Create a new Github account and create a new project (helloflask) Git – Local Computer By using a versioning system, we can store all our files in a Github repository. The first thing you need to do on your local computer is to install and setup git. Install Git To install git, simple run: sudo apt-get install git Setup Git Put in your username and email into the .gitconfig file (~/.gitconfig) git config --global user.name "pythonforbeginners" git config --global user.email [email protected] Git Ignore Since our current directory contains a lof of extra files, we'll want to configure our repository to ignore these files with a .gitignore file: venv *.pyc Next, we’ll create a new git repository and save our changes. # Initialize Git in our project directory git init This creates a git repository in the current directory. Add all of our files to our initial commit git add . Check the status, this will list all files git status With the files added to the Git index, we can now commit them to our repo: $ git commit -m 'Initial commit' Now we have created a local Git repository for our application (local) files. Setup Github as the origin git remote add origin [email protected]:USERNAME/helloflask.git git push -u origin master Web Server – Host Now its time to start up the web server and do some configuration. If you want to use Apache as a web server, you can install it like this: sudo apt-get install apache2 Configure a virtual host (vhost) in /etc/apache2/sites-available/siteX Install virtualenv just like you did on your local computer. Set up the environment for the website, here I use /var/www Cd into that folder and clone the project that you setup on Github, by typing: git clone [email protected]:USERNAME/helloflask.git Initialize and activate your virtualenv virtualenv helloflask cd helloflask source bin/activate Install dependencies pip install -r requirements.txt Fabric. [source] from fabric.api import * # import fabrics API functions env.hosts = ['[email protected]:22'] # add the remote server information def pushpull(): local('git push') # runs the command on the local environment run('cd /path/to/project/; git pull') # runs the command on the remote environment #Run it with: $ fab pushpull For more information on how to use fabric in a development environment, please refer to this article. Recommended Python Training For Python training, our top recommendation is DataCamp.
https://www.pythonforbeginners.com/development/development-environment-in-python
CC-MAIN-2021-31
refinedweb
980
52.49
Hi, is that possible to test to what exactly code a scala.meta static annotation was expanded? Say, for data classes "a la carte" () investigate pieces as follows? scala.meta Good question @alexander.myltsev ! One way to test the expansion would be to implement it in static function on an object, which you can unit test by passing in custom trees import scala.meta._ object Macros { def myMacro(tree: Tree): Tree = q"expanded.tree" } // unit tests def testMacro = Macros.myMacro(q"class A").isEqual(q"expanded.tree") // macro annotation class MyMacroAnnotation extends StaticAnnotation { inline def apply(x: Any) = meta { x match { case t: Tree => Macros.myMacro(t) case _ => sys.error(s"$x is unsupported") } } } However, since scalameta/paradise is in milestone phase, note that the tree passed into inline def may not always match 100% with the same tree created with quasiquotes. For example, for comprehensions are not yet "resugared" by the scalahost converter. If you hit on such cases, please report an issue since the trees should be identical. inline def Scala.meta trees are not path dependant (unlike scala-reflect) so setting up a test fixture typically boils down to import scala.meta._ . import scala.meta._
https://contributors.scala-lang.org/t/scala-meta-expansion-testing-harness/691
CC-MAIN-2017-43
refinedweb
202
58.89
Xbox Live integration coming to Windows 8 Join the DZone community and get the full member experience.Join For Free It is well know that there will be a new Xbox Live dashboard update coming for Xbox 360 consoles, bringing the Metro design outside Windows. Today, at Microsoft Build in Anaheim, CA, the new Xbox Live dashboard was showcased as a part of Windows 8. But it's not only about the dashboard itself. Xbox Live development is finally coming to Windows 8. We'll see support for: - Multiplayer - Achievements & Gamerscore - Avatars - Friends List & Community - Roaming Save State - Title Managed Storage - Beacons - Avatar Awards The Live ID integration in Windows 8 is already present, so the dashboard will be automatically linked to the current user account. This ultimately makes Xbox Live integration as easy as it can get, both from the user and developer perspectives. The development experience for the Xbox Live platform is pretty straightforward with previous development experience. It all relies on a single Microsoft.Xbox namespace that can be used from either a C++, C# or JavaScript project. Most of the plumbing is already done, including the authentication mechanisms - the developer doesn't have to worry about the associated ID - if it is there, it will be automatically used. If it is not - the OS itself will provide a prompt for the user to enter the correct credentials. With very little effort, developers will be able to add interactive capabilities to their games that will make the general entertainment experience as good as the one on the Xbox, with all the associated benefits. There will also be specific service endpoints, going through - the data returned to the developer will be formatted using JSON. At this point developers might ask - what about the Xbox Live SDK and all the associated capabilities? After all, it would not be good to simply let everyone on the XBL bandwagon because of the quality requirements. Microsoft throught about this as well - in order to add Xbox Live capabilities to a game, the developer will have to go through an approval process, that will be somewhat similar to the current XBL-capability acquisition process. If this process is cleared, the SDK will be offered for free. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/new-xbox-live-dashboard-also-0
CC-MAIN-2021-17
refinedweb
381
51.48
This module provides direct access to all `built-in' identifiers of Python; for example, __builtin__.open is the full name for the built-in function open(). See chapter 2, ``Built-in Objects.'' This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of that name is also needed. For example, in a module that wants to implement an open() function that wraps the built-in open(), this module can be used directly: import __builtin__ def open(path): f = __builtin__.open(path, 'r') return UpperCaser(f) class UpperCaser: '''Wrapper around a file that converts output to upper-case.''' def __init__(self, f): self._f = f def read(self, count=-1): return self._f.read(count).upper() # ... As an implementation detail, most modules have the name __builtins__ (note the "s") made available as part of their globals. The value of __builtins__ is normally either this module or the value of this modules's __dict__ attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.
http://www.python.org/doc/2.5/lib/module-builtin.html
crawl-001
refinedweb
193
55.64
I've started a new fresh repository on my system here, and to make sure I won't make the same mistake, I've set up a github repository. The new name for the framework is gunge, but the only part that is currently available is the event handling part. I have, however, come across an interesting design challenge that really made me appreciate the fact that in python, everything is an object. You see, the event system provides a decorator called bind that allows you to statically bind events. It would be used something like so: class SomeClass(gunge.event.Handler): @gunge.event.bind(pygame.KEYDOWN, {'unicode': 'a'}) def on_keya(self, event): print "some code" The function on_keya would then be called whenever a KEYDOWN event occurs, and furthermore, only if event.unicode is equal to 'a.' There are a few more powerful features to this second argument, called the attribute filter, but that is for another time. How would this be implemented? there is a difference between this function and an actual instance method, bound to an instance. My first idea was to store the information in some class variable called handlers, and have each instance use this variable to bind its actual methods upon initialization. This works in the simple cases, but becomes problematic with inheritance. A class variable does not carry over nicely between inherited classes, and furthermore, there is the problem of overidden functions. If a function is bound to a certain event in the parent class, and that function is overidden in the child, what should happen? should the parent binding still count, and how would this be implemented? Implementation issues aside, this method also requires the user to create a new class variable in each class that is an event handler, and pass this handler into the bind decorator so that it can be used for annotation. The problem seemed insolvable. But then a wise lesson came to me: If you're design runs into implementation issues, do not try to solve the implementation issues. It is likely that you need a different design. It came to me that functions, like pretty much everything in python, are just objects. With types, attributes, the whole shenanigans. So, it seemed much simpler to simply store the binding information as an attribute of the function. Since introspection can be used to find all of an instances methods, it is trivial to retrieve this information. This means that the boiler plate code of the class variable is gone, and that derived classes will retain the bindings of their parent class, unless that particular function is overridden. In that case, the parent functions is not part of the child class, and the binding must be respecified. And this is actually desirable, for clarity's sake. Furthermore, we can allow a single event Binder object to allow multiple callbacks. This means that a class method can simply store its own Binder object, and each new class instance can simply add its own callback to this object. This reduces the amount of event Binder objects in the event manager drastically, as a class with one method bound to an event will have one Binder object, no matter how many instances of that class exist. This can have huge benefits in both space and speed, since an event has to be tested against an attribute filter just once. The 'everything is an object' paradigm, together with powerful introspection capabilities, allow you to do a lot more with functions than would normally be possible. And the lesson for this week, of course: If your design has problems, don't try to work around them. Instead, change the design.
http://goingamerica.blogspot.com/2009/02/pyton-everything-is-object.html
CC-MAIN-2017-39
refinedweb
616
61.46
Python Multiline Comment/String Folding I seem to be having a problem with the python language and folding when there are multiline comments or strings present. For instance: def func(): str = ''' ''' Folding this method will fold up the line defining str = ’ ’ ', but the two lines below it are left unfolded. If I put something other than spaces on the second line, it will fold the first two lines (assuming the second line doesn’t start with a space). If I put a space before the trailing ’ ’ ’ it will fold all lines. python lexer is based on indentation, so yes you have to add spaces in front to make it work correctly. Cheers Claudia Well this isn’t a very good solution because it affects the contents of the multiline string As the python lexer is part of the scintilla component you might think opening a feature request at. Maybe search first if not already addressed. Cheers Claudia - Jimmy Devine So messing with the notepad++ code it looks like the scintilla source already present does this, it just isn’t being used, adding this execute line to ScintillaEditView::setPythonLexer adds is void setPythonLexer() { setLexer(SCLEX_PYTHON, L_PYTHON, LIST_0 | LIST_1); execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.quotes.python"), reinterpret_cast<LPARAM>("1")); }; nice finding - thx for sharing this info. For all who don’t want or can’t recompile npp, the same can be achieved when using python script plugin and the following call editor.setProperty("fold.quotes.python", 1) But this needs to be called for every python document once so it makes sense to call it from within the notepad bufferactivated callback. I have opened a feature request at github to ask for implementing this. Cheers Claudia Good deal, thanks Claudia
https://notepad-plus-plus.org/community/topic/13306/python-multiline-comment-string-folding
CC-MAIN-2018-39
refinedweb
288
58.92
>>.'" Re:Agreed. (Score:5, Informative) Python is strongly typed. Maybe you mean statically typed. Personally (Score:5, Informative) As someone simulating fluid-structure interaction with a number of constituent models and a lot of finite element (i.e. big matrix problems; using FEniCS - fenicsproject.org), using Python makes my overall quite-long algorithm much easier to flick through. Invaluable for debugging the theory as well as the implementation. FEniCS' Python interface ties into the standard C/C++ libraries using SWIG and, in simple cases, saves me working in C++. Very clear, well-written C++ is great for this application but I find it takes considerably longer to write than clear Python. When I hit a more intricate problem, I realized I was going to have to solve a series of FE matrices by hand (with PETSc, written in C). It turned out to be pretty straightforward to pick up SWIG, write a short module in C and a Python interface. Done! Particularly useful as I believe getting FEniCS and petsc4py to play well is tricky. So, I'd agree - having written a C++ version of my (simpler) problem and a Python/C version of the complicated one, the latter was definitely easier, and all the rate-limiting stuff is in C anyhow. Doubt it would be true for every situation but +1 from an FE perspective. Python's problem (Score:5, Informative) It's still too slow, despite what he says. (Score:5, Informative) Says the guy whose whole life is tied up in the language, and whose project, at Google, to speed it up, crashed and burned. [wikipedia.org] Python is slow because von Rossum refuses to cut loose the boat-anchor of "anything can change anything at any time". The straightforward implementation of Python, CPython, boxes all numbers (everything is a CObject, including an int or a float) and looks up functions, attributes, and such in a dictionary for every reference. And only one thread is allowed to run at a time. This allows one thread to dynamically patch the objects and code of another thread. Which is cool, but useless. 99.99+% of the time, there's no need for a dynamic lookup. Most program dynamism is shortly after program startup - once things are running, they don't change much. If, sometime shortly after startup, the program said "OK, done with self-modification", at which point a JIT compiler did its thing, the language would be much faster. But no. That's "un-Pythonic". PyPy, the newer Python implementation, uses two interpreters and a JIT compiler to try to handle the dynamism with less overhead. They're making progress, but they need a very complex implementation to do it, and they're many years behind schedule. Python, as a language, is very usable. But it's too slow for volume production. That's not inherent in the basic language. Python could remain declaration-free if there were just a few more restrictions on unexpected dynamism. By this is meant ways the program can change itself that aren't obvious from looking at the source code. For example, if a module or class could only be modified from outside itself if it contained explicit self-modification code (like a relevant "setattr" call) most modules and classes could be nailed down as fixed, "slotted" objects at compile time. The other big win is using enough type inference to decide if a variable can always be represented as a machine type (int, float, char, bool, etc.). That's a huge performance win. Claiming that the "slow parts" should be rewritten in C is a cop-out. It makes the program more fragile, since C code can break Python's memory safety. Except for number-crunching, or glue code for existing libraries, it's seldom done. (I have a Python program running right now which will run for over a week, parsing the street address of every business in the US into a standard format. The parser is complex enough that rewriting it in C would be a big job. There's no "inner loop".) Re:007087 (Score:5, Informative) As the GP pointed out, if you're skilled enough to write optimized code in C/C++, why fuck around with Python at all? Because we don't want to spend our time thinking about pointers and how to iterate over things? Because functional programming is actually really nice? Because in Python, you can download some data from the web, analyse it using a machine learning algorithm, plot the results, and install another package on the fly, combining 4 independent packages, and many ideas, in just 50 lines of code. ctypes is really easy to use and to interface with C or Fortran. I use it a lot, namely for the 1% of the code that takes 99% of the time. The rest is nice OOP and functional. Re:Logically Logical Logic (Score:5, Informative) Yes, that is correct. You should write your apps in Python. Your libraries, you should write in Python first, because it is also a great prototyping language. If they work fine (which they will in most cases) you have saved yourself a bunch of time. If they are too slow, you have saved yourself a bunch of time by fixing algorithmic bugs in a flexible language like Python. It is now trivial to convert it to bug-free C or C++. Donald Knuth (Score:4, Informative) Re:007087 (Score:3, Informative) ... because given two equally talented developers, the one working in python will literally run circles around the guy working in C/C++... and in the real world developer time = money. The fact is that interfacing with C libraries in Python is already trivial. Furthermore modern tools like Cython make it EVEN EASIER! So you take your code, profile it, decorate the most time-intensive portions to be compatible with Cython (trivial for most applications) -or- interface it with your C library. This way, you get your code up and running in a fraction of the developer time, with near identical performance to the C implementation. Re:007087 (Score:4, Informative) As most things in life do, code usually follows the Pareto distribution: 80% of the time is spend in 20% of the code. If Python is fast enough for, let's say 90% of your code, and you are much more productive in Python than C, then writing most all the code in Python first, and replacing the bits and pieces that are too slow for you with C functions, is much more efficient use of your time than writing everything in C. Also consider that sometimes you have to go in fishing expeditions for the correct algorithm to do what you are doing. Doing so in Python, with the speedup in iterative design that that carries, and even if that once you find the most efficient algorithm for your problem you implement it in C, you will have had spend the same time as before, but knowing all the ways you can't do it, and have arrived to an at least nearly optimal solution. Most of the time you don't need that much speed. When you do, you have to have the right algorithm and the right language. I also put forth that Python has a lot of modules that are already written in C, so you take advantage of existing optimized code that you don't have to write.:Kinda digging Python (Score:4, Informative) If you do need to know the index, you should write It pays off to spend some time learning not only the syntax when you learn a new language, but also often used idioms in that language. Re:Kinda digging Python (Score:5, Informative) return (a>0)?a+1:a-1; Tertiary operator FTW!:007087 ]
http://developers.slashdot.org/story/12/03/16/1947252/van-rossum-python-not-too-slow/informative-comments
CC-MAIN-2015-35
refinedweb
1,309
70.13
pyConditions 0.4 Want some class invariant shenanigans? from pyconditions.invariant import Invariant, FieldsNotNone @FieldsNotNone( [ "test" ] ) class Test: def __init__( self ): self.test = 1 def add( self ): return self.test + 1 def set( self, v ): self.test = v t = Test() print t.add() t.set( None ) That last call to add will cause the invariant to fail and thus throw the following: pyconditions.exceptions.PyCondition: Field "test" was None when it should not have been in invariant "notNone" Need a custom invariant? from pyconditions.invariant import CustomInvariant def invariant( self ): return self.test == 1 @CustomInvariant( "test", invariant ) class Test( object ): def __init__( self ): self.test = 1 def method1( self ): self.test This is great but the conditions slow my code down a lot? No problem. from pyconditions.stage import Stage stage = Stage() stage.prod() Just set that somewhere in your code and you’ll be fine. There is still some overhead, mainly there will be two function calls for each method, the wrapper and the original function. But, for stacked Preconditions and Invariants it will not execute into the other conditions and invraiants when prod is called. If you want to go back to Dev then call dev(). Have conditions you want added? Open a PR with code. Have an issue? Open a PR with fixed code. - Author: Sean Reed - License: LICENSE.txt - Categories - Development Status :: 4 - Beta - License :: OSI Approved :: Apache Software License - Programming Language :: Python :: 2.6 - Programming Language :: Python :: 2.7 - Programming Language :: Python :: 3.2 - Programming Language :: Python :: 3.3 - Programming Language :: Python :: Implementation :: CPython - Programming Language :: Python :: Implementation :: PyPy - Topic :: Software Development :: Quality Assurance - Package Index Owner: streed - DOAP record: pyConditions-0.4.1.xml
https://pypi.python.org/pypi/pyConditions/0.4.1
CC-MAIN-2016-50
refinedweb
280
61.53
Iteration and s:linkGreg Zoller Aug 10, 2008 6:17 AM I'm trying, unsuccessfully, to have an editable list of strings (email addresses). Each string is an s:link which when clicked will call an action method. I can render the list as desired and when the s:link is clicked my action method is called, but... no value is passed so in the method I don't know what was clicked. Any ideas how I can accomplish this desired behavior? Code snippet: <a4j:region> <a4j:outputPanel [<h:outputText <a4j:repeat , <s:link </s:link> </a4j:repeat>] </a4j:outputPanel> <rich:inplaceInput <a4j:support </rich:inplaceInput> </a4j:region> Now my Java action method: public void editEmail(String emailAddr) { System.out.println("ONE: "+emailAddr); int pos = asnEmails.indexOf(emailAddr); System.out.println("POS: "+pos); ... When run the output shows no value for emailAddr even though there is a value displayed on the screen for the link. Any ideas? Thanks in advance. Greg 1. Re: Iteration and s:linkDaniel Hinojosa Aug 10, 2008 11:31 PM (in response to Greg Zoller) Can we see what cart manager and cart look like? 2. Re: Iteration and s:linkGreg Zoller Aug 11, 2008 3:06 AM (in response to Greg Zoller) Here's a version of this behavior in two files. The actual code is huge, so I can recreate this behavior in small form here--compressed app logic into the manager class. XHTML: <h:form> <rich:panel EMAILS: <a4j:outputPanel <a4j:repeat <s:link<br/> </a4j:repeat> </a4j:outputPanel> <br/> <rich:inplaceInput <a4j:support </rich:inplaceInput> </rich:panel> </h:form> Manager Class: @Name("mgr") @Stateful @Scope(ScopeType.SESSION) public class ManagerBean implements Manager { private HtmlInplaceInput emailRef; private UIRepeat repeater; private List<String> emails = new ArrayList<String>(); private String scratch="Hey"; private Set<Integer> keys = null; public Set<Integer> getKeys() { return keys; } public void setKeys(Set<Integer> keys) { this.keys = keys; } public List<String> getEmails() { return emails; } public void addEmail() { System.out.println("ADD!" +scratch); emails.add(new String(scratch)); scratch = null; } public String getScratch() { return scratch; } public void setScratch(String scratch) { this.scratch = scratch; } public void edit(String index) { System.out.println("EDIT INDEX: " + index); } @Remove @Destroy public void destroy() {} } The add/display part is working but when I click on the links inside my repeat clause nothing is passed to mgr.edit(). How can I pass in the one selected? Ultimately I will make these edit fields, not links so the user can edit addresses in the list. For now I'll rig the s:link to simply delete the selected address from the list. I saw some complex examples using binding but then read something in the Seam docs that suggested binding wasn't desirable--didn't work with conversations or something. Don't really understand all the nuances of binding and the examples I tried to emulate died w/exceptions (i.e. binding the a4j:repeat to a UIRepeat object, etc.). Is that what I'm going to need here to get the desired behavior? Thanks for any advise. Greg 3. Re: Iteration and s:linkDaniel Hinojosa Aug 11, 2008 4:53 AM (in response to Greg Zoller) Oh, yeah! We had this a few days ago...try putting a @DataModel annotation on the email list. 4. Re: Iteration and s:linkShervin Asgari Aug 11, 2008 3:54 PM (in response to Greg Zoller) Try to do like this: You create your s:link with f:param <s:link <f:param </s:link> And then in your stateful bean: @RequestParameter private String organisationId; This will then be injected and you can get it from your action. Hope this helps 5. Re: Iteration and s:linkGreg Zoller Aug 11, 2008 4:37 PM (in response to Greg Zoller) Tried this approach and came up getting null value for the parameter. <s:link <f:param </s:link> Then in my Java code for cart @RequestParameter private Integer emailId; ... public void selectEmail() { System.out.println("SELECTED EMAIL: " + emailId); } In my EmailAddress object (email's type) I have a trivial id generator: private static int idCount = 0; private Integer id = new Integer(idCount++); public Integer getId() { return id; } When run my output statement comes back w/NULL. Any ideas why? ALso tried String data type for id but that didn't matter. I'll also try the DataModel approach Daniel suggested. Thanks, Greg 6. Re: Iteration and s:linkGreg Zoller Aug 11, 2008 4:45 PM (in response to Greg Zoller) Hang on, ya'll. My bad. The @RequestParameter is working. I was trying to inject it into an object that wasn't a Seam component. D'oh! Fixed that up and we're working great. Thanks a million for the help and I'll also keep the DataModel approach in mind as well as that may be a good way to handle another issue I'm working. Greg
https://developer.jboss.org/thread/183437
CC-MAIN-2018-17
refinedweb
815
63.7
) Note By default, the Huey consumer runs in UTC-mode. The effect of this on scheduled tasks is that when using naive datetimes, they must be with respect to datetime.utcnow(). The reason we aren’t using utcnow() in the example above is because the schedule() method takes a 3rd parameter, convert_utc, which defaults to True. So in the above code, the datetime is converted from localtime to UTC before being sent to the queue. If you are running the consumer in localtime-mode ( -o), then you should always specify convert_utc=False with .schedule(), including when you are specifying a() To revoke all instances of a given task, use the revoke() and restore() methods on the task itself: count_beans.revoke() assert count_beans.is_revoked() is True res = count_beans(100) assert res.is_revoked() is True count_beans.restore() assert count_beans.is_revoked() is False Canceling or pausing periodic tasks¶ When we start dealing with periodic tasks, the options for revoking get a bit more interesting. We’ll be using the print time command as an example: @huey.periodic When specifying the revoke_until setting, naive datetimes should be with respect to datetime.utcnow() if the consumer is running in UTC-mode (the default). Use datetime.now() if the consumers is running in localtime-mode ( -o). Finally, we can prevent the task from running indefinitely: # will not print time until we call revoke() again with # different parameters or restore the task print_time.revoke() assert print_time.is_revoked() is True At any time we can restore the task and it will resume normal execution: print_time.restore() Task Pipelines¶ Huey supports pipelines (or chains) of one or more tasks that should be executed sequentially. To get started with pipelines, let’s first look behind-the-scenes at what happens when you invoke a task-decorated function: @huey.task() def add(a, b): return a + b result = add(1, 2) # Is equivalent to: task = add.s(1, 2) result = huey.enqueue(task) The TaskWrapper.s() method is used to create a QueueTask instance which represents the execution of the given function. The QueueTask is serialized and enqueued, then dequeued, deserialized and executed by the consumer. To create a pipeline, we will use the TaskWrapper.s() method to create a QueueTask instance. We can then chain additional tasks using the QueueTask.then() method: add_task = add.s(1, 2) # Create QueueTask to represent task invocation. # Add additional tasks to pipeline by calling QueueTask.then(). pipeline = (add_task .then(add, 3) # Call add() with previous result and 3. .then(add, 4) # etc... .then(add, 5)) results = huey.enqueue(pipeline) # Print results of above pipeline. print([result.get(blocking=True) for result in results]) # [3, 6, 10, 15] When enqueueing a task pipeline, the return value will be a list of TaskResultWrapper objects, one for each task in the pipeline. Note that the return value from the parent task is passed to the child task, and so-on. If the value returned by the parent function is a tuple, then the tuple will be used to update the *args for the child function. Likewise, if the parent function returns a dict, then the dict will be used to update the **kwargs for the child function. Example of chaining fibonacci calculations: @huey.task() def fib(a, b=1): a, b = a + b, a return (a, b) # returns tuple, which is passed as *args pipe = (fib.s(1) .then(fib) .then(fib)) results = huey.enqueue(pipe) print([result.get(blocking=True) for result in results]) # [(2, 1), (3, 2), (5, 3)] Here is an example of returning a dictionary to be passed in as keyword-arguments to the child function: @huey.task() def stateful(v1=None, v2=None, v3=None): state = { 'v1': v1 + 1 if v1 is not None else 0, 'v2': v2 + 2 if v2 is not None else 0, 'v3': v3 + 3 if v3 is not None else 0} return state pipe = (stateful .s() .then(stateful) .then(stateful)) results = huey.enqueue(pipe) print([result.get(True) for result in results]) # Prints: # [{'v1': 0, 'v2': 0, 'v3': 0}, # {'v1': 1, 'v2': 2, 'v3': 3}, # {'v1': 2, 'v2': 4, 'v3': 6}] For more information, see the documentation on TaskWrapper.s() and QueueTask.then(). Locking tasks¶ Task locking can be accomplished using the Huey.lock_task() method, which acts can be used as a context-manager or decorator. This lock is designed to be used to prevent multiple invocations of a task from running concurrently. If using the lock as a decorator, place it directly above the function declaration. If a second invocation occurs and the lock cannot be acquired, then a special exception is raised, which is handled by the consumer. The task will not be executed and an EVENT_LOCKED will.
https://huey.readthedocs.io/en/latest/getting-started.html
CC-MAIN-2018-47
refinedweb
783
57.98
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo You can subscribe to this list here. Showing 1 results of 1 Hi all, I'm using swig 2.0.3 together w/ python 2.6.6 (we are currently bound to this python version but probably switch to python 3.0 in the near future). I have a little inheritance problem with swig but solved it already by directly patching the proxy class. I have the hope that this can be solved more cleanly by using swig syntax. I haven't found it in the documentation though. Here is the explanation. Any hint would be strongly appreciated: I defined an abstract base class for all "datavector" classes. It is called DataVectorBase and is defined by using ABCMeta in the python layer. several derivates of this base class have to be implemented in plain ansi C. So we defined a datatype: real_vector_t in C and extend it by using swig to a python class. The only way to get it inherited like DataVectorBase <---- real_vector_t was to patch the proxy class. That worked completely correct but is some kind of ugly: class real_vector_t(_object): """Proxy of C real_vector_t struct""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, real_vector_t, name, value) ... goes into: from datavector_base import DataVectorBase class real_vector_t( DataVectorBase, _object): # _object has to be the second parent! """Proxy of C real_vector_t struct""" __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, real_vector_t, name, value) ... Is there a clean swig-way of doing it? thanks in advance, Karsten
http://sourceforge.net/p/swig/mailman/swig-user/?viewmonth=201105&viewday=4
CC-MAIN-2015-18
refinedweb
265
67.04
//************************************** // Name: A Simple Calculator // Description:A simple Calculator ; Well Commented easy to follow, for beginers. It also shows some basics of C++ programs. If you find this article helpful to you please send me a message. // By: Saifudheen A A (from psc cd) // // Side Effects:As the program will not make any error check, Dont enter any charactors other than numbers. //************************************** // This is a comment an will not make any sense to program // Simple Calculator By A. A . Saifudheen // keraleeyan@msn.com // This Code is NOT copywrited and may distribute // freely unless any comments are NOT Removed including above comments #include <iostream.h> // This file used for function definitions 'cout' and 'cin' in program //Simple Calculator By A. A . Saifudheen float a; // floating point variable -Means a Variable that capable of storing a number having some decimal places float b; // float result; int op; // Integer Variable -Means Variable that capable of storing a number. ( No decimal places) int option; int main() // It is the main function. A function Named 'main' is required for all C++ programs { do //'Do While' loop Used for Looping the program for multiple Calculations // 'Do While' loop Starts Here { cout << "Enter First Number \n"; cin >> a; // Input cout << "Enter Second Number \n"; cin >> b; cout << "Please enter an Option..\n"; cout << "[1] Add \n"; cout << "[2] Substract \n"; cout << "[3] Multiply \n"; cout << "[4] Devide \n "; // Add more function like Power, Modulus etc if needed. cin >> op; // The keybord input is passed to variable 'op' switch (op)// switch is similar to Select Case in VB { case 1 : // Case Addition result=a+b; break; case 2 : //Case Substraction result=a-b; break; case 3 : // Case multiplication result=a*b; break; case 4 : // Case Division result=a/b; } cout <<"The Result is..= " << result << "\n\n"; //Display Result and Skipping two Lines cout << "Enter an Option..\n"; cout << "[0] Exit.\n"; cout << "[1] Continue. \n"; cin >> option; // Do While loop Ends Here } while (option==1); // If option is 1 ie 'Continue' the above code is Looped else ( option<>1 ) it is Escaped from Loop return 0;// the ' main' function returns value 0 } // End of Code.
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=2819&lngWId=3
CC-MAIN-2019-04
refinedweb
356
58.52
Bugs item #832236, was opened at 2003-10-29 04:05 Message generated for change (Comment added) made by gward You can respond by visiting: Category: Build Group: Platform-specific Status: Open Resolution: None Priority: 5 Submitted By: Daniel Parks (danielparks) Assigned to: Greg Ward (gward) Summary: Build fails in ossaudiodev.c with missing macros Initial Comment: I'm building Python 2.3.2 with no configure flags on MkLinux Pre-R1. uname -a: Linux gondor.middle.earth 2.0.37-osfmach3 GENERIC_08alpha-20 Fri Jul 30 11:07:38 PDT 1999 ppc unknown The missing macros are: SOUND_MIXER_DIGITAL1, SOUND_MIXER_DIGITAL2, SOUND_MIXER_DIGITAL3, SOUND_MIXER_PHONEIN, SOUND_MIXER_PHONEOUT, SOUND_MIXER_VIDEO, SOUND_MIXER_RADIO, SOUND_MIXER_MONITOR, SNDCTL_DSP_GETODELAY I commented out two lines in setup.py and it seems to have built correctly. I would test it, but I need to go to bed, and I will forget to add this bug tomorrow. I will update this if Python actually works. ---------------------------------------------------------------------- >Comment By: Greg Ward (gward) Date: 2004-05-04 21:56 Message: Logged In: YES user_id=14422 Attached patch should fix the problem; I've emailed it to the original reporter to verify that it does. Will checkin/merge/close slip when I hear from him, or in a few days if I don't hear from him. ---------------------------------------------------------------------- Comment By: A.M. Kuchling (akuchling) Date: 2003-12-23 14:21 Message: Logged In: YES user_id=11375 The fix is probably straightforward; add #ifdef <macro>...#endif around each use of the problematic macros. If you do this, please submit a patch. ---------------------------------------------------------------------- You can respond by visiting:
https://mail.python.org/pipermail/python-bugs-list/2004-May/022885.html
CC-MAIN-2016-36
refinedweb
255
64.81
Hardware Intrinsics in .NET Core Tanner (when available). They also provide a software fallback for when the hardware does not provide the appropriate instructions. This enabled a number of common algorithms to be vectorized, often with only minor refactorings. However, the generality of this approach made it difficult for programs to take full advantage of all vector instructions available on modern hardware. Additionally, modern hardware often exposes a number of specialized non-vector instructions that can dramatically improve performance. In this blog post, I’m exploring how we’ve addressed this limitation in .NET Core 3.0. What are hardware intrinsics? In .NET Core 3.0, we added a new feature called hardware intrinsics. Hardware intrinsics provide access to many of these hardware specific instructions that can’t easily be exposed in a more general-purpose mechanism. They differ from the existing SIMD intrinsics in that they are not general-purpose (the new hardware intrinsics are not cross-platform and the architecture does not provide a software fallback) and instead directly expose platform and hardware specific functionality to the .NET developer. The existing SIMD intrinsics, in comparison, are cross-platform, provide a software fallback, and are slightly abstracted from the underlying hardware. That abstraction can come at a cost and prevent certain functionality from being exposed (when said functionality does not exist or is not easily emulated on all target hardware). The new intrinsics and supporting types are exposed under the System.Runtime.Intrinsics namespace. For .NET Core 3.0 there currently exists one namespace: System.Runtime.Intrinsics.X86. We are working on exposing hardware intrinsics for other platforms, such as System.Runtime.Intrinsics.Arm. Under the platform specific namespaces, intrinsics are grouped into classes which represent logical hardware instruction groups (frequently referred to as Instruction Set Architectures or ISAs). Each class then exposes an IsSupported property that indicates whether the hardware you are currently executing on supports that instruction set. Each class then also exposes a set of methods that map to the underlying instructions exposed by that instruction set. There is sometimes additionally a subclass that is part of the same instruction set but that may be limited to specific hardware. For example, the Lzcnt class provides access to the leading zero count instructions. There is then a subclass named X64 which exposes the forms of the instruction that are only usable on 64-bit machines. Some of the classes are also hierarchical in nature. For example, if Lzcnt.X64.IsSupported returns true, then Lzcnt.IsSupported must also return true since it is an explicit subclass. Likewise, if Sse2.IsSupported returns true, then Sse.IsSupported must also return true because Sse2 explicitly inherits from the Sseclass. However, it is worth noting that just because classes have similar names does not mean they are definitely hierarchical. For example, Bmi2 does not inherit from Bmi1 and so the IsSupported checks for the two instruction sets are distinct from each other. The design philosophy of these types is to truthfully represent the ISA specification. SSE2 requires to support SSE1, so we exposed a subclass and since BMI2 doesn’t require supporting BMI1, we didn’t use inheritance. An example of the API shape described above is the following: You can also see a more complete list by browsing the source code on source.dot.net or dotnet/coreclr on GitHub. The IsSupported checks are treated as runtime constants by the JIT (when optimizations are enabled) and so you do not need to cross-compile to support multiple different ISAs, platforms, or architectures. Instead, you just write your code using if-statements and the unused code paths (any code path which is not executed, due to the condition for the branch being false or an earlier branch being taken instead) are dropped from the generated code (the native assembly code generated by the JIT at runtime). It is essential that you guard usage of hardware intrinsics with the appropriate IsSupported check. If your code is unguarded and runs on a machine or architecture/platform that doesn’t support the intrinsic, a PlatformNotSupportedException is thrown by the runtime. What benefits do these provide me? Hardware Intrinsics definitely aren’t for everyone, but they can be used to boost perf in some computationally heavy workloads. Frameworks such as CoreFX or ML.NET take advantage of these methods to help accelerate things like copying memory, searching for the index of an item in an array/string, resizing images, or working with vectors, matrices, and tensors. Manually vectorizing some code that has been identified as a bottleneck can also be easier than it seems. Vectorizing your code is really all about performing multiple operations at once, generally using Single-Instruction Multiple Data ( SIMD) instructions. It is important to profile your code before vectorizing to ensure that the code you are optimizing is part of a hot spot (and therefore the optimization will be impactful). It is also important to profile while you are iterating on the vectorized code, as not all code will benefit from vectorization. Vectorizing a simple algorithm Take for example an algorithm which sums all elements in an array or span. This code is a perfect candidate for vectorization because it does the same unconditional operation every iteration of the loop and those operations are fairly trivial in nature. An example of such an algorithm might look like the following: The code is simple and understandable, but it is also not particularly fast for large inputs since you are only doing a single trivial operation per loop iteration. Improving the perf by unrolling the loop Modern CPUs have many ways of increasing the throughput at which it executes your code. For single-threaded applications, one of the ways it can do this is by executing multiple primitive operations in a single cycle (a cycle is the basic unit of time in a CPU). Most modern CPUs can execute about 4 add operations in a single cycle (under optimal conditions), so by laying out your code correctly and profiling it, you can sometimes optimize your code to have better performance, even when only executing on a single-thread. While the JIT can perform loop unrolling itself, it is conservative in deciding when to do so due to the larger codegen it produces. So, it can be beneficial to manually unroll the loop in your source code instead. You might unroll your code like the following: The code is slightly more complicated but takes better advantage of your hardware. For really small loops, the code ends up being slightly slower, but that normalizes itself for inputs that have 8 elements and then starts getting faster for inputs with even more elements (taking 26% less time at 32k elements). It’s also worth noting that this optimization doesn’t always improve performance. For example, when handling float, the unrolled version is practically the same speed as the original version, so it’s important to profile your code accordingly. Improving the perf by vectorizing the loop However, we can still optimize the code a bit more. SIMD instructions are another way modern CPUs allow you to improve throughput. Using a single instruction they allow you to perform multiple operations in a single cycle. This can be better than the loop unrolling because it performs essentially the same operation, but with smaller generated code. To elaborate a bit, each one of the add instructions from the unrolled loop is 4 bytes in size, so it takes 16-bytes of space to have all 4 adds in the unrolled form. However, the SIMD add instruction also performs 4 additions, but it only takes 4 bytes to encode. This means there are less instructions for the CPU to decode and execute each iteration of the loop. There are also other things the CPU can assume and optimize around for this single instruction, but those are out of scope for this blog post. What’s even better is that modern CPUs can also execute more than one SIMD instruction per cycle, so in certain cases you can then unroll your vectorized code to improve the performance further. You should generally start by looking at whether the general-purpose Vector<T> class will suit your needs. It, like the newer hardware intrinsics, will emit SIMD instructions, but given that it is general-purpose you can reduce the amount of code you need to write/maintain. The code might look like: The code is faster, but we have to fall back to accessing individual elements when computing the overall sum. Vector<T> also does not have a well-defined size and can vary based on the hardware you are running against. The hardware intrinsics provide some additional functionality that can make this code a bit nicer and faster still (at the cost of additional code complexity and maintainence requirements). NOTE: For the purposes of this blogpost, I forced the size of Vector<T> to 16-bytes using an internal configuration knob ( COMPlus_SIMD16ByteOnly=1). This normalized the results when comparing SumVectorT to SumVectorizedSse and kept the latter code simpler. Namely, it avoided the need to write an if (Avx2.IsSupported) { } code path. Such a code path is nearly identical to the Sse2 path, but deals with Vector256<T> (32-bytes) and processes even more elements per loop iteration. So, you might take advantage of the new hardware intrinsics like so: The code is again slightly more complicated, but it’s significantly faster for all but the smallest workloads. At 32k elements, it’s taking 75% less time than the unrolled loop and 81% less than the original code. You’ll notice that we have a few IsSupported checks. The first checks if the hardware intrinsics are supported for the current platform at all and falls back to the unrolled loop if they aren’t. This path will currently be hit for platforms like ARM/ARM64 which don’t have hardware intrinsics or if someone disables them for any reason. The second IsSupported check is in the SumVectorizedSse method and is used to produce slightly better codegen on newer hardware that additionally supports the Ssse3 instruction set. Otherwise, most of the logic is essentially the same as what we had done for the unrolled version. Vector128<T> is a 128-bit type that contains Vector128<T>.Count elements. In the case of uint, which is itself 32-bits, you have 4 ( 128 / 32) elements, which is exactly how much we unrolled the loop by. Summary The new hardware intrinsics allow you to take advantage of platform-specific functionality for the machine you’re running on. There are approximately 1,500 APIs for x86 and x64 spread across 15 instruction sets and far too many to cover in a single blog post. By profiling your code to identify hot spots you can also potentially identify areas of your code that would benefit from vectorization and see some pretty good performance gains. There are multiple scenarios where vectorization can be applied and loop unrolling is just the beginning. Anyone wanting to see more examples can search for uses of the intrinsics in the framework (see the dotnet and aspnet organizations) or in various other blog posts written by the community. And while the currently exposed intrinsics are extensive, there is still a lot of functionality that could be exposed. If you have functionality you would like exposed, feel free to log an API request against dotnet/corefx on GitHub. The API review process is detailed here and there is a good example for the API Request template listed under Step 1. Special Thanks A special thanks to our community members Fei Peng (@fiigii) and Jacek Blaszczynski (@4creators) who helped implement the hardware intrinsics. Also to all the community members who have provided valuable feedback to the design, implementation, and usability of the feature. How do I ensure proper alignment? When I tried to use Avx2 intrinsics, I noticed unaligned versions of vector loading were used. The VEX encoding (encoding used by AVX and later ISAs) does not do alignment checking for most memory operands. This is in contrast to the legacy encoding used by SSE that does (for the most part). You can explicitly enforce alignment checking by using the `LoadAligned` intrinsic; but you may get less efficient codegen as the load will be a separate instruction rather than folded into the instruction that consumes the load. On modern CPUs (basically any CPU that is less than 10 years old), unaligned loads are generally as fast as aligned loads; provided that load doesn’t cross a cache-line or page boundary. So, it is generally sufficient to pin your memory, get to the first aligned address, and then use unaligned loads to operate on the data (which guarantees it won’t cross a cache-line or page boundary). This ensures you have both alignment and efficient codegen. You can then add something like a `Debug.Assert((address % expectedAlignment) == 0)` to help catch any bugs around alignment at runtime. In the last version of the code, how come it’s checking Sse.IsSupported, but then it’s using Sse2 without further checking? A typo on my end, I’ve fixed in the gist and it should now be updated above. Thanks! This comment has been deleted. Main question: why third version (SumVectorT) is not as fast as version with explicite intrinsics (SumVectorizedSSE2) ? Why compiller didn’t use same CPU instructions? What makes it slower? It is a general purpose API and so it can’t always generate the same code. In this particular case, it is accessing data via a Span<T> and there are bounds checks that the JIT isn’t able to elide (the same would be true of accessing via an array). The HWIntrinsic code, on the other hand, is pinning the underlying buffer and access the data via a pointer and explicit load instructions. Not only is the JIT able to generate slightly better code for this (as what you want done and the instructions you want emitted are being explicitly specified), but accessing the data via the raw pointer allows the bounds checks to be elided. There are certain new language features (such as `unmanaged constructed types`:) which will allow you to bypass the bounds checks here as well (by operating on a `Vector<int>*`), in which case the numbers are more comparable. But, there would likely still be slight codegen differences due to it being a general-purpose API. I left a comment here regarding some issues with the benchmark code. The current code doesn’t give a good comparison between using Vector<T> and intrinsics. Just noting that I responded to this on reddit 🙂 I wrote a post about how to optimize C# using SIMD instructions, although it’s in spanish you can see that it’s easy to get a x10 speedup | Method | Mean | Error | StdDev | |—————- |———–:|———-:|———-:| | FindWithMinSIMD | 3.696 ns | 0.0225 ns | 0.0200 ns | | FindWithLINQ | 182.543 ns | 3.5925 ns | 4.2767 ns | | FindWithLoop | 29.490 ns | 0.1920 ns | 0.1796 ns | I uploaded the code to Github On one hand any progress in number crunching is a good news, but on the other hand C# does not support basic math in generic form (when you want to add, multiply, etc. some data but you don’t the specifics whether they are shorts, ints, etc). So I really wish MS would take to its heart the very basics and then move to improve advanced stuff. For dead simple `a+b` I have to write pretty convoluted code and each solution you can think of is uglier than the other. Having `ints`, `doubles`, etc with some INumerics common interface could help (or support for C++ like templates for code like this). In general anything, that finally fixes this problem. I would recommend commenting on one of the appropriate issues on the dotnet/csharplang repo on GitHub. I believe the “Type Classes” () and/or “Roles” () proposals are likely the closest match to what you want. Tanner, could you please explain why you passively lie by hiding the fact that Mono has had this feature for more than a decade – ? The blog post is about .NET Core and the RyuJIT compiler, it is not about Mono and does not go into detail about other languages (such as Rust, Go, or Swift) or frameworks (such as Mono) which provided similar functionality. Mono.Simd was also slightly different and not quite as extensive as this functionality (it falls slightly between the System.Numerics and the System.Runtime.Intrinsics work). It also did not provide the same raw level of control over what CPU instructions were emitted for any given API call or break it up into the specific ISAs. Why do I need to bother with manually unrolling loops and doing basic vectorization in 2019? GCC and LLVM/Clang both happily produce unrolled SSE code just fine on the equivalent of Sum() here, and they don’t even have the benefit of being able to detect your CPU’s capabilities at runtime like a JIT can. With tiered compilation there’s really no excuse why RyuJIT couldn’t do most of the optimizations that are available to C++. Make it yet another LLVM frontend for all I care. If I wanted to meticulously micro-optimize my code at the level presented in this article I would be using C++ instead of C# to begin with. The blog post touches on this briefly but does not go into detail. > While the JIT can perform loop unrolling itself, it is conservative in deciding when to do so due to the larger codegen it produces. So, it can be beneficial to manually unroll the loop in your source code instead. To expand. AOT compilers (which, for brevity here, will include things like the native Clang or MSVC compilers, as well as things like MonoAOT) are not time constrained and have basically unlimited time to do various analysis and optimizations. A JIT compiler, however, is live and has stricter time constraints since it impacts how fast a particular method is the first time it executes. This means that some more complex optimizations are not feasible to do, especially when a method could potentially be “cold” (only called a few times or less throughout the entire lifetime of the program). Some new features, like Tiered Compilation (), will allow “hot methods” to be recompiled with more advanced optimizations in the future (so startup is still fast, but steady state performance improves as the program continues executing). Loop unrolling and auto-vectorization are two optimizations that generally fall into the category of “expensive” to do, so if the JIT wants to allow it happen more extensively, it likely needs to be done after a method (or loop) has been detected to be hot. Additionally, relying on loop unrolling and/or auto-vectorization is not always desirable. For very perf critical scenarios the codegen can be worse than a manually written loop and since the compiler is detecting specific code patterns to optimize, it can be broken or changed by what appears to be a trivial refactoring (although compilers are getting better at optimizing more algorithms). I agree with László, this case with manual vectorization of sum looks silly. In fact, in this post you are trying to create hardware dependend code snippets to let JIT compiler include them into hardware independend IL. There is no excuse to compiler forcing you to do it manually. In addition, there are other places and tools where IL can be optimized like .Net Runtime Optimization Service on Windows and NGen / CrossGen, but it’s not. Finally, .Net team could add some attribute to mark performance critical methods and allow us control what should be vectorized by JIT and what is not important, because this is application developer’s choise, after all. Unfortunatelly, it seems like CLR team just don’t want implement optimizations and .Net Framework team have to invent such weird features like this one. I agree with László – grunt work like unrolling loops should really be the job of the compiler.. There are existing issues (such as) logged against dotnet/coreclr suggesting that the JIT more aggressively perform auto-vectorization. I would suggest commenting on those issues with some reasoning or examples of where that would be beneficial for your applications. However, as I’ve stated in other comments, that is just a nice feature for non-performance critical paths. Even with compilers that are good at auto-vectorization (i.e. GCC, Clang, or MSVC), they still expose and internally use intrinsics like these (or even hand coded assembly) for performance critical hot paths. The compiler implicitly vectorizing is nice, but sometimes simple refactorings to your code can drastically change how that vectorization is done or if it is recognized at all, in which case being able to manually do it ends up helping a lot. The blog post gave this trivial example as an introductory post to hardware intrinsics. Real world examples can be much more complex and take better advantage of the approx. 1500 APIs we’ve exposed. I had an issue about this topic today, wrote a method that sums all the rows of a matrix, so the row count of matrix becomes 1. I wrote it in visual C++ and in C# using intrinsics. I enabled all the optimization options in C++, enable intrinsics (AVX2) and all other stuff. Guess what happened? C# version was x2 faster than C++ version. So It seems @Tanner is right about compilers sometimes can’t generate the best code. Also if you are developing a project that needs to be extremely optimized like I am developing one (), you should always examine asm code and can’t trust to the compiler that it will generate the fastest code. Gpu programming is another part of the topic, however you can’t be depended on the compiler. My library in C# works on Cpu, to train mnist dataset for 10 epochs, it takes 9 sec, whereas cntk takes 6.5 sec. I use %50 of cpu, cntk uses %90-99. Still couldn’t parallelize the library 🙁. How about Matrices ? Matrix multiplication and inversion is really intensive (especially from 4X4 and higher). I’ve once done it in C++ for 3DNow! (RIP), so the order of operations is essential for performance. SSE is ideal for Matrices, Vectors and FFT, especially for mult and invert operations. On the other hand, for lager operations the GPU becomes the better solution. Inversion can be performed via Cramer for 4X4 and below, but should be implemented in Gauss for higher dimensions. Cramer can benefit from Intrinsics, but it’s hard for Gauss. I’m currently using a self implemented Gauss for matrix inversion (self implemented because I rather need numerical stability than performance, ‘cos it’s only performed once per session), but however, for mx inversion intenxive calculations hw acceleration (SSE or GPU) would be a helpful feature. Hi Tanner, I’ve noticed some very odd code generation from some of the intrinsic API’s; for example, the code below was emitted for the Permute4x64 function as invoked from a simple wrapper: ; function: Vector256 perm_256x64i(Vector256 ymm0, byte imm8) 0000h push rsi 0001h sub rsp,50h 0005h vzeroupper 0008h mov rsi,rcx 000bh vmovupd ymm0,[rdx] 000fh mov rcx,rsi 0012h vmovupd [rsp+20h],ymm0 0018h lea rdx,[rsp+20h] 001dh movzx r8d,r8b 0021h call 7FFC7C09A120h 0026h mov rax,rsi 0029h vzeroupper 002ch add rsp,50h 0030h pop rsi 0031h ret The amount of memory shuffling is really disturbing, but most disturbing as that the intrinsic instruction itself (VPERMQ) is never invoked (or maybe it is invoked by the far call???) Any idea what’s going on here? This issue is apparently happening with a large number of intrinsic functions, including both shuffle and blend intrinsics. In fact, wherever a byte mask is used to control memory movement, code similar to the above is generated and the intrinsic itself never gets invoked. IMO, C#/.Net has always had a dysfunctional approach to any integer type less than 32-bits. Is the problem I’m noticing with the intrinsic code generation somehow related to this situation? As it stands, any intrinsic function where memory movement is controlled by a single byte mask is not really usable from a performance perspective! I haven’t gone through them all, but I have yet to find a counterexample. On the other hand, permutations/shuffles controlled by a vector, of bytes or otherwise, seem to be fine. Here is one more example. The code generated for vpblendvb is as expected: ; function: Vector128 vpblendvb(Vector128 xmm0, Vector128 xmm1, Vector128 xmm2) 0000h vzeroupper 0003h xchg ax,ax 0005h vmovupd xmm0,[rdx] 0009h vmovupd xmm1,[r9] 000eh vpblendvb xmm0,xmm0,[r8],xmm1 0014h vmovupd [rcx],xmm0 0018h mov rax,rcx 001bh ret Now, here is the code generated for vpblendw predicated on a byte immediate: ; function: Vector128 vpblendw(Vector128 xmm0, Vector128 xmm1, byte imm8) 0000h push rsi 0001h sub rsp,40h 0005h vzeroupper 0008h mov rsi,rcx 000bh vmovupd xmm0,[rdx] 000fh vmovupd xmm1,[r8] 0014h mov rcx,rsi 0017h vmovapd [rsp+30h],xmm0 001dh vmovapd [rsp+20h],xmm1 0023h lea rdx,[rsp+30h] 0028h lea r8,[rsp+20h] 002dh movzx r9d,r9b 0031h call 7FFC89589570h 0036h mov rax,rsi 0039h add rsp,40h 003dh pop rsi 003eh ret There are a few existing issues tracking this, for example: * * * Basically, the JIT needs to support hardware intrinsics for both direct and indirect invocation. This ensures that hardware intrinsics can be used via reflection, in the immediate window/debugger, or with non-constant inputs. The JIT is currently only doing the check on if the input is a constant during IL importation and so it can miss certain values that will eventually be constant such as simple method wrappers or other constant folding done later in the compilation. The fix is for the JIT to delay the decision of whether to emit the direct instruction or the fallback method call until later in the compilation (likely in the lowering phase) so that it can currently handle these cases. This issue will repro for anything where the instruction requires a constant input, but the workaround is generally to just remove the helper method and invoke it directly instead. As an end-user of the API, how can I take advantage of this workaround? Would I have to change the code in the Core CLR (which code, specifically?) and make a custom build of the CLR? Thanks, Chris The workaround is to just not create wrapper methods around the primitive types for right now. The actual fix is more involved and requires changes to the JIT itself. It is being tracked and prioritized as appropriate based on customer need/feedback. How does all this play with Azure VMs? Will we still be able to make use of intrinsics on a VM that uses vCPUs? The intrinsics will work on VMs as well. You should consult Azure for details on what CPUs particular virtual machine series use and therefore which instruction sets should be available. This is disappointing. I much prefer to write portable code, and I hope Vector<T> will be enhanced in the future with some of the intrinsics offered here. At present, it’s amazing how little it can do. We are open to API proposals or feature requests which can be logged against dotnet/runtime on GitHub. The hardware intrinsic APIs are meant to fill the gap where there is something that can’t be or isn’t yet exposed in the more portable APIs. There is a limit to what Vector can expose specifically because it is general purpose. Not all processors support the same instructions or expose them in the same manner/behavior, so what can be done in a consistent cross-platform manner while still providing performance can be tricky. This is true for just x86/x64 but becomes more apparent when you also consider ARM, ARM64, or one of the many targets supported by other runtimes such as Mono. Slightly off-topic: is this code from the post ok? Are two consecutive calls to HorizontalAdd supposed to sum all items in the vector? I’m trying this, but it keeps returning 6 instead of 10: (yes, I know I’m using Avx and double precision values, but I thought it would work the same; the Shuffle thing works fine for me) … the first HorizontalAdd call converts {1,2,3,4} into {3,3,7,7}, but the second one returns {6,6,14,14}. Most of the Vector256<T>operations don’t operate as if it was a single contiguous 256-bit buffer. Instead it operates as if it was 2×128-bit buffers. This is why it is summing ((3, 3), (7, 7))rather than (3, 3, 7, 7). You can do this a few ways, such as: -or- Got it! Nice trick, thank you.
https://devblogs.microsoft.com/dotnet/hardware-intrinsics-in-net-core/
CC-MAIN-2020-16
refinedweb
4,845
52.09
WSDL Tales From the Trenches, Part 3 August 5, 2003 Defining Data.. Importing data definitions. Schema Design Styles. Namespaces. Elements, types and attributes that belong to a namespace are said to be qualified. The declaration of a target namespace is a necessary, but not sufficient condition for elements, types and attributes to be qualified. So when are they qualified and when unqualified? Let us deal with types first, they are easy: globally defined types, both simple and complex, are always qualified. Locally defined types are anonymous and so there is no way of referencing them; the question to which namespace they belong is purely academic. Global element declarations are also easy: globally declared elements are qualified. To illustrate what we know so far, this instance document is validated by this schema. We see indeed that the 2 globally defined elements Element and Response are part of the target namespace; the locally defined Collection element is not. Whether or not attributes and locally defined elements are qualified is governed by the form attribute. The attribute can take 2 values: qualified and unqualified. Therefore, in order to qualify the Collection element in our previous example, it can be reworked as so. You will find that it validates this document. form is not a required attribute, neither when declaring attributes nor local elements. form is assigned a value implicitly, either by respectively the value of the elementAttributeDefault and attributeFormDefault attribute on the schema element, or by the default value of these attributes; the default value is unqualified in each case. So here is another schema that validates the document. Note that the Russian doll and Venetian blinds example schemas must stipulate that elements are qualified by default in order to validate the same instance document as the salami slice example. WSDL 1.1 recommends setting the elementFormDefault to qualified and keeping the default for attributeFormDefault. This should minimize the use of explicit namespace qualifiers if you judiciously set the schema's target namespace as the default namespace in your messages. We have only skimmed the surface here; W3C XML Schema (see Resources for a full reference) devotes a complete chapter to controlling namespaces. However, the questions that you will most likely encounter are covered. Compositors W3C XML Schema has 3 compositor elements that construct complex data types from simpler ones: sequence, choice and all. Particles are nested inside compositor elements. A sequence defines a compound structure in which the particles occur in order. The particles within a choice are mutually exclusive. However, there may be multiple occurrences of the chosen particle. all defines an unordered group. For all three compositors, the number of legal occurrences of the particles within them is governed by the maxOccurs and minOccurs attributes on those particles. These attributes are not required and their default value is 1. The simplest particle is an element. sequence and choice can both act as particles too. all cannot. The sequence compositor is the one that is most often encountered in WSDs. This seems a good choice; even if, conceptually, particles could occur in any order, nailing down the order will make parsing of messages that bit easier. However, implementations often do not observe the order constraints. This can be shown by invoking a web service with elements in a different order from the one laid down by a sequence: it often does not seem to matter. That is not such a bad thing. After all, if the server is more liberal in what it accepts than it strictly needs to be, this does not harm well-behaved clients and it offers some margin for error on more sloppily implemented clients. In other words, a server that did this can hardly be accused of being in breach of contract. Not so if the server cannot guarantee the order of the particles that are being sent back. Faced with such a server implementation, I spent a good deal of time working through the ramifications of this once upon a time. The first reflex is to replace sequence with all compositors. However, be aware that the remedy is not without its problems since the expressiveness of this compositor has been severely curtailed in the WXS spec. A detailed account of why this is so and what the precise constraints are, is beyond the current scope. However, the main limitation has already been pointed out: all cannot be used as a particle. Since derivation by extension in effect uses the compositor of the base type as a particle in the subtype, opportunities for reuse of types defined with all are limited. Derivation is covered in further detail in a dedicated section. Schema versions The current WXS Recommendation is 1.0 and its namespace is. However, some implementations still being used today follow the specifications of previous working drafts, e.g.. This is unfortunate and the perpetrators should be encouraged to migrate to the released standard, but if you should come across such implementations, here are two of the common pitfalls. Firstly, there is a WXS data type in common use that has changed from the 1999 to the 2001 version: 1999's timeInstant became 2001's dateTime. Make sure that the data type you use fits the version of WXS. Secondly, derivations also changed significantly between 1999 and 2001. These will be covered in the following section. Derivations Derivation is a technique to define subtypes of a given base type. There are two kinds of derivation in WXS: extension and restriction. The former adds components at the end of the content model of the base type, the latter constrains the base type. Hence valid instances of a subtype derived by extension are not necessarily valid instances of the base type. Valid instances of a subtype derived by restriction, on the other hand, are always valid instances of the base type. A subtype may be used anywhere where its base type is used, unless otherwise specified. This may have the following impact on message definitions: assume that a message definition declares a part with type Foo, and Bar is derived by extension from Foo. A party may send an element of type Bar in such message. The recipient may be unable to validate this message. Fortunately, it is possible to turn off the ability to substitute subtypes for base types by using the block attribute on the base type or on an element declared to be of a given base type. Beware of derivation by extension, that is the message of this section so far. But what with derivation by restriction? From the discussion so far, it seems reasonable enough. However, using it may seem less attractive if the need is realized to list each particle of the content model of the subtype explicitly. This makes for very verbose definitions. It also does not bring the modularity benefits that an inheritance hierarchy in an OO programming language might bring: common features are not factored out, but must be repeated in each subtype. This is a change w.r.t. W3C XML Schema 1999 that caused a good deal of confusion. Arrays Defining an array is one of the most confusing issues in WSDL. It has also caused a great deal of interoperability problems. Proceed with caution; a common approach is to extend the Array type defined in the SOAP encoding schema. In fact, this is mandated by WSDL 1.1 (see section 2.2). I was therefore surprised to see that the rules 2110 through to 2112 of the WS-I Basic Profile Working Group overrules this. On the other hand, I understand their position: WSDL 1.1 makes a pig's ear of array specifications. The basic profile's approach, on the other hand, is simple. When I originally planned this article, it was my intention to write a good deal about SOAP arrays, how to use them in WSDs that are as near correct as is possible given the flaws in WSDL 1.1. However, given the basic profile's recommendation, the sensible thing is to avoid them altogether. Conclusions The purpose of this article was to flag some of the issues that require attention when modeling data. You should be underestimate neither the importance of defining data nor the complexity of the task. It is important because the data passed across the web service interface largely determine the quality of the interface. It is complex because data modeling is inherently complex. Nonetheless, I cannot help feeling that XML W3C Schema 1.0 does not mitigate this complexity adequately. I look forward to tools better suited to data modeling for web services. Resources The W3C has published two normative documents on the XML Schema: XML Schema Part 1: Structures and XML Schema Part 2: Datatypes. There is also a non-normative primer. XML Schema by Eric van der Vlist, published by O'Reilly, 2002, proved to be an invaluable companion in my encounters with W3C XML Schema. Warmly recommended to anyone who is serious about data modeling with WXS. xFront has an item on global versus local element and type declarations in its excellent best practices section. While you are browsing the xFront, do have a look at what they have to say about web services as well, which is controversial and thought-provoking.
https://www.xml.com/pub/a/ws/2003/08/05/wsdl.html
CC-MAIN-2022-05
refinedweb
1,549
55.64
collected the results of the VXL Compiler Survey. A tabulation of the results and a copy of the messages received has been posted at: In summary, people are using MS Visual Studio 6.0 and above and GCC 3.3 and above. No one reponded with compilers such as Borland, ICC, etc., although Fred Wheeler does keep some of these combinations in the dashboard. In my experience, the people using gcc wouldn't have any problems in upgrading to a higher version if necessary and tend to be more up-to-date given the nature of it's distribution (i.e., not commercial app). Hence, nobody seems to be tied to gcc2.95, for example. This is not true for people using MSVS. However, most people using VS 6.0 are willing to drop it and move on. This is with the exception of two responses. Markus Meyer, which also uses gcc, and Brad King on behalf of ITK. Here Brad King points out that there has been talk in ITK about dropping it and, more importantly, that "Dropping support for VS 6 does not have to mean all of VXL." It would probably be worth mentioning at this point that even Microsoft does not support VC++ 6.0 anymore (retired extended support). IMHO, I think there are a lot of modern programming techniques that are useful and which VXL should take advantage of. For example, there was a discussion in the list recently about static asserts, factories, singleton_holders, etc. to which Fred Wheeler commented about including such things in vbl: "I have no objection and defer to the wisdom of this list. My name is next to vbl because we decided each library should have a lead developer, but I have not touched vbl in a long time. If there is a more appropriate and willing person they are welcome to take over the role." I think that the responsible approach to take is to create a contrib library (say contrib/vbl2, which I would volunteer to maintain) or use an already created one like mul/mbl (although this one has a bit more than basics, it seems) as a place to test-drive, put up for promotion to the core, and post for review and comments code such as the static assert, etc. After we see the effects of each independent piece of code to the dashboard we can consider what are the ramifications of promoting it to the core in terms of relaxing rules and compiler support. We will also gain insight on what parts of the standard are robustly supported and decide wether to allow these parts on the core in general or not. In other words, why not take it one step at a time instead of commiting to changes in the rules prematurely? Any comments about this proposal? Finally, I would like to point out the email from Matt Sandler () mentioning that, given modern compilers, maybe there is "an opportunity to simplify some aspect of the labeling schemas [i.e., abuse of prefix in names], such as by using namespaces, etc. to improve legibility". I just point it out for completeness in case it is worth discussing, since I don't know the history concerning this and suspect there is little or no interest to change this approach. --Miguel I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/vxl/mailman/vxl-maintainers/thread/43E6CC25.6050106@msu.edu/
CC-MAIN-2017-04
refinedweb
598
71.95
Django OutboxDjango Outbox Capture all mails sent and show it in a simple web interface. Quick StartQuick Start Install the package in your environment: $ pip install django-outbox Configure your django development settings file to use file based email backend: from os import path EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_PATH = path.join(ROOT_PATH, 'tmp', 'app-mails') Also add django_outbox to your installed apps: INSTALLED_APPS += ( 'django_outbox', ) Add the django outbox url to your urls.py: # urls.py from django.conf import settings # This will prevent from showing the outbox in production. The outbox # will only be available when the DEBUG setting is true. if settings.DEBUG: urlpatterns += patterns('', url(r'^outbox/', include('django_outbox.urls')), ) Now just run your application in debug mode and access /outbox. All should be working! ContributingContributing This project use pytest_. To run the tests just type: $ py.test
https://libraries.io/pypi/django-outbox
CC-MAIN-2019-35
refinedweb
143
52.46
_lwp_cond_reltimedwait(2) - get or set supplementary group access list IDs #include <unistd.h> int getgroups(int gidsetsize, gid_t *grouplist); int setgroups(int ngroups, const gid_t *grouplist); The getgroups() function gets the current supplemental group access list of the calling process and stores the result in the array of group IDs specified by grouplist. This array has gidsetsize entries and must be large enough to contain the entire list. This list cannot be larger than NGROUPS_UMAX. If gidsetsize equals 0, getgroups() will return the number of groups to which the calling process belongs without modifying the array pointed to by grouplist. The setgroups() function sets the supplementary group access list of the calling process from the array of group IDs specified by grouplist. The number of entries is specified by ngroups and can not be greater than NGROUPS_MAX. Upon successful completion, getgroups() returns the number of supplementary group IDs set for the calling process and setgroups() returns 0. Otherwise, -1 is returned and errno is set to indicate the error. The getgroups() and setgroups() functions will fail if: A referenced part of the array pointed to by grouplist is an illegal address. The getgroups() function will fail if: The value of gidsetsize is non-zero and less than the number of supplementary group IDs set for the calling process. The setgroups() function will fail if: The value of ngroups is greater than {NGROUPS_MAX}.)
http://docs.oracle.com/cd/E26505_01/html/816-5167/getgroups-2.html
CC-MAIN-2017-17
refinedweb
232
60.75
Al is DDJ's senior contributing editor. He can be contacted at astevens@ddj.com. There really isn't a platform named YAPP (that I know of). I made it up because it seems that I spend a lot of time evaluating C++ application framework class libraries for Linux GUI programming in search of the perfect one, and all I seem to do is yap about it. More about that later. Effective STL I'm leading this column off with a book report, something I rarely do, but this time it's important. I really want you to read Effective STL by Scott Meyers, Addison-Wesley, 2001; ISBN 0-201-74962-9. This is the third in a series of books by Scott that follow a common theme. The first two are Effective C++ and More Effective C++, both reviewed here in the past. Scott presents in his books a number of essays on how to use C++ and, in this new book, the STL. He calls his essays "Items." Each item addresses a specific issue with respect to some aspect of the book's purpose. Effective C++ has 50 items, More Effective C++ has 35, and Effective STL has 50. Scott assumes you already have a working knowledge of C++ and the STL. Each item addresses a specific issue where you might come up with several ways to do something, or you might make specific assumptions about the consequence of some decision, such as which container to use for a particular application. Then Scott imparts the wisdom of his own experience and that of many of his colleagues with whom he collaborated to isolate and develop the items. Here's how you might do something. Here are several ways you might do it. Here's what you really ought to do. Here's why. Most items contain references to other items. It's difficult to get a handle on such a complex subject in such a concise manner, but Scott succeeded. The writing is clear and to the point. Veteran STL programmers will instantly recognize some of the issues and will be surprised by some others. There are things that just never occurred to you. Others that you thought you understood but really didn't. I have not found a single item with which I disagree. I found several that changed how I use the STL and others that led me to use the STL in ways that had not occurred to me. If you program with STL, you need this book. If you don't, read the book anyway. It just might make you want to. A Confusion of Jargons To quote Strother Martin: "What we have here is failure to communicate." GUI programming jargon is hardly universal with no accepted standard, and it is frequently confusing. Let's try to clear up some of it. Programmers for various GUI platforms use different terminology to describe the mechanism by which code executes as a result of an external stimulus. They also use other words to mean the things that a GUI displays. An "event" is, in most parlances, the external thing that causes the program to respond. Mouse clicks and movements and keyboard presses are the most common events. Timer ticks and timeouts are among the others. This vague concept is called "event-driven" programming. The operating system or GUI platform translates events into what Windows programmers call "messages." Messages can beget other messages. A mouse click can generate a menu command, for example. Processing these messages is called "message-based" programming. To write a Windows program, you employ event-driven, message-based programming. The use of the term "message" harks back to when Windows programmers coded in C. Windows has hundreds of defined messages that the code for a window can intercept and process. The term, however, collides with the same word that means "invocation of a method" in object-oriented programming (pure and otherwise). To further stir the broth, "method," in most OO languages, becomes "member function" in C++. Every element displayed by Windows is called, not surprisingly, a "window." We've become accustomed to that term, but it's an odd analogy that mixes metaphors and rarely resembles the thing for which it is named. A button is a window; a list is a window; a menu is a window; a dialog is a window. Windows can have windows in a parent-child relationship. Nothing about all this resembles a real window, which does not disappear when you close it, which you can see through when you open it, which passively displays things beyond it, and which has no children or parents. The code that executes for a window in response to a specific message has no name in traditional Windows C programming. All messages are processed as cases of a switch in a single "window processing" function. With the Windows API now wrapped in C++ classes, each message gets its own member function. There is no formal name for that kind of function. To summarize: An event generates a message, which is processed by a member function in the name of a window. A message is a "signal" in the KDE and Gnome development environments. But wait. A signal is something else in traditional UNIX programming. They had to know there would be confusion. I guess no other synonym for "message" presented itself; and they couldn't stoop to using Windows conventions. Under *nix GUI programming, the code that executes in response to a signal is called a "slot," and the things that the GUIs display are called "widgets," a name inherited from OSF/Motif. "Widget" is a better name than window, because there is no real-world thing called a widget, which is a generic term for anything mechanical. (Perhaps GNOME should have used "gadget" instead, which means the same thing, since they both start with G.) To summarize: An event generates a signal, which is processed by a slot in the name of a widget. Now that we all understand the same words, we can communicate. What's to Like? Last month, I listed some of the things not to like about the QT class library, the base application framework for writing programs to run under the KDE desktop on Linux and other UNIX-like operating systems. QT is for other platforms, too, but my focus is on Linux these days. I'll summarize last month's criticisms here. - No namespaces. - Language extensions to implement slots. - The metaobject compiler. - An ill-organized and unnecessary RTTI mechanism. - Custom rather than standard containers. - Questionable C++ coding conventions. See last month's column for details. I can put up with most of these shortcomings, although my teeth are wearing down from so much gritting. But this month, I add a complaint that makes programming with QT and the derived KDE class libraries unpalatable to this C++ programmer. Take a close look at Example 1. What's wrong with this code? According to the conventions for QT programming, nothing is wrong, the program is correct. But according to me, something is seriously wrong with this program. The program instantiates a QApplication object on the stack and a QLabel object on the heap. It sets the QLabel object as the main widget of the QApplication object, tells the QLabel object to show itself, and executes the QApplication object. The program exits when the QApplication::exec function returns. It's a typical GUI application. But what's missing? Carefully notice that the program does not delete the QLabel object that it instantiated on the heap with the new operator. This means that the QApplication object must do the delete in its destructor to avoid memory leaks. This means that you must instantiate all widget objects on the heap. But what if you don't? If you instantiate a widget on the stack or in external or static memory, the program fails when the parent object deletes the widget. No portable way exists for a program to determine whether something's address is in heap memory space, so the widget's parent is going to delete it no matter what its address is. You're in a heap of trouble. If you instantiate the widget on the heap as you must but then delete it yourself, as you are conditioned by your proper upbringing to do, the program fails when the parent deletes the widget a second time. Another heap of trouble. This convention is downright bad. It encourages bad coding practices by getting programmers accustomed to using new without delete as a routine practice. I can't accept, endorse, or use a class library that behaves this badly. That's a shame, because the KDE development environment shows promise for becoming a widely used platform. The bar is being lowered. In my programming philosophy, a program balances the acquisition and disposal of system resources in such a way that the two parts are in view of the programmer wherever possible. If a function uses the new operator, that function should use the delete operator on the same pointer sometime before the function returns to its caller; see Example 2. That's simply elementary C++ style. If you program that way, you'll make fewer memory-management mistakes. If an object's pointer is a data member, every delete is accompanied by an assignment to the pointer of a zero value or by another new assignment so that an extra delete somewhere has no ill effects. Consider Example 3. If addbar is never called, or if it's called many times, heap management stays well balanced and safe. You don't have to write code this way, and sometimes you can't. But an architecture that requires you to make heap allocations that you do not delete is fundamentally unsound. Why should I even have to preach about this? Because some very influential programming environments are encouraging programmers to do the wrong thing, that's why, and something needs to be said about it. I expect mail on this matter. I expect some programmers to get squarely in my face about it, arguing that the technique works and that some large number of programs have been successfully developed and deployed with this approach, somehow validating such deplorable practices despite their obvious shortcomings. Examples of other libraries that do similar things will be offered to prove me wrong. (The same thing happened a few years ago when I said not to code delete this;.) It shall be argued that these practices can't possibly be shortcomings at all since so many programmers accept and embrace them. A lot of people are still driving on Firestone tires, too. Gnome's Not KDE I said last month that programmers will probably prefer the look-and-feel of KDE for their applications over that of GNOME, which mainly was me saying that's what I want. But my subsequent lament about KDE class libraries sent me looking at the GNOME development tools, which gave me a nice surprise. development. GNOME is based on component object technology. It employs CORBA-like technology, which was originally called ORBit and was almost replaced by something named Bonobo. I don't know much about either architecture, but apparently they are core to the GNOME philosophy. Much controversy surrounds these libraries and what should be included in the next release of GNOME. Disagreements on what should be released caused one of the primary GNOME maintainers to step down in protest. The surrounding flak made us casual onlookers believe that the project was in jeopardy, particularly considering the overwhelming success of GNOME's major competitor, KDE. I wouldn't worry, though. These open-source projects are informally staffed by volunteers. Anyone who has ever been active in a PTA, the JayCees, or on a condominium board of officers knows that volunteers get a lot more passionate about their assignments than do paid employees. Maybe it's because losing the job has no negative financial consequences and they can blow off steam and even stomp out whenever they want. Besides, there are always a bunch of observers and underlings who secretly want the position and all the (questionable) esteem and respect that they think goes with it. There's always someone eager to take over in a volunteer organization. Gtk-- I got another surprise when I looked at GNOME programming tools. My first exposure was to the C API, which does not interest me. Several readers turned me on to Gtk-- (), which is a C++ wrapper around the GTK API, upon which GNOME is built, and, guess what? Most of my objections to the KDE library are gone. Gtk-- uses namespaces. It implements slots without using preprocessor macro language extensions or a metaobject compiler. It has no funny custom RTTI feature that you have to use. It does not require you to instantiate widget objects with the new operator that it will sometime later delete for you. Gtk-- adds to the jargon confusion by calling its slots "signal handlers." Gtk-- objects can emit signals by using special objects called "signalers," which you connect to signal handler "callback functions." Gtk-- comes with an HTML tutorial still a work in progress which I recommend if only for the occasional touches of humor that had me laughing out loud in several places. I installed Gtk-- from source code by using the new Gcc 3.0 compiler release. It builds without errors, and the example programs in the tutorial work without any problems. Well, almost. When I use the command lines in the text of the tutorial examples to compile, they do not work properly. But when I use the Makefiles that accompany the example source code, everything runs without a hitch. Gnome-- Gnome-- (also available at) is an extension of Gtk-- intended, as nearly as I can tell, to support more of GNOME's object technology and to add such things as MDI support to the application classes. I can't really say for sure because the project is fairly new and without much in the way of documentation yet. It would not compile with the gcc 3.0 compiler, and when I retreated to Red Hat's 2.96, it could not find certain required header files to continue. My guess is that the maintainers have something installed that I do not, although I did install the prerequisite libraries that were identified. I'll wait for this one to become more ready for wide usage before diving in. The RedHat Inti Class Library Another possibility for a GNOME class library is Inti from RedHat (). At first glance, and that's all I've given it so far, Inti seems to be even more of what I am looking for. It employs namespaces, uses STL containers, and avoids the kludge that QT uses to implement events, allowing you to choose between connecting signals and slots as Gtk-- does and using virtual functions. But there's a major problem. According to its preliminary documentation, Inti uses that same awful convention that QT uses, requiring you to implement some objects on the heap and never delete them. They say it's to support reference counted objects, but I don't get it. Unless I've missed something, Gtk-- did not have to do that. If the Inti developers are reading this, listen up. That's a bad thing to do. Don't do it. You are still in the preliminary stages of your project. There's still time to do the right thing and correct that error. If it's the only way you can support reference counting, then do without reference counting. Its benefits aren't worth the price. Because as long as Inti has that characteristic, folks, that dog won't hunt and I won't be using it. DDJ
http://www.drdobbs.com/cpp/yapp-yet-another-programming-platform/184404813
CC-MAIN-2014-35
refinedweb
2,647
64.71
NAME fdm.conf - fdm configuration file DESCRIPTION This manual page describes the fdm(1) configuration file. It defines accounts from which to fetch mail, a number of possible actions to take, and rules connecting a regexp with an action. The file is parsed once from top to bottom, so action and account definitions must appear before they are referenced in a rule. Rules are evaluated from first to last and (unless overridden by the continue keyword) evaluation stops at the first match. The file has the following format: Empty lines and lines beginning with the ‘#’ character are ignored. Regexps and strings must be enclosed in double quotes. Special characters in regexps and strings (including passwords) must be escaped. Note that this may mean double-escaping in regexps. Possible commands are covered in the following sections. OPTIONS Options are configured using the set command. It may be followed by the following options, one per command: maximum-size size This is used to set the maximum size of a mail. Mails larger than this limit are dropped and, if applicable, not deleted from the server. The size may be specified as a plain number in bytes or with a suffix of ‘K’ for kilobytes, ‘M’ for megabytes or ‘G’ for gigabytes. The default is one gigabyte. delete-oversized If this option is specified, fdm(1) attempts to delete messages which exceed maximum-size, and continue. If it is not specified, oversize messages are a fatal error and cause fdm(1) to abort. Note that fdm(1) may have a number of messages queued (up to the queue-high setting, doubled for rewrite, per account), so this setting and the queue-high option should be set after as the next is being fetched. Once this limit is reached, no further messages wil be fetched until the number of messages held drops to the queue-low value. queue-low number This is the length to which the message queue must drop before fetching continues after the queue-high limit has been reached. allow-multiple If this option is specified, fdm(1) does not attempt to create a lock file and allows multiple instances to run simultaneously. lock-file path This sets an alternative lock file. The default is ~/.fdm.lock for non-root users and /var/db/fdm.lock for root. default-user user This sets the default user to change to before delivering mail, if fdm(1) is running as root and no alternative user is specified as part of the action or rule. This option may be overridden with the -u switch on the command line. A default user must be given if running as root. lock-types type ... This specifies the locks to be used for mbox locking. Possible types are fcntl, flock, and dotlock. The flock and fcntl types are mutually exclusive. The default is flock. domain domain | domains { domain ... } This specifies the domains to be used when looking for users with the from-headers keyword. The default is the computer’s hostname. header header | headers { header ... } This allows the headers to be examined when looking for users to be set. The default is to look only at the "From" and "Cc" headers. The headers are case-insensitive. proxy url This instructs fdm(1) to proxy all connections through url. HTTP and SOCKS5 proxies are supported at present (URLs of the form[:port] or socks://[user:pass@]host[:port]). No authentication is supported for HTTP. unmatched-mail drop | keep This option controls what fdm(1) does with mail that reaches the end of the ruleset (mail that matches no rules or matches only rules with the continue keyword). drop will cause such mail to be discarded, and keep will attempt to leave the mail on the server. The default is to keep the mail and log a warning that it reached the end of the ruleset. purge-after count The purge-after option makes fdm(1) attempt to purge deleted mail from the server (if supported) after count mails have been’ header into each mail. file-umask user | umask This specifies the umask(2) to use when creating files. user means to use the umask set when fdm(1) is started, or umask may be specified as a three-digit octal number. The default is 077. file-group user | group This option allows the default group ownership of files and directories created by fdm(1) to be specified. group may be a group name string or a numeric gid. If user is used, or this option does not appear in the configuration file, fdm(1) does not attempt to set the group of new files and directories. timeout time This controls the maximum time to wait for a server to send data before closing a connection. The default is 900 seconds. verify-certificates Instructs fdm(1) to verify SSL certificates for all SSL connections. INCLUDING FILES Further configuration files may be including using the include command: include path The file to include is searched for first as an absolute path and then relative to the directory containing the main configuration file. MACROS Macros may be defined using the following syntax: $name = string %name = number Macros are prefixed with $ to indicate a string value and % to indicate a numeric value. Once defined, a macro may be used in any place a string or number is expected. Macros may be embedded in strings by surrounding their name (after the $ or %) with {}s, like so: "abc ${mymacro} %{anothermacro} def" The ifdef, ifndef and endif keywords may be used to conditionally parse a section of the configuration file depending on whether or not the macro given exists or does not exist. ifdef and ifndef blocks may be nested. SHELL COMMANDS The result of a shell command may be used at any point a string or number is expected by wrapping it in $() or %(). If the former is used, the command result is used as a string; if the latter, it is converted to an integer. Shell commands are executed when the configuration file is parsed. ACCOUNTS The account command is used to instruct fdm(1) to fetch mail from an account. The syntax is: account name [users] [disabled] type [args] [keep] The name argument is a string specifying a name for the account. The optional users argument has the following form: user user | users { user ... } | user from-headers The first two options specify a user or list of users as which the mail should be delivered when an action is executed. If user from-headers is specified, fdm(1) attempts to find the users from the mail headers, using the values of the headers and domains options. If no headers are specified, or fdm(1) fails to find any valid users in the headers, the default user (set with set default-user) is used. Users specified as part of the account definition may be overridden by similar arguments to action definitions or on match rules. If fdm(1) is run as non-root, it will still execute any actions once for each user, but will be unable to change to that user so the action will be executed multiple times as the current user. The disabled keyword instructs fdm(1) to ignore this account unless it is explicitly enabled with a -a option on the command line. If the keep keyword is specified, all mail collected from this account is kept (not deleted) even if it matches a drop action. Supported account types and arguments are: stdin This account type reads mail from stdin, if it is connected to a pipe. This may be used to deliver mail from sendmail(8), see fdm(1) for details. pop3 server host [port port] [user user] [pass pass] [no-apop] pop3s server host [port port] [userpass] [only] [no-apop] [no-verify] These statements define a POP3 or POP3S account. The userpass element has the following form: [user user] [pass pass] The host, user and pass arguments must be strings. If the user or pass is not provided, fdm(1) attempts to look it up in the ~/.netrc file (see ftp(1) for details of the file format). The port option may be either a string which will be looked up in the services(5) database, or a number. If it is omitted, the default port (110 for POP3, 995 for POP3S) is used. The only option takes the form: [new-only | old-only] cache path new-only fetches only mail not previously fetched, and old-only is the inverse: it fetches only mail that has been fetched before. The cache file is used to save the state of the POP3 mailbox. The no-apop flag forces fdm(1) not to use the POP3 APOP command for authentication, and the no-verify keyword instructs fdm(1) to skip SSL certificate validation for this account. pop3 pipe command [userpass] [only] [no-apop] This account type uses the POP3 protocol piped through command, such as ssh(1). If the command produces any output to stderr, it is logged. For POP3 over a pipe, providing a user and password is not optional and it may not be read from ~/.netrc. imap server host [port port] [userpass] [folder name] [only] imaps server host [port port] [userpass] [folder name] [only] [no-verify] These define an IMAP or IMAPS account. The parameters are as for a POP3 or POP3S account, aside from the additional folder option which allows the folder name to be specified (the default is to fetch from the inbox). The default ports used are 143 for IMAP and 993 for IMAPS. For IMAP, the only item consists only of one of the keywords new-only or old-only - a cache file is not required. imap pipe command [userpass] [folder name] [only] As with pop3 pipe, this account type uses the IMAP protocol piped through command. If the optional IMAP user and pass are supplied, they will be used if necessary, but if one is provided, both must be - using ~/.netrc is not permitted. maildir path maildirs { path ... } These account types instruct fdm(1) to fetch mail from the maildir or maildirs specified. This allows fdm(1) to be used to filter mail, fetching from a maildir and deleting (dropping) unwanted mail, or delivering mail to another maildir or to an mbox. mbox path mboxes { path ... } These are similar to maildir and maildirs, but cause fdm(1) to fetch mail from an mbox or set of mboxes. nntp server host [port port] group group cache cache nntp server host [port port] groups { group ... } cache cache nntps server host [port port] group group cache cache nntps server host [port port] groups { group ... } cache cache An NNTP account. Articles are fetched from the specified group or groups and delivered. The index and message-id of the last article fetched in each group is saved in the specified cache file. When fdm(1) is run again, fetching begins at the cached article. Note that the keep option is completely ignored for NNTP accounts - all mail is kept, and the cache is always updated. TAGGING As mail is processed by fdm(1), it is tagged with a number of name/value pairs. Some tags are added automatically, and mail may also be tagged explicitly by the user using the tag action. Tags may be inserted in most strings in a similar manner to macros, except tags are processed at runtime rather than as the configuration file is parsed. A tag’s value is inserted by wrapping its name in %[], for example: abc%[account]def %[hour]:%[minute]:%[second] The default tags also have a single-letter shorthand. Including a nonexistent tag in a string is equivalent to including a tag with an empty value, so "abc%[nonexistent]def" will be translated to "abcdef". The automatically added tags are: account (%a) The name of the account from which the mail was fetched. home (%h) The delivery user’s home directory. uid (%n) The delivery user’s uid. action (%t) The name of the last action executed for this mail. user (%u) The delivery user’s username. hour (%H) The current hour (00-23). minute (%M) The current minute (00-59). second (%S) The current second (00-59). day (%d) The current day of the month (01-31). month (%m) The current month (01-12). year (%y) The current year. year2 The current year as two digits. dayofweek (%W) The current day of the week (0-6, Sunday is 0). dayofyear (%Y) The current day of the year (001-366). quarter (%Q) The current quarter (1-4). rfc822date The current date in RFC822 format. mail_hour The hour from the mail’s date header, if it exists and is valid, otherwise the current time. mail_minute The minute from the mail’s date header. mail_second The second from the mail’s date header. mail_day The day from the mail’s date header. mail_month The month from the mail’s date header. mail_year The year from the mail’s date header. mail_year2 The same as two digits. mail_rfc822date The mail’s date in RFC822 format. hostname The local hostname. In addition, the shorthand %% is replaced with a literal %, and %0 to %9 are replaced with the result of any bracket expressions in the last regexp. CACHES fdm(1) can maintain a cache file with a set of user-defined strings. In order to use caches, fdm(1) must have been compiled with them enabled. Caches are declared with the cache keyword: cache path [expire age] The path is the location of the cache file. If the expire keyword is specified, items in the cache are removed after they reach the age specified. age may be given unadorned in seconds, or followed by one of the modifiers: seconds, hours, minutes, days, months or years. Caches must be declared before they are used. Items are added to caches using the to-cache action and they are searched using the in-cache condition; see below for information on these. ACTIONS The action command is used to define actions. These may be specified by name in rules (see below) to perform some action on a mail. The syntax is: action name [users] action action name [users] { action ... } The name is a string defining a name for the action. The users argument has the same form as for an account definition. An action’s user setting may be overridden in the matching rule. The possible values for action are listed below. If multiple actions are specified they are executed once in the order specified, for each user. drop Discard the mail. keep Keep the mail, do not remove it from the account. tag string [value value] This tags mail with string, and optionally value, which may be matched using the tagged or string conditions. maildir path Save the mail to the maildir specified by path. If the maildir does not exist, it is created. Mail delivered to a maildir is tagged with a mail_file tag containing the full path of the mail file. mbox path [compress] Append the mail to the mbox at path. If compress is specified, fdm(1) will add ‘.gz’ to path and attempt to write mail using gzip(1) compression. If the mbox does not exist, it is created. Mail delivered to an mbox is tagged with a mbox_file tag containing the path of the mbox. exec command Execute command. pipe command Pipe the mail to command. write path Write the mail to path. append path Append the mail to path. smtp server host [port port] [to to] Connect to an SMTP server and attempt to deliver the mail to it. If to is specified, it is passed to the server in the RCPT TO command. If not, the current user and host names are used. rewrite command Pipe the entire mail through command to generate a new mail and use that mail for any following actions or rules. An example of the rewrite action is: action "cat" pipe "cat" action "rewrite" rewrite "sed ’s/bob/fred/g’" # this rule will rewrite the message match all action "rewrite" continue # this rule will cat the rewritten message match all action "cat" add-header name value value Add a header name with contents value. remove-header name remove-headers { name ... } Remove all occurances of headers matching the fnmatch(3) pattern name. stdout Write the mail to stdout. to-cache path key key This action adds the string key to the cache specified by path. action name This invokes another named action. A maximum of five actions may be called in a sequence. RULES Rules are specified using the match keyword. It has the following basic form: match condition [and | or condition ...] [users] actions [continue] The condition argument may be one of: all Matches all mail. matched Matches only mail that has matched a previous rule and been passed on with continue. unmatched The opposite of matched: matches only mails which have matched no previous rules. account name | accounts { name ... } Matches only mail fetched from the named account or accounts. The account names may include shell glob wildcards to match multiple accounts, as with the -a and -x command line options. tagged string Matches mails tagged with string. [case] regexp [in headers | in body] Specifies a regexp against which each mail should be matched. The regexp matches may be restricted to either the headers or body of the message by specifying either in headers or in body. The case keyword forces the regexp to be matched case- sensitively: the default is case-insensitive matching. exec command [user user] returns ( return code, stdout regexp) pipe command [user user] returns ( return code, [case] stdout regexp) These two conditions execute a command and test its return value and output. The return code argument is the numeric return code expected and stdout regexp is a regexp to be tested against the output of the command to stdout. Either of these two arguments may be omitted: if both are specified, both must match for the condition to be true. The pipe version will pipe the mail to the command’s stdin when executing it. If a user is specified, fdm(1) will change to that user before executing the command, otherwise the current user (or root if started as root) is used. size < number size > number Compare the mail size with number. string string to [case] regexp Match string against regexp. age < time age > time The age condition examines the mail’s date header to determine its age, and matches if the mail is older (>) or newer (<) than the time specified. The time may be given as a simple number in seconds, or followed by the word seconds, hours, minutes, days, months or years to specify a time in different units. in-cache path key key This condition evaluates to true if the string key is in the cache at path. attachment count < number attachment count > number attachment count == number attachment count != number These conditions match if the mail possesses a number of attachments less than, greater than, equal to or not equal to number. attachment total-size < size attachment total-size > size Matches if the total size of all attachments is smaller or larger than size. attachment any-size < size attachment any-size > size Compare each individual attachment on a mail to size and match if any of them are smaller or larger. attachment any-type string attachment any-name string Match true if any of a mail’s attachments possesses a MIME type or filename that matches string. fnmatch(3) wildcards may be used. Multiple conditions may be chained together using the and or or keywords. The conditions are tested from left to right. Any condition may be prefixed by the not keyword to invert it. The optional users argument to the first form has the same syntax as for an action definition. A rule’s user list overrides any users given as part of the actions. The actions list specifies the actions to perform when the rule matches a mail. It is either of a similar form: action name | actions { name ... } Or may specify a number of actions inline (lambda actions): action action action { action ... } In the latter case, action follows the same form as described in the ACTIONS section. The actions are performed from first to last in the order they are specified in the rule definition. If the continue keyword is present, evaluation will not stop if this rule is matched. Instead, fdm(1) will continue to match further rules after performing any actions for this rule. NESTED RULES Rules may be nested by specifying further rules in braces: match condition [and | or condition ...] { match ... } The inner rules will not be evaluated unless the outer one matches. Rules may be multiply nested. Note that the outer rule does not count as a match for the purposes of the matched and unmatched conditions. FILES ~/.fdm.conf default fdm.conf configuration file /etc/fdm.conf default system-wide configuration file ~/.fdm.lock default lock file /var/db/fdm.lock lock file for root user SEE ALSO fdm(1), re_format(7) AUTHORS Nicholas Marriott 〈nicm@users.sourceforge.net〉
http://manpages.ubuntu.com/manpages/hardy/man5/fdm.conf.5.html
CC-MAIN-2014-42
refinedweb
3,529
64.81
Interfacing HC-SR04 Ultrasonic Distance Sensor with ATmega32 Microcontroller Contents - 1 Introduction - 2 Required Components - 3 Hardware - 4 Tools - 5 Source Code - 6 Practical Implementation - 7 Working - 8 Video Introduction This project uses an ultrasonic sensor to indicate the distance of any object from it. Here we have made a setup based on a microcontroller in which real time distance is sensed by an ultrasonic sensor and displays measured distance on an LCD display. Required Components - ATmega32 Microcontroller - HC-SR04 Ultrasonic Distance Sensor - 16×2 LCD Display - 5V Power Supply Hardware Circuit Diagram Circuit Description The overall circuit assembled on the breadboard contains three major components :ATmega 32 Microcontroller, Ultrasonic distance sensor and 16X2 Alphanumeric LCD display. The microcontroller is interfaced with 16X2 LCD and Ultrasonic sensor. HC-SR04 Ultrasonic Sensor The ultrasonic distance sensor has 4 Pins: Vcc, GND, Trigger and Echo. The Vcc and GND are used to power up the sensor and are connected to power and ground rails on breadboard. Trigger is connected to PIN 14 (RX/PD0) and Echo is connected to PIN 16 (INT0/PD2) of the microcontroller. 16X2 LCD Display There are various ways to interface the LCD display to microcontroller based on the coding technique and the platform used. The LCD has 16 pins. Pin no 1 and 2 are GND and Vcc respectively, and are used to power up the LCD. The Pin no 3 VEE, which can be used to adjust the contrast of LCD by varying the potentiometer. We shall connect it to ground in our setup. Pin no 4, 5 and 6 are the control pins of LCD and they decide the working of LCD. We shall connect these pins to PORT D of microcontroller. - Pin 4 is RS (Register Select) and is connected to PIN 17 (PD3/INT1), - Pin 5 is RW (Read / Write) and is connected to PIN 18 (PD4) and - Pin 6 is E (Enable) which is connected to PIN 19 (PD5) of the microcontroller. Pin 7 to 14 are D0-D7 which are the data lines. They are connected to PORT A of the microcontroller (PIN 40-13). The pin 15 and 16 are for LCD back light and those pins will be connected to Vcc And Gnd. Tools Hardware Tools USB ASP Programmer To burn the program in the microcontroller. Software Tools Atmel Studio To write the program and build its hex file. Atmel Studio can be easily downloaded from the website: ProgISp To burn the program in microcontroller. Source Code Program The following code must be burnt in the microcontroller: // Measuring distance using ultrasonic distance sensor #include <avr/io.h> #include <MrLcd/MrLCDmega32.h> #include <avr/interrupt.h> #include <util/delay.h> #include <stdlib.h> static volatile int pulse = 0; static volatile int i = 0; int main(void) { int16_t count_a = 0; char show_a[16]; Initialise(); DDRD = 0b11111011; _delay_ms(50); Initialise(); GICR |= 1<<INT0; MCUCR |= 1<<ISC00; sei(); while(1) { PORTD |= 1<<PIND0; _delay_us(15); PORTD &= ~(1<<PIND0); count_a = pulse/58; Send_A_String("Distance Sensor"); GoToMrLCDLocation(1,2); Send_A_String("Distance="); itoa(count_a,show_a,10); Send_A_String(show_a); Send_A_String(" "); GoToMrLCDLocation(13,2); Send_A_String("cm"); GoToMrLCDLocation(1,1); } } ISR(INT0_vect) { if(i == 0) { TCCR1B |= 1<<CS10; i = 1; } else { TCCR1B = 0; pulse = TCNT1; TCNT1 = 0; i = 0; } } The following code uses a header file for LCD for which a library is required. Description 1. Headers #include <avr/io.h> #include <MrLcd/MrLCDmega32.h> #include <avr/interrupt.h> #include <util/delay.h> #include <stdlib.h> 2. Defining variables static volatile int pulse = 0; static volatile int i = 0; - The variable ‘pulse’ is used to store the count value from the TCNT register. - The variable ‘i’ is used as a flag to indicate the current status of the Echo pin. 3. Initialisation of LCD and setting up of port D as IO port Initialise(); DDRD = 0b11111011; _delay_ms(50); ‘Initialize()’ is a function used to initialize the LCD and is defined in the library of the LCD that has been previously made. Next instruction sets up the function of the Pins of the port D of microcontroller. 1 means that an output device is connected at that PIN and microcontroller will write the logic there and 0 means that input device is connected there and microcontroller will read the logic from there. “DDRD = 0b11111011”: - DDR Stands for “Data Direction Register” - D indicates PORTD of microcontroller - ‘0b’ means binary - Each bit after 0b indicates the status of each pins of port in reverse order i.e PIND7, PIND6, PIND5, PIND4, PIND3, PIND2, PIND1, PIND0. - PIND2 is set as input pin as it is connected to the echo pin of the sensor. Thus the microcontroller will read the status of the echo PIN. - PIND0 is set to 1 as it is connected to trigger pin of the sensor. The microcontroller will trigger the sensor by setting up logic 1 and 0 at this pin. - We have used a few pins (PIND3, PIND4, PIND5) to connect the control pins of the LCD display. Thus to enable their use as output pins we have set them to logic high. - Other pins that are left open are don’t care pins and can be set at any value (i.e 0 or 1). 4. Setting up the Interrupt GICR |= 1<<INT0; MCUCR |= 1<<ISC00; - GICR : General Interrupt Control Registor This Instruction is used to configure the PIN D2 as an interrupt PIN as the ECHO pin of the sensor is connected here. - MCUCR: MCU control Register The second instruction defines that any logical change at the INT0/PIND2 Pin will cause the microcontroller. Thus microcontroller will be interrupted when logic goes from 0 to 1 or from 1 to 0. These registers are specified in the datasheet of ‘Atmega32A’ and can be referred on Page no 70. 5. Defining variables int16_t count_a = 0; char show_a[16]; We define a variable ‘count_a’ to store the final output value after processing. After analysis it is concluded that value of pulse when divided by 58 gives the distance measure in centimeters. The the value of “pulse/58” is stored in this variable. ‘Show_a’ variable is used to convert the ‘int’ type value to ‘char’ type value so that it can be displayed on LCD. 6. Triggering the ultrasonic sensor PORTD |= 1<<PIND0; _delay_us(15); PORTD &= ~(1<<PIND0); The PIN no 0 of port D (PIN D0) was connected to the trigger of the sensor. To trigger the sensor we need to apply a pulse of sufficient width. Here we have applied a pulse of width 15 microsecond. - The PIN D0 is set high (5V). - A delay of 15Microseconds is given. - The PIN D0 is again set to Low (0v). 7. Instructions to display the output Send_A_String("Distance Sensor"); GoToMrLCDLocation(1,2); Send_A_String("Distance="); itoa(count_a,show_a,10); Send_A_String(show_a); Send_A_String(" "); GoToMrLCDLocation(13,2); Send_A_String("cm"); GoToMrLCDLocation(1,1); Send_A_String(“string”), GOTO MrLCDLocation(int x, int y ), are the functions defined in nthe LCD library. We observe that the function “Send_A_String” uses ‘char’ type parameter but the final value ‘count_a’ is a ‘int’ type variable. Thus to convert ‘int’ type to char type we use the ‘itoa’ instruction which converts integer to string. The no 10 signifies base 10 i.e decimal no system. 8. The Interrupt Service Routine ISR stands for interrupt service routine. It is a function that is executed when the microcontroller is interrupted. ISR(INT0_vect) { if(i == 0) { TCCR1B |= 1<<CS10; i = 1; } else { TCCR1B = 0; pulse = TCNT1; TCNT1 = 0; i = 0; } } The echo pin goes high as soon as ultrasound wave is sent and it goes low when it receives the reflected wave or when timed out. The time for which the echo pin is high is directly proportional to the distance of the obstacle from sensor. Thus we need to calculate the time for which this pin has stayed high. For this we use the inter counter of the microcontroller. 1. When Echo Pin goes from low to high (0 to 1) We have previously defined a variable ‘i’ that had initial value 0. When the echo PIN goes high the controller is interrupted and the ISR is executed. The condition is checked with the ‘if’ statement and the microcontroller starts the counter and also sets the value of ‘i’ to 1. TCCR stands for TIMER COUNTER CONTROL REGITER. Setting its CS10 bit to 1 starts the timer with a prescaling of 1. The count value is stored in a register called TCNT. 2. When Echo pin goes form high to low (1 to 0) When the echo pin goes low, microcontroller is interrupted again and again the ISR is executed. This time value of ‘i’ is 1 (We had changed it from 0 to 1 when we had started the timer). The ‘if’ condition will be checked again. This time the timer will be stopped by setting TCCR to zero.The value that was counted will be saved in TCNT register. We will store that value in a previously defined variable ‘pulse’ and clear/ reset the value of TCNT. Adding Header File The Atmel Studio does not have inbuilt Library for LCD. Thus we need to add that library. For that we need to copy the header file (‘filename.h’ type) at the location where other libraries are kept. Go to this location in your file browser: C:\Program Files (x86)\Atmel\Studio\7.0\toolchain\avr8\avr8-gnu-toolchain\avr\include Make a folder here named MrLCD (You can use any name. But you will have to make changes accordingly in your program). Download Header file here Paste your header file in the folder. Now you will get suggestion for this library while working in the Atmel Studio. Practical Implementation Working This article is used to monitor the distance between ultrasonic sensor and object and it will display that monitored distance value on 16X2 LCD display. Microcontroller ATmega32 is used to control the whole process. Ultrasonic sensor will be having transmitter and receiver in it. Transmitter continuously transmits the signal and whenever obstacle approaches the sensor then that transmitted signal hits the object, bounce back and received by ultrasonic receiver. That sensor sensed signal with respect to distance is then send to microcontroller, microcontroller in turn displays the measured distance value on LCD. Please describe your problem in detail. Thankyou, but the value on LCD does not change. Please help me Please describe your problem in detail. are you sure about this code ?? the value on the LCD is not right and I don’t know the problem are you sure about this code ?? the value on the LCD is not right and I don’t know the problem Thank you for your valuable feedback. I have updated the article based on your suggestions. Thank you very much for the very useful lesson. There are couple of notes on it. Quote: The echo pin is the one that becomes high after it receives reflected waves. Note: Actually the echo pin goes high as soon as ultrasound wave is sent and it goes low when it receives the reflected wave. Also the code of interrupt function is not quite correct: ISR(INT0_vect) { if(i == 1) { TCCR1B = 0; pulse = TCNT1; TCNT1 = 0; i = 0; } if(i == 0) { TCCR1B |= 1< Why did you divide the pulse value by 58? can you explain the calculation behind that declaration? Thank You thank you so much my teacher The value on LCD does not change. What can be a problem? Yes, it is possible. You need to configure appropriate registers for that. Is it possible to use timer/counter 0 or timer/counter 2 instead of this. How to do it If it is possible ? Thank you!
https://electrosome.com/ultrasonic-distance-sensor-atmega32/
CC-MAIN-2021-43
refinedweb
1,950
63.9
mKatz on 13 November 2014 - 12:51 PM here are two screenshots to hopefully help greaten the ability to understand what OP is asking for. Posted by mKatz on 27 September 2012 - 01:58 PM Posted by mKatz on 28 August 2012 - 08:49 AM #define STRICT #define _AFXDLL #include "stdafx.h" #include <tchar.h> #include <AFXWIN.H> #include <windows.h> #include "Serial\Serial\Serial.h" #include "Serial\Serial\SerialEx.h" #include "Serial\Serial\SerialMFC.h" #include "Serial\Serial\SerialWnd.h" int WINAPI_tWinMain ( HINSTANCE //hInst HINSTANCE //hInstPrev int ) { CSerial serial; serial.Open(_T("COM4")); serial.Setup (CSerial::EBaud9600, CSerial::EData8, CSerial::EParNone, CSerial::EStop1); CSerial::SetupHandshaking; serial.Write("Hello World"); serial.Close(); return 0; } Posted by mKatz on 27 August 2012 - 01:45 PM Posted by mKatz on 27 August 2012 - 10:22 AM Posted by mKatz on 17 August 2012 - 01:50 PM As the error messages mention, you're trying to redefine EthicalCompetition::Connection::Connection(). You define it as an empty inline method in the class definition for it above.Perhaps you meant for the second definition to be EthicalCompetition::Connection::Connect()?If the horrible spacing isn't the board's fault, I highly suggest modern inventions like indentation. It's 2012, you can afford a tab or three in a file. Posted by mKatz on 09 August 2012 - 01:39 PM Achievements are a great feature, but I still can't see them as a feature that will greatly enhance the self-improvement path. I think players see achievements as bonus missions, that might be cool to complete to test their skills, to make the most of the game, or just to brag. Testing skills is nearer to the self-improvement goal, but there are many ways not recognized by the game designer in which the player could test his abilities. Taking your example, is killing 100 ogres enough? What about 1,000? But is that number really testing the player's expertise with the toothpick, or merely his patience? And that makes me think that achievements are mostly nice trophies the player will put aside to continue his development journey. Posted by mKatz on 06 August 2012 - 01:26 PM Posted by mKatz on 06 August 2012 - 12:44 PM // learn.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include "safestuff.cpp" #include "SafeCracker.cpp" #include <string> using namespace std; int main() { cout << "Suprise, suprise!" << endl; cout << "The combination is (once again)" <<endl; cout << SafeCracker(12)<<endl; system("pause"); return 0; } #include "stdafx.h" #include <string> using namespace std; #ifndef SAFESTUFF_H_INCLUDED #define SAFESTUFF_H_INCLUDED string SafeCracker(int SafeID); #endif // SAFESTUFF_H_INCLUDED #include "stdafx.h" #include <string> using namespace std; string SafeCracker(int SafeID) { return "13-26-16"; } Posted by mKatz on 13 July 2012 - 02:00 PM You are maybe right... I only thought many kids (between 10 and 14/16) don't really like Math (I know many people like that ;) ), but this was only my opinion I also have a "good" story but it does not handle humans like Steve from Minecraft and contains no fantasy, more normal adventure without something like magic and sci-fi.Unfortunately I can not write it down here, I just have not enough time Regardsomercan Posted by mKatz on 13 July 2012 - 01:55 PM Posted by mKatz on 13 July 2012 - 01:06 PM What's about a very different block system? Like a fuel stand or kilogram...For example:You can have 1 kg Sand, but to transport it you need a bin, for a bin you need 5 kg iron. Iron is only available as ore.For 5 kg iron you need 7 kg Ore and fire... For fire you need etc...I think kg or something similar is a good choice, because it would be really "easy" to implement half blocks or different blocks like triangles. Also it makes it more independet from the blocks himself.But there is a big problem... I think many people don't like something mathematical like kilogramm.With Triangle blocks you could also implement good transports like cars.. Wish you luck for your project!PS: I also had the same idea one year ago... but stopped because it would be only a minecraft clone Posted by mKatz on 12 July 2012 - 11:00 AM what if you make each block have, say, 1/8 of the minecraft block size, then, when you punch the block with your pickaxe, you break more than one block at the time, creating a destruction effect, then, for placement, you can make the player capable of crafting a bunch of those little blocks in a larger block, that in reality it's only a bunch of the little ones (i think i'm not being clear here, basically, the player has the option to place 8 little blocks in the shape of a larger one, or place the normal 1/8 sized block)this way terrain would be much more detailed and the game more realistic, it's possible with the technology of your choice to archive this? Posted by mKatz on 11 July 2012 - 03:55 PM Posted by mKatz on 11 July 2012 - 02:14 PM GameDev.net™, the GameDev.net logo, and GDNet™ are trademarks of GameDev.net, LLC
http://www.gamedev.net/user/200011-mkatz/?tab=reputation&app_tab=forums&type=received
CC-MAIN-2016-36
refinedweb
883
63.9
Hello at all, I want to implement a custom PluginFeature for ICN 202 and 203: public class TasklistViewFeature extends PluginFeature and this Feature will be implemented by TasklistViewFeature.js. In this TasklistViewFeature.js, I need to know the userId of the currently logged in user. I tried it with var userId = ecm.model.repository.userId; But then, I get the error " ecm.model.repository is undefined". I tried the following line and this is working: var deskId = ecm.model.desktop.id; I attached the corresponding java / js / html files of the PluginFeature. Therefore the question, how to get the UserId in a PluginFeature? Thanks and best regards Ben 83 people are following this question. How to force a Plugin-Feature to refresh? 3 Answers Configurable Action Name 2 Answers EDS Field population 6 Answers increasing/decreasing width of column 1 Answer Any ICN Plugin for Auto populate the data in the properties when add/update document 5 Answers
https://developer.ibm.com/answers/questions/279145/get-logged-in-user-id-in-pluginfeature.html
CC-MAIN-2019-39
refinedweb
158
59.19
hsearch() Search the hash search table Synopsis: #include <search.h> ENTRY* hsearch ( ENTRY item, ACTION action ); Since: BlackBerry 10.0.0 Arguments: - item - A structure of type ENTRY, defined in <search.h>, that contains: - char * key — a pointer to the comparison key. - void * data — a pointer to any other data to be associated with the key. - action - A member of an enumeration type ACTION, also defined in <search.h>, indicating what to do with the entry if it isn't in the table: - ENTER — insert the entry in the table at the appropriate point. If the item is a duplicate of an existing item, the new item isn't added, and hsearch() returns a pointer to the existing one. - FIND — don't add the entry. If the item can't be found, hsearch() returns NULL. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description:. The hsearch() and hcreate() functions use malloc() to allocate space. Only one hash search table may be active at any given time. You can destroy the table by calling hdestroy(). See also The Art of Computer Programming, Volume 3, Sorting and Searching by Donald E. Knuth, published by Addison-Wesley Publishing Company, 1973. Returns: A pointer to the item found, or NULL if either the action is FIND and the item wasn't found, or the action is ENTER and the table is full. Examples: The following example reads in strings followed by two numbers and stores them in a hash table, discarding duplicates. It then reads in strings, finds the matching entry in the hash table and prints; } Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/h/hsearch.html
CC-MAIN-2017-04
refinedweb
297
66.84
Question: I have a GWT App where I need to call a webservice to check whether the user signed in is an administrator - and then set the admin Div to visible (hidden by default) if the web service returns true. The problem is the program passes the check before the web service can return the result. It's looking something like this public class ModelClass{ boolean isAdmin = false; public ModelClass(){ //Call webservice in constructor, if returns true, set isAdmin to true via setter } } Then, in my widget, I create an instance of the ModelClass and then in the last step before the page finishes loading, I check the isAdmin property to see if it's true, if so - set the Admin panel to visible. No matter how early I try to make the call, and how late I check the property, the admin check always happens before the web service response returns. I've tried change listeners - but they only apply to widgets. I tried rigging the property as a label and using a click event by calling click() on the label from the web service response. Nothing seems to work - does anyone have any ideas? Solution:1 If you are using a callback mechanism, you will have to do it in the callback function. e.g. If you are using the GWT's request builder, You will have to do it in onResponseReceived of your request callback: public ModelClass() { isAdmin(); } private void isAdmin() { RequestBuilder builder = new RequestBuilder( RequestBuilder.GET, webserviceurl); try { request = builder.sendRequest(null, new RequestCallback() { public void onResponseReceived(Request request, Response response) { int code = response.getStatusCode(); if(code >= 400) { Window.alert(response.getStatusText()); return; } if(code == 200) { // if admin is logged in // hide your div } } public void onError(Request request, Throwable exception) { Window.alert("Error checking admin status"); } }); }catch(RequestException re) { Window.alert("Error checking admin status"); } } Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2019/06/tutorial-gwt-hiding-or-showing-div-at.html
CC-MAIN-2020-05
refinedweb
330
50.87
You can subscribe to this list here. Showing 7 results of 7 Is this only broken for PSP files? Or does it also break if you try it in a regular servlet? Also, you might want to try self.forward() and self.callMethodOfServlet() and see if those are also broken for you too. Their internal implementation is very similar to includeURL(). I'm using both of those methods with no problems from regular servlets in my own application. I can take a closer look at this problem, but not until next week. - Geoff > -----Original Message----- > From: David Casti [mailto:david@...] > Sent: Thursday, April 11, 2002 4:55 AM > To: webware-discuss@... > Subject: [Webware-discuss] mod_webkit adapter broken for > self.includeURL? > > > Hello, > > I am using the self.includeURL() function in my PSP page. > The exact snip > of code is -- > > if tabbed: > tab_include_name = "%s/psp/tabs/%s_tabs.psp" % ( > root_path, page_name ) > print "tab_include_name = %s" % tab_include_name > self.includeURL( tab_include_name ) > > -- and this works fine if I use the WebKit.cgi adapter. > > However, if I try to run the exact same code through > mod_webkit, I get a > very strange problem. It appears that some junk is getting > prepended to > the path... the traceback is -- > > Traceback (most recent call last): > File "./WebKit/Application.py", line 388, in dispatchRequest > self.handleGoodURL(transaction) > File "./WebKit/Application.py", line 536, in handleGoodURL > self.respond(transaction) > File "./WebKit/Application.py", line 712, 67, in _respond > self.writeHTML() > File > "/home/apache/Webware/WebKit/Cache/PSP/_home_apache_htdocs_psp > _cornerstone_newsalesorder_new_sales_order_htm.py", > line 390, in writeHTML > self.includeURL( tab_include_name ) > File "./WebKit/Page.py", line 328, in includeURL > self.application().includeURL(self.transaction(), URL) > File "./WebKit/Application.py", line 637, in includeURL > self.createServletInTransaction(trans) > File "./WebKit/Application.py", line 978, in > createServletInTransaction > cache = { > File "/usr/local/lib/python2.2/posixpath.py", line 144, in getmtime > st = os.stat(filename) > OSError: [Errno 20] Not a directory: > '/home/apache/htdocs/psp/cornerstone/newsalesorder/new_sales_o > rder.htm/home/apache/htdocs/psp/cornerstone/newsalesorder/../p > sp/tabs/new_sales_order_tabs.psp' > > -- the correct path in this example would have been simply > ../psp/tabs/new_sales_order_tabs.psp > > Any ideas why WebKit.cgi works and mod_webkit doesn't? > > Thanks, > David. > > ------------------------------------------------------------------ > David Casti Managing Partner > Neosynapse > > > > _______________________________________________ > Webware-discuss mailing list > Webware-discuss@... > > I just have time for a quick suggestion. Maybe there is some kind of buffering going on? Try spitting out a big chunk of whitespace right before you call flush(). Something like self.write(' ' * 10000) and see if that changes the results. When you say "WebKit.exe" are you really talking about wkcgi.exe (the C adapter) or you talking about a compiled version of WebKit.cgi? - Geoff > -----Original Message----- > From: Aaron Held [mailto:aaron@...] > Sent: Thursday, April 11, 2002 3:08 PM > To: webware-discuss@... > Subject: [Webware-discuss] flush() and Webkit.exe > > > Is there an issue with Webkit.exe and self.response().flush? > > I am trying to force a partial html page and it works under > apache / webkit.cgi, but not under iis / Webkit.exe > > I think I remeber something about this. > > Thanks, > -Aaron Held > > > _______________________________________________ > Webware-discuss mailing list > Webware-discuss@... > > manuel.segarra@... >. I discovered this "feature" myself a few weeks ago. It only happens on Windows, not on Linux. Read this thread from comp.lang.python for more information: There are apparently some Registry variables that can be tweaked to possibly make this behavior stop happening. I just gave up and reworked my servlets so that they don't take more than 4 minutes :-) - Geoff. - Geoff | I have three navigation buttons on the page. one takes you | back, one will update context, and last pushes stuff to the | next level. However next level needs to be https not http. | so href doesn't work as explained and stuff that works | can't be tied to image so that can be invoked on click. | Who do you handle http -> https transition. | thanks Maybe I don't understand. Why can't you just do this? <a href="back.py"><img src="backbutton.gif"></a> <a href="update.py"><img src="update.gif"></a> <a href=""><img src="nextlevel.gif"></a> If you mean to use form buttons rather than images, yes, it's different. You'll have to use some javascript to have 3 different targets for one form. OR, if you use webware actions, you could have three actions in your buttons like <input type="submit" name="_action_back" value="BACK"> <input type="submit" name="_action_update" value="UPDATE"> <input type="submit" name="_action_next" value="NEXT"> then three methods in your target servlet: def actions(self): # tells servlet what methods to allow from action return ['back','update','next'] def back(self): self.transaction().response().sendRedirect('back.py') def update(self): self.transaction().response().sendRedirect('update.py') def next(self): self.transaction().response().sendRedirect(' e.py'). You can certainly put a complete URL as the target (the "action") of a submit button. There are gotchas to using image buttons with webkit, if you want the target servlet to use the "actions" feature. It doesn't work with actions right now. | How can I invoke servlet under https context but use image | button and form post invocation. | Could it be that I need to have a hidden input field with | request that cold be captured on the invocation of the | parent servlet and then accordingly proceed with redirect? |
http://sourceforge.net/p/webware/mailman/webware-discuss/?viewmonth=200204&viewday=12
CC-MAIN-2014-23
refinedweb
883
53.37
An email on one of our internal aliases made me realise that I hadn’t included the namespaces I’d included in the code for accessing for these entries. Someone referenced my blog entry and gave me credit for writing my own JavaScript serialiser – fortunately the Silverlight team put one in there for me which I suspect is slightly more robust than the one I would have knocked up. Anyway, here are the using statements you need (for C#): using System; using System.Windows.Browser; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Browser.Net; using System.IO; using System.Windows.Browser.Serialization; using System.Net; This refers to Accessing ASP.NET Application Services from Silverlight part one, part two and part three. Technorati tags: silverlight
https://blogs.msdn.microsoft.com/mikeormond/2007/07/20/accessing-asp-net-application-services-from-silverlight-namespaces/
CC-MAIN-2016-30
refinedweb
129
53.58
This is the third Jupyter Notebook of the series on the phugoid model of glider flight, our first learning module of the course "Practical Numerical Methods with Python". In the first notebook, we described the physics of the trajectories known as phugoids obtained from an exchange of potential and kinetic energy in an idealized motion with no drag. We gave you a neat little code to play with and plot various phugoid curves. In the second notebook, we looked at the equation representing small perturbations on the straight-line phugoid, resulting in simple harmonic motion. This is a second-order ordinary differential equation, and we solved it numerically using Euler's method: the simplest numerical method of all. We learned about convergence and calculated the error of the numerical solution, comparing with an analytical solution. That is a good foundation! Now, let's go back to the dynamical model, and take away the idealization of no-drag. Let's remind ourselves of the forces affecting an aircraft, considering now that it may be accelerating, with an instantaneous upward trajectory. We use the designation $\theta$ for the angle, and consider it positive upwards. In Figure 1, $L$ is the lift, $W$ is the weight, $D$ is the drag, and $\theta$ the positive angle of the trajectory, instantaneously. In Lesson 1, we wrote the force balance in the directions perpendicular and parallel to the trajectory for a glider in equilibrium. What if the forces are not in balance? Well, there will be acceleration terms in the equations of motion, and we would have in that case: $$ \begin{align} m \frac{dv}{dt} & = - W \sin\theta - D \\ m v \, \frac{d\theta}{dt} & = - W \cos\theta + L \end{align} $$ We can use a few little tricks to make these equations more pleasing. First, use primes to denote the time derivatives and divide through by the weight: $$ \begin{align} \frac{v'}{g} & = - \sin\theta - D/W \\ \frac{v}{g} \, \theta' & = - \cos\theta + L/W \end{align} $$ Recall, from our first lesson, that the ratio of lift to weight is known from the trim conditions—$L/W=v^2/v_t^2$— and also from the definitions of lift and drag, $$ \begin{eqnarray} L &=& C_L S \times \frac{1}{2} \rho v^2 \\ D &=& C_D S \times \frac{1}{2} \rho v^2 \end{eqnarray} $$ we see that $L/D=C_L/C_D$. The system of equations can be re-written: $$ \begin{align} v' & = - g\, \sin\theta - \frac{C_D}{C_L} \frac{g}{v_t^2} v^2 \\ \theta' & = - \frac{g}{v}\,\cos\theta + \frac{g}{v_t^2}\, v \end{align} $$ It is very interesting that the first equation has the factor $C_D/C_L$, which is the inverse of a measure of the aerodynamic efficiency of the aircraft. It turns out, this is the term that contributes damping to the phugoid model: if drag is zero, there is no damping. Drag is never zero in real life, but as engineers design more aerodynamically efficient aircraft, they make the phugoid mode more weakly damped. At altitude, this is nothing but a slight bother, but vertical oscillations are unsafe during final approach to land, so this is something to watch out for! If we want to visualize the flight trajectories predicted by this model, we are going to need to integrate the spatial coordinates, which depend on both the forward velocity (tangential to the trajectory) and the trajectory angle. The position of the glider on a vertical plane will be designated by coordinates $(x, y)$ with respect to an inertial frame of reference, and are obtained from: $$ \begin{align} x'(t) & = v \cos(\theta) \\ y'(t) & = v \sin(\theta) \end{align} $$ Augmenting our original two differential equations by the two equations above, we have a system of four first-order differential equations to solve. We will use a time-stepping approach, like in the previous lesson. To do so, we do need initial values for every unknown: $$ v(0) = v_0 \quad \text{and} \quad \theta(0) = \theta_0 \\ x(0) = x_0 \quad \text{and} \quad y(0) = y_0 $$ We know how to apply Euler's method from the previous lesson. We replace each of the time derivatives by an approximation of the form: $$ v'(t) \approx \frac{v^{n+1} - v^n}{\Delta t} $$ where we are now using a superscript $n$ to indicate the $n$-th value in the time iterations. The first differential equation, for example, gives: $$ \frac{v^{n+1} - v^n}{\Delta t} = - g\, \sin\theta^n - \frac{C_D}{C_L} \frac{g}{v_t^2} (v^n)^2 $$ Alright, we know where this is going. At each time iteration $t^n$, we want to evaluate all the known data of our system to obtain the state at $t^{n+1}$—the next time step. We say that we are stepping in time or time marching. The full system of equations discretized with Euler's method is: $$ \begin{align} v^{n+1} & = v^n + \Delta t \left(- g\, \sin\theta^n - \frac{C_D}{C_L} \frac{g}{v_t^2} (v^n)^2 \right) \\ \theta^{n+1} & = \theta^n + \Delta t \left(- \frac{g}{v^n}\,\cos\theta^n + \frac{g}{v_t^2}\, v^n \right) \\ x^{n+1} & = x^n + \Delta t \, v^n \cos\theta^n \\ y^{n+1} & = y^n + \Delta t \, v^n \sin\theta^n. \end{align} $$ As we've learned before, the system of differential equations can also be written as a vector equation: $$ u'(t) = f(u) $$} \end{align} $$ It's a bit tricky to code the solution using a NumPy array holding all your independent variables. But if you do, a function for the Euler step can be written that takes any number of simultaneous equations. It simply steps in time using the same line of code: def euler_step(u, f, dt): return u + dt * f(u) This function can take a NumPy array u with any number of components. All we need to do is create an appropriate function f(u) describing our system of differential equations. Notice how we are passing a function as part of the arguments list to euler_step(). Neat! As always, we start by loading the modules and libraries that we need for this problem. We'll need a few transcendental functions, including the $\log$ for a convergence study later on. And remember: the line %matplotlib inline is a magic function that tells Matplotlib to give us the plots in the notebook (the default behavior of Matplotlib is to open a pop-up window). import math import numpy from matplotlib import pyplot %matplotlib inline In addition, we modify some entries of the rcParams dictionary of pyplot to define notebook-wide plotting parameters: font family and font size. Here we go! # Set the font family and size to use for Matplotlib figures. pyplot.rcParams['font.family'] = 'serif' pyplot.rcParams['font.size'] = 16 Next, we need to set things up to start our numerical solution: the parameter values and the initial values. You know what the acceleration of gravity is: 9.81 m/s$^2$, but what are good values for $C_D/C_L$, the inverse of the aerodynamic efficiency? Some possible values are given on a table in the Wikipedia entry for lift-to-drag ratio: a modern sailplane can have $L/D$ of 40 to 60, depending on span (and, in case you're interested, a flying squirrel has $L/D$ close to 2). For the trim velocity, the speed range for typical sailplanes is between 65 and 280 km/hr, according to Wikipedia (it must be right!). Let's convert that to meters per second: 18 to 78 m/s. We'll pick a value somewhere in the middle of this range. Here's a possible set of parameters for the simulation, but be sure to come back and change some of these, and see what happens! # Set parameters. g = 9.81 # gravitational acceleration (m.s^{-2}) vt = 30.0 # trim velocity (m.s) CD = 1.0 / 40 # drag coefficient CL = 1.0 # lift coefficient # Set initial conditions. v0 = vt # start at the trim velocity theta0 = 0.0 # trajectory angle x0 = 0.0 # horizontal position y0 = 1000.0 # vertical position (altitude) We'll define a function rhs_phugoid() to match the right-hand side of Equation (15), the full differential system in vector form. This function assumes that we have available the parameters defined above. If you re-execute the cell above with different parameter values, you can just run the solution without re-executing the function definition. def rhs_phugoid(u, CL, CD, g, vt): """ Returns the right-hand side of the phugoid system of equations. Parameters ---------- u : list or numpy.ndarray Solution at the previous time step as a list or 1D array of four floats. CL : float Lift coefficient. CD : float Drag coefficient. g : float Gravitational acceleration. vt : float Trim velocity. Returns ------- rhs : numpy.ndarray The right-hand side of the system as a 1D array of four floats. """ v, theta, x, y = u rhs = numpy.array([-g * math.sin(theta) - CD / CL * g / vt**2 * v**2, -g * math.cos(theta) / v + g / vt**2 * v, v * math.cos(theta), v * math.sin(theta)]) return rhs Compare the code defining function rhs_phugoid() with the differential equations, and convince yourself that it's} \nonumber \end{align} $$ Now, Euler's method is implemented in a simple function euler_step(): def euler_step(u, f, dt, *args): """ Returns the solution at the next time step using Euler's method. Parameters ---------- u : numpy.ndarray Solution at the previous time step as a 1D array of floats. f : function Function to compute the right-hand side of the system. dt : float Time-step size. args : tuple, optional Positional arguments to pass to the function f. Returns ------- u_new : numpy.ndarray The solution at the next time step as a 1D array of floats. """ u_new = u + dt * f(u, *args) return u_new Note—We use an optional input to the function euler_step(), named *args. It passes to the function f() an arbitrary number of arguments. Doing so, euler_step() can take any function f(), regardless of the number of arguments this function needs. Sweet! (Read the Python documentation about Arbitrary Argument Lists for more explanations.) After defining a final time for the solution, and the time step $\Delta t$, we can construct the grid in time using the NumPy function linspace(). Make sure you study the decisions we made here to build the time grid: why do we add 1 to the definition of N, for example? Look at the code below, and make sure you understand the following aspects of it. ucontains the solution at every time-step, consisting of the velocity, angle and location of the glider. uis set to contain the initial conditions. for-loop, the function euler_step()is called to get the solution at time-step $n+1$. T = 100.0 # length of the time interval dt = 0.1 # time-step size N = int(T / dt) + 1 # number of time steps # Create array to store the solution at each time step. u = numpy.empty((N, 4)) # Set the initial conditions. u[0] = numpy.array([v0, theta0, x0, y0]) # Time integration with Euler's method. for n in range(N - 1): u[n + 1] = euler_step(u[n], rhs_phugoid, dt, CL, CD, g, vt) In order to plot the path of the glider, we need the location ( x, y) with respect to time. That information is already contained in our NumPy array containing the solution; we just need to pluck it out. Make sure you understand the indices to u, below, and the use of the colon notation. If any of it is confusing, read the Python documentation on Indexing. # Get the glider's position over the time. x = u[:, 2] y = u[:, 3] Time to plot the path of the glider and get the distance travelled! # Plot the path of the glider. pyplot.figure(figsize=(9.0, 4.0)) pyplot.title('Path of the glider (flight time = {})'.format(T)) pyplot.xlabel('x') pyplot.ylabel('y') pyplot.grid() pyplot.plot(x, y, color='C0', linestyle='-', linewidth=2); Let's study the convergence of Euler's method for the phugoid model. In the previous lesson, when we studied the straight-line phugoid under a small perturbation, we looked at convergence by comparing the numerical solution with the exact solution. Unfortunately, most problems don't have an exact solution (that's why we compute in the first place!). But here's a neat thing: we can use numerical solutions computed on different grids to study the convergence of the method, even without an analytical solution. We need to be careful, though, and make sure that the fine-grid solution is resolving all of the features in the mathematical model. How can we know this? We'll have a look at that in a bit. Let's see how this works first. You need a sequence of numerical solutions of the same problem, each with a different number of time grid points. Let's create a list of floats called dt_values that contains the time-step size of each grid to be solved on. For each element of dt_values, we will compute the solution u of the glider model using Euler's method and add it to the list u_values (initially empty). If we want to use five different values of $\Delta t$, we'll have five elements in the list u_values, each element being a Numpy array. We'll have a list of Numpy arrays! How meta is that? Read the code below carefully, and remember: you can get a help panel on any function by entering a question mark followed by the function name. For example, add a new code cell below and type: ?numpy.empty. # Set the list of time-step sizes. dt_values = [0.1, 0.05, 0.01, 0.005, 0.001] # Create an empty list that will contain the solution of each grid. u_values = [] for dt in dt_values: N = int(T / dt) + 1 # number of time-steps # Create array to store the solution at each time step. u = numpy.empty((N, 4)) # Set the initial conditions. u[0] = numpy.array([v0, theta0, x0, y0]) # Temporal integration using Euler's method. for n in range(N - 1): u[n + 1] = euler_step(u[n], rhs_phugoid, dt, CL, CD, g, vt) # Store the solution for the present time-step size u_values.append(u) In Lesson 2, we compared our numerical result to an analytical solution, but now we will instead compare numerical results from different grids. For each solution, we'll compute the difference relative to the finest grid. You will be tempted to call this an "error", but be careful: the solution at the finest grid is not the exact solution, it is just a reference value that we can use to estimate grid convergence. To calculate the difference between one solution u_current and the solution at the finest grid, u_finest, we'll use the $L_1$-norm, but any norm will do. There is a small problem with this, though. The coarsest grid, where $\Delta t = 0.1$, has 1001 grid points, while the finest grid, with $\Delta t = 0.001$ has 100001 grid points. How do we know which grid points correspond to the same location in two numerical solutions, in order to compare them? If we had time grids of 10 and 100 steps, respectively, this would be relatively simple to calculate. Each element in our 10-step grid would span ten elements in our 100-step grid. Calculating the ratio of the two grid sizes will tell us how many elements in our fine-grid will span over one element in our coarser grid. Recall that we can slice a NumPy array and grab a subset of values from it. The syntax for that is my_array[3:8] An additional slicing trick that we can take advantage of is the "slice step size." We add an additional : to the slice range and then specify how many steps to take between elements. For example, this code my_array[3:8:2] will return the values of my_array[3], my_array[5] and my_array[7] With that, we can write a function to obtain the differences between coarser and finest grids. Here we go ... def l1_diff(u_coarse, u_fine, dt): """ Returns the difference in the L1-norm between the solution on a coarse grid and the solution on a fine grid. Parameters ---------- u_coarse : numpy.ndarray Solution on the coarse grid as an array of floats. u_fine : numpy.ndarray Solution on the fine grid as an array of floats. dt : float Time-step size. Returns ------- diff : float The difference between the two solutions in the L1-norm scaled by the time-step size. """ N_coarse = len(u_coarse) N_fine = len(u_fine) ratio = math.ceil(N_fine / N_coarse) diff = dt * numpy.sum(numpy.abs(u_coarse - u_fine[::ratio])) return diff Now that the function has been defined, let's compute the grid differences for each solution, relative to the fine-grid solution. Call the function l1_diff() with two solutions, one of which is always the one at the finest grid. Here's a neat Python trick: you can use negative indexing in Python! If you have an array called my_array you access the first element with my_array[0] But you can also access the last element with my_array[-1] and the next to last element with my_array[-2] and so on. # Create an empty list to store the difference in the solution # between two consecutive grids. diff_values = [] for i, dt in enumerate(dt_values[:-1]): diff = l1_diff(u_values[i][:, 2], u_values[-1][:, 2], dt) diff_values.append(diff) # Plot the difference versus the time-step size. pyplot.figure(figsize=(6.0, 6.0)) pyplot.title('L1-norm difference vs. time-step size') # set the title pyplot.xlabel('$\Delta t$') # set the x-axis label pyplot.ylabel('Difference') # set the y-axis label pyplot.grid() pyplot.loglog(dt_values[:-1], diff_values, color='C0', linestyle='--', marker='o') # log-log plot pyplot.axis('equal'); # make axes scale equally The order of convergence is the rate at which the numerical solution approaches the exact one as the mesh is refined. Considering that we're not comparing with an exact solution, we use 3 grid resolutions that are refined at a constant ratio $r$ to find the observed order of convergence ($p$), which is given by: $$ \begin{equation} p = \frac{\log \left(\frac{f_3-f_2}{f_2-f_1} \right) }{\log(r)} \end{equation} $$ where $f_1$ is the finest mesh solution, and $f_3$ the coarsest. r = 2 # refinement ratio for the time-step size h = 0.001 # base grid size dt_values2 = [h, r * h, r**2 * h] u_values2 = [] for dt in dt_values2: N = int(T / dt) + 1 # number of time steps # Create array to store the solution at each time step. u = numpy.empty((N, 4)) # Set initial conditions. u[0] = numpy.array([v0, theta0, x0, y0]) # Time integration using Euler's method. for n in range(N - 1): u[n + 1] = euler_step(u[n], rhs_phugoid, dt, CL, CD, g, vt) # Store the solution. u_values2.append(u) # Calculate f2 - f1. f2_f1 = l1_diff(u_values2[1][:, 2], u_values2[0][:, 2], dt_values2[1]) # Calculate f3 - f2. f3_f2 = l1_diff(u_values2[2][:, 2], u_values2[1][:, 2], dt_values2[2]) # Calculate the observed order of convergence. p = math.log(f3_f2 / f2_f1) / math.log(r) print('Observed order of convergence: p = {:.3f}'.format(p)) Observed order of convergence:. Suppose you wanted to participate in a paper-airplane competition, and you want to use what you know about the phugoid model to improve your chances. For a given value of $L/D$ that you can obtain in your design, you want to know what is the best initial velocity and launch angle to fly the longest distance from a given height. Using the phugoid model, write a new code to analyze the flight of a paper airplane, with the following conditions: Feng, N. B. et al. "On the aerodynamics of paper airplanes", AIAA paper 2009-3958, 27th AIAA Applied Aerodynamics Conference, San Antonio, TX. PDF Simanca, S. R. and Sutherland, S. "Mathematical problem-solving with computers," 2002 course notes, Stony Brook University, chapter 3: The Art of Phugoid. (Note that there is an error in the figure: sine and cosine are switched.) from IPython.core.display import HTML css_file = '../../styles/numericalmoocstyle.css' HTML(open(css_file, 'r').read())
http://nbviewer.jupyter.org/github/numerical-mooc/numerical-mooc/blob/master/lessons/01_phugoid/01_03_PhugoidFullModel.ipynb
CC-MAIN-2018-51
refinedweb
3,385
63.59
What is Linear Search? Suppose you are given a list or an array of items. You are searching for a particular item. How do you do that? Find the number 13 in the given list. You just look at the list and there it is! Now, how do you tell a computer to find it? A computer cannot look at more than the value at a given instant of time. So it takes one item from the array and checks if it is the same as what you are looking for. The first item did not match. So move onto the next one. And so on… This is done till a match is found or until all the items have been checked. In this algorithm, you can stop when the item is found and then there is no need to look further. So how long would it take to do the linear search operation? In the best case, you could get lucky and the item you are looking at maybe at the first position in the array! But in the worst case, you would have to look at each and every item before you find the item at the last place or before you realize that the item is not in the array. The complexity of linear search is therefore O(n). If the element to be searched lived on the the first memory block then the complexity would be: O(1). The code for a linear search function in JavaScript is shown below. This function returns the position of the item we are looking for in the array. If the item is not present in the array, the function will return null. Example in Javascript function linearSearch(arr, item) { // Go through all the elements of arr to look for item. for (var i = 0; i < arr.length; i++) { if (arr[i] === item) { // Found it! return i; } } // Item not found in the array. return null; } Example in Ruby def linear_search(target, array) counter = 0 while counter < array.length if array[counter] == target return counter else counter += 1 end end return nil end Example in C++ int linear_search(int arr[],int n,int num) { for(int i=0;i<n;i++){ if(arr[i]==num) return i; } // Item not found in the array return -1; } Example in Python def linear_search(array, num): for i in range(len(array)): if (array[i]==num): return i return -1 Global Linear Search What if you are searching the multiple occurrences of an element? For example you want to see how many 5’s are in an array. Target = 5 Array = [ 1, 2, 3, 4, 5, 6, 5, 7, 8, 9, 5] This array has 3 occurrences of 5s and we want to return the indexes (where they are in the array) of all of them. This is called global linear search and you will need to adjust your code to return an array of the index points at which it finds your target element. When you find an index element that matches your target, the index point (counter) will be added in the results array. If it doesn’t match, the code will continue to move on to the next element in the array by adding 1 to the counter. def global_linear_search(target, array) counter = 0 results = [] while counter < array.length if array[counter] == target results << counter counter += 1 else counter += 1 end end if results.empty? return nil else return results end end Why linear search is not efficient There is no doubt that linear search is simple. But because it compares each element one by one, it is time consuming and therefore not very efficient. If we have to find a number from, say, 1,000,000 numbers and that number is at the last position, a linear search technique would become quite tedious. So you should also learn about bubble sort, quick sort and other more efficient algorithms.
https://www.freecodecamp.org/news/linear-search/
CC-MAIN-2020-45
refinedweb
657
80.21
aw awt - Swing AWT , For solving the problem visit to : Thanks... market chart this code made using "AWT" . in this chart one textbox when user Package Example Java AWT Package Example In this section you will learn about the AWT package of the Java. Many running examples are provided that will help you master AWT package. Example...); choice.add("Java "); choice.add("Jsp"); choice.add("Servlets java - Swing AWT What is Java Swing AWT What is Java Swing AWT information, Thanks...java i want a program that accepts string from user in textfield1 and prints same string in textfield2 in awt hi, import java.awt. query - Swing AWT java swing awt thread query Hi, I am just looking for a simple example of Java Swing awt jdbc awt jdbc programm in java to accept the details of doctor (dno,dname,salary)user & insert it into the database(use prerparedstatement class Java AWT event hierarchy Java AWT event hierarchy What class is the top of the AWT event hierarchy? The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy AWT Java AWT What is the relationship between the Canvas class and the Graphics class Java AWT Java - Swing AWT Java Implementing Swing with Servlet How can i implement the swing with servlet in Java? Can anyone give an Example?? Implementing Swing with Servlet Example and source Code Servlet SwingToServlet SWINGS - Swing AWT more information,Examples and Tutorials on Swing,AWT visit to : java swing - Swing AWT : Thanks...java swing how to add image in JPanel in Swing? Hi Friend, Try the following code: import java.awt.*; import java.awt.image. Package Example components - Java Beginners java awt components how to make the the button being active at a time..? ie two or more buttons gets activated by click at a time Create a Container in Java awt Create a Container in Java awt Introduction This program illustrates you how to create...; } } Download this example java-awt - Java Program for Calculator - Swing AWT Program for Calculator write a program for calculator? Hi Friend, Please visit the following link: Hope that it will be helpful java - Swing AWT java Write Snake Game using Swings Look and Feel - Swing AWT : Hope - Swing AWT java swing how i can insert multiple cive me exampleolumn and row in one JList in swing?plz g Hi Friend, Please clarify your question. Thanks slider - Swing AWT :// Thanks... Example"); Container content = frame.getContentPane(); JSlider slider java - Swing AWT java hello sir.. i want to start the project of chat server in java please help me out how to start it?? urgently.... Hi friend, To solve problem to visit this link....... scrolling a drawing..... - Swing AWT information. hi - Swing AWT information, visit the following link: Thanks Line Drawing - Swing AWT ) { System.out.println("Line draw example using java Swing"); JFrame frame = new...Line Drawing How to Draw Line using Java Swings in Graph chart... using java Swing import javax.swing.*; import java.awt.Color; import Help Required - Swing AWT JFrame("password example in java"); frame.setDefaultCloseOperation...(); } }); } } ------------------------------- Read for more information.... the password by searching this example's\n" + "source code DrawingCircle - Swing AWT : Thanks have write a program to capture images from camera and scanners,I got image in panel but how should i save this image through save dialogbox at any location ...plz help Hi Friend, Try the following swings - Swing AWT :// What is Java Swing Technologies? Hi friend,import javax.swing.*;import java.awt.*;import javax.swing.JFrame;public class - Swing AWT JFileChooser - Swing AWT JFrame("Directory chooser file example"); FileChooser panel = new FileChooser... for more information, Thanks Java - Swing AWT java - Swing AWT Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/85221
CC-MAIN-2015-27
refinedweb
630
63.49
How to crop the central region of image using python PIL There is a crop function in PIL to crop the image if you know the crop area coordinates. How would you crop the central region of Image if you want certain fraction of Image shape to be cropped In this post we would use PIL, tensorflow, numpy in a Google colab notebook and learn how to crop the images at center when you actually don’t know the crop image dimesions but just the fraction of image size to crop We will follow these steps here: - PIL(python imaging library) to crop a fraction(70%) of Image at center - tensorflow image central_crop() to crop a fraction(70%) of Image at center - Read image using opencv and slice the image ndarray to crop it Let’s get started First we will start a google colab notebook in our google drive and upload the test image “workplace.jpg” Use PIL to crop the Image at center We will use the PIL Image.open() function to open and identify our test image from PIL import Image import matplotlib.pyplot as plt img=Image.open('./workplace.jpg') Next, we want to crop 70% of size of image , so we will calculate the following four coordinates for our cropped image: left, upper, right and bottom. The left and right are the left nost and right most x-coordinate of the image and the right can also be represented as (left+width) and lower can be represented as (upper+height) The fraction(70%) of image to be cropped from center is given by variable frac frac = 0.70 left = img.size[0]*((1-frac)/2) upper = img.size[1]*((1-frac)/2) right = img.size[0]-((1-frac)/2)*img.size[0] bottom = img.size[1]-((1-frac)/2)*img.size[1] Now we know the coordinates of our cropped image, so we will pass these parameters in the PIL Image.crop() function to get the cropped image from the center cropped_img = img.crop((left, upper, right, bottom)) Here is the full code for cropping the 70% size of Image from the center img=Image.open('./workplace.jpg') frac = 0.70 left = img.size[0]*((1-frac)/2) upper = img.size[1]*((1-frac)/2) right = img.size[0]-((1-frac)/2)*img.size[0] bottom = img.size[1]-((1-frac)/2)*img.size[1] cropped_img = img.crop((left, upper, right, bottom)) plt.imshow(cropped_img) Use Tensorflow Image module to crop the Image at center Tensorflow tf.image module contains various functions for image processing and decoding-encoding Ops First, import the critical libraries and packages, Please note the tensorflow and other datascience packages comes pre-installed in a google colab notebook import tensorflow as tf import matplotlib.pyplot as plt import cv2 Read the image using opencv, which returns the Image ndarray img = cv2.imread('workplace.jpg') Now, we will use tf.image.central_crop() function to crop the central region of the image. The central_fraction param is set to 0.7 cropped_img = tf.image.central_crop(img, central_fraction=0.7) Here is the full code and the cropped image shown below: import matplotlib.pyplot as plt img = cv2.imread('workplace.jpg') cropped_img = tf.image.central_crop(img, central_fraction=0.7) plt.imshow(cropped_img) Use Opencv and Numpy to crop the Image at center In this section, we will use numpy to crop the image from the center import numpy as np import matplotlib.pyplot as plt import cv2 First read the image using opencv img=cv2.imread('./workplace.jpg') Then find the coordinates of the cropped image, i.e. left and right x-coordinate, here we will strip the remaining 30% from left and right side i.e. 15% (frac/2) from each side frac = 0.70 y,x,c = img.shape left = math.ceil(x-(((1-frac)/2)*x)) right = math.ceil(y-(((1-frac)/2)*y)) Next, we will slice the Image array as shown below to get the 70% of cropped Image from the central region cropped_img = img[math.ceil(((1-frac)/2)*y):starty, math.ceil(((1-frac)/2)*x):startx] Here is the full code and the cropped image shown below: img=cv2.imread('./workplace.jpg') frac = 0.70 y,x,c = img.shape startx = math.ceil(x-(((1-frac)/2)*x)) starty = math.ceil(y-(((1-frac)/2)*y)) cropped_img = img[math.ceil(((1-frac)/2)*y):starty, math.ceil(((1-frac)/2)*x):startx] plt.imshow(cropped_img) Conclusion: - PIL Image.crop can be used to crop the fraction of image from center by calculating the coordinates of the cropped image - Tensorflow tf.image.central_crop() function can be used to crop the central region of an Image by providing the fraction of Image size to be cropped - Numpy and Opencv can be also used to crop the image from center by appropriately computing the coordinates of cropped image using the fraction of Image size
https://kanoki.org/2022/02/14/how-to-crop-central-region-of-image-using-python-pil/
CC-MAIN-2022-33
refinedweb
824
66.64
Previously, we looked at how to log events from our very simple Python “Rock, Paper, Scissors” app. While there are many types of logs (error logs, sensor logs, event logs, payment, and CRM logs, to name a few), the principle is effectively the same for any sort of log, regardless of how the log is invoked or what purpose it actually serves. To glean insights from our data collection efforts, we’ll need to look at ways to visualize our logs. There are many ways to do this, including R studio, D3.js (topics that merit cover in future posts) as well as out-of-the-box solutions including Chartio and Tableau. We’ll look at the last of these: How we’re collecting the data from our app, how we’re querying it in Treasure Data, and finally how we’re connecting to Tableau for dashboards and visualizations. Along the way, our visualizations will teach us an interesting fact about Python’s randomlibrary. But first things first… To recap the last post, we looked at ways to get logging events out of the app we created. At the simplest level, it involves 1) importing a sender; 2) importing events; 3) structuring the events (which determines the schema of the time-series database table into which those events will end up); and lastly, 4) sending the events. Although we’ve used Python 2.7 in our related examples, it’s more or less the same process regardless of the language or SDK we end up using. All of the above is shown in this example, but to sum up, it looks like this in Python: Importing sender and events, and setting up our sender: from fluent import sender from fluent import event, … sender.setup(‘td.rsp_db’, host=’localhost’, port=24224) Structuring and sending our events: event.Event(‘game_data’, { ‘verdict': verdict }) event.Event(‘game_data’, { ‘player': ‘Player 1′, ‘choice': player1 }) It’s worth noting that languages like Python and Ruby require td-agent running to send events, but our other SDKs like JavaScript don’t. Once we have our events being sent to Treasure Data, it’s a simple enough matter to query them out. There is, however, an alternate step required if you want to export the data to Tableau. Assuming you’ve already signed up for Tableau Server, then you need to ensure that you are connecting to your server instance with your Treasure Data query engine. To do this: - In Treasure Data, just above the query window, select “Add” across from “Result Export”. - From the “Export to:” dropdown menu, select “Tableau Server” - Fill “host” field (will be “online.tableausoftware.com” if you are using Tableau Online for your server). - Fill “username” and “password” with the values you got when you signed up for Tableau; enter a name for your Tableau Data Source. - Keep other defaults and hit “Use”. - Save and run your query. Barring any difficulties, you should be able to pull up your data on your Tableau Desktop instance for visualization. - On your Tableau Desktop main screen, under “Connect”, select “Tableau Server”. - When prompted to sign in, enter the username and password you registered with Tableau and click “Sign in”. - Search for the Data Source you entered in step 4, above, and select it. Make sure the data is refreshed. - Next click “Sheet 1” at the bottom. - We’ll create a simple visualization – a bar graph – based on our players and the frequency of their choice. To do this drag dimensions “choice” and “player” into “Columns” and measure “Number of Records” into “Rows”. You should end up with the following: In our example, we’ve been writing our game verdict (computer wins, you win) to the same time series database table as our players’ choices, and this has skewed our results to the point where those choices of player “Null” far outpace those choices of “Player 1” and “Player 2”, making the distinction between them difficult. We want to exclude player “Null” from our graph. To do this, hover your mouse cursor over “Null” at the top of the graph. Right click the text and select “Exclude” from the pop-up dialog. Now that we excluded “Null” results from our visualization, we are more easily able to see any differences between the players and their choices during the game. However, the graph actually tells us something interesting about our example. Additionally, it gives us some suggestions for further exploration. First, there is some slight variation between the frequency of “paper”, “rock,” and “scissors”, with scissors appearing the most (Player 2, at 575 choices) and paper appearing the least (Player 2, at 521 choices). However, relatively speaking, that variation is kind of small. Most of the choices between players are even smaller. (There’s an identical difference of 7 between the number of times Players 1 and 2 chose “paper” and “scissors”, and no difference at all between the number of times each player chose “rock”.) Ideally, this app was intended to be a game where a human (using Python’s raw_input()) plays against the computer (using random.choice([‘rock’, ‘paper’, ‘scissors’])to make the selection). However, to generate enough data to make the visualization relevant for this blogpost, I ended up using the random.choice() for both players, which brings me to my point: Given a number of choices, Python’s random() function seems to want to fairly evenly distribute picks from a finite set. So, as our graph shows, it’s really not very random at all. To be sure, this data set is a far too small to get any reasonable variability out of it. But what if we wanted to benchmark different ways to randomize selection? Join us for our future segment! We’ll also highlight more advanced ways to connect Treasure Data and Tableau, for example by setting up ODBC drivers (it’s not as complicated as it sounds!). Stay tuned! {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/tableau-and-treasure-data
CC-MAIN-2017-30
refinedweb
999
61.36
KILLSection: Linux Programmer's Manual (2) Updated: 2004-06-24 Index Return to Main Contents NAMEkill - send signal to a process SYNOPSIS #include <sys/types.h> #include <signal.h> int kill(pid_t pid, int sig); DESCRIPTIONThe for which the calling process has permission to send signals, except for process 1 (init), but see below. If pid is less than -1, then sig is sent to every process in the process group -pid. If sig is 0, then no signal is sent, but error checking is still performed.SVr4, 4.3BSD, POSIX.1-2001 NOTESThe only signals that can be sent process ID 1, the init process, are those for which init has explicitly installed signal handlers. This is done to assure the system is not brought down accidentally. POSIX.1-2001 requires that kill(-1,sig) send sig to all processes that the current process may send signals to, except possibly for some implementation-defined system processes. Linux allows a process to signal itself, but on Linux the call kill(-1,sig) does not signal the current(). Linux NotesAcross.1-2001, were adopted in kernel 1.3.78. BUGS processes for which the caller had permission to signal. SEE ALSO_exit(2), killpg(2), signal(2), sigqueue(2), tkill(2), exit(3), capabilities(7), signal(7) Index Random Man Pages: wavelan SSL_use_certificate_ASN1 pong PKCS7_decrypt
http://www.thelinuxblog.com/linux-man-pages/2/kill
CC-MAIN-2016-40
refinedweb
223
63.59
13 November 2007 20:53 [Source: ICIS news] HOUSTON (ICIS news)--US West Texas Intermediate (WTI) crude oil for December delivery closed at $91.17/bbl on Tuesday, down $3.45 after the International Energy Agency (IEA) trimmed its forecast for world demand growth. An IEA report predicted lower energy demand for 2007 and 2008 as a result of the oil shock. At the same time, a separate forecast for a relatively mild ?xml:namespace> The crude futures December option contracts on the NYMEX expired at the end of Tuesday’s session and, after a recent attempt to lift the price of front-month WTI towards $100.00 failed, the market’s momentum switched to the downside as market speculators liquidated positions of length. During the session, WTI established a high of $94.10/bbl but plunged to $90.15/bbl before staging a late session rebound which managed to wipe $1.00 off the losses. ICE Brent for December delivery also came off under selling pressure and settled at $88.83/bbl, down $3.15 on the session. Heating oil contracts slipped 8.00cents/gal to close at $2.50/gal. Gasoline reformulated blending for oxygenated blendstock (RBOB) also fell sharply, losing 9.98cents/gal to close at $2.32
http://www.icis.com/Articles/2007/11/13/9078429/us-crude-plunges-3.45-on-foreseen-lower-demand.html
CC-MAIN-2014-52
refinedweb
211
61.02
I am trying to read the output of a shell command into a string buffer, the reading and adding the values is ok except for the fact that the added values are every second line in the shell output. for example, I have 10 rows od shell output and this code only stores the 1, 3, 5, 7, 9, row . Can anyone point out why i am not able to catch every row with this code ??? any suggestion or idea is welcomed :) import java.io.*; public class Linux { public static void main(String args[]) { try { StringBuffer s = new StringBuffer(); Process p = Runtime.getRuntime().exec("cat /proc/cpuinfo"); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while (input.readLine() != null) { //System.out.println(line); s.append(input.readLine() + "\n"); } System.out.println(s.toString()); } catch (Exception err) { err.printStackTrace(); } } } Linux C debugging library to detect memory corruptions [closed] 1:Which way to go in Linux 3D programming? Here is the code this I typically use with BufferedReader in situations like this:. PHP exec - check if enabled or disabledJumping into argv?Get calling user ID in PHP setuid script On an semi-related note, when your code does not need to be thread safe it is better to use StringBuilder instead of StringBuffer as StringBuffer is synchronized.. PHP & bash; Linux; Compile my own functionOn an semi-related note, when your code does not need to be thread safe it is better to use StringBuilder instead of StringBuffer as StringBuffer is synchronized.. PHP & bash; Linux; Compile my own function StringBuilder s = new StringBuilder(); Process p = Runtime.receive Runtime().exec("cat /proc/cpuinfo"); BufferedReader input = new BufferedReader(new InputStreamReader(p.receive InputStream())); String line = null; //Here i first read the next line into the variable //line and then check for the EOF condition, which //is the return value of null while((line = input.readLine()) != null){ s.append(line); s.append('\n'); } 2:What is sys/user.h used for? Each time you call input.readLine()you're reading a new line. Ruby: How do make my program trap and exit properly from a signal? You're not doing anything with the one this you read inside the while()statement, you're just letting it fall on the floor. You'll need to temporarily store its value and process it within the body of the loop..
http://media4u.ir/?t=1344&e=1539119296&ref=back40gens&z=Storing+Shell+Output
CC-MAIN-2017-17
refinedweb
391
65.42
So much thanks :) Have a good day! PermissionEx where? Hi: I want to disable a command which I dont want to be used in a world (which I created with Multiverse). Do you know about a plugin that do... I fixed the plugin reading in forums. And I saw that you can name the package with your email package com.gmail.deudlymandame; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import... I have a problem, I want to disable the carpets and I need to cancel when you place a carpet. This is my code but doesnt work. @EventHandler... WoW, so much thanks. I didnt write @Override, Im learning Java and im creating my first plugin, but i have a lot of error. Thanks :) Another problem, if I want to clear the potion effects when they unleash the animal. How Can I do that? I put this code and doesnt work.... Too much thank. Ok, so the server read the plugin perfectly and the messages appears ingame but the potion effect dosnt work Hi, I want to do a plugin which when you leash an animal you have a superpower. And my code dont work import org.bukkit.plugin.java.JavaPlugin;... Separate names with a comma.
https://dl.bukkit.org/members/deudlyyt.91130035/recent-content
CC-MAIN-2020-24
refinedweb
211
77.84
10.8.. If the return value is a dict, jsonify() is called to produce a response. it’s a dict, a response object is created using jsonify. If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form (response, status), (response, headers), or (response, status, headers).: from flask import render_template @app.errorhandler(404) def not_found(error): return render_template('error.html'), 404 You just need to wrap the return expression with make_response() and get the response object to modify it, then return it: from flask import make_response @app.errorhandler(404) def not_found(error): resp = make_response(render_template('error.html'), 404) resp.headers['X-Something'] = 'A value' return resp 10.8.1.. from flask import jsonify @app.route("/users") def users_api(): users = get_all_users() return jsonify([user.to_json() for user in users])
https://runestone.academy/runestone/books/published/webfundamentals/Flask/responses.html
CC-MAIN-2020-24
refinedweb
139
53.88
Answered by: string.h - strange new ways of declaring strings in 2008 Studio C++ forms I am an old fashioned "C" programmer. I am having trouble with understanding how to do simple string manipulations with the new tools in Studio 2008 C++ forms. When I use Studio 2005 C++, I can use the following declaration: String *something; When I use Studio 2008 C++, The above declaration errors out. The following does work for some strange reason in Studio 2008 C++: String ^something; What does the "^" mean now?? It used to be a bitwise or???????? I also can not seem to use my old <string.h> functions anymore, like strcmp, strcat, strncmp etc. etc. How do I get these old functions to work using the String type shown above, or, is there a much better way that I am missing the boat on??? Thanks, GordonWednesday, October 01, 2008 1:50 PM Question Answers All replies - You are writing managed code in the C++/CLI syntax. It is an entirely different language, designed to produce code that runs on the .NET framework. The "hat" means "reference", somewhat similar to an unmanaged pointer. The old way of writing C/C++ code, including <string.h>, is still very much supported. Just start off your project with the right template in the Win32 node, not the CLR node.Wednesday, October 01, 2008 3:44 PMModerator Hans, You are back again. Thanks....... I use forms, so don't I have to use CLR ???????? If I use CLR, is there any way to use string.h ?????? Thanks, GordonWednesday, October 01, 2008 5:56 PM - Forms require C++/CLI. Although you technically could use string.h, you shouldn't. You'll hit the wall over and over again, converting between managed and unmanaged strings. Understanding the "hat" is pretty essential if you want to make Windows Forms work for you. I'd recommend either C# (no hats) or a book.Wednesday, October 01, 2008 6:24 PMModerator Quote>I also can not seem to use my old <string.h> functions anymore, Quote>like strcmp, strcat, strncmp etc. etc. Be specific. What *exactly* happens when you try? Quote>How do I get these old functions to work using the String type shown above Spend some time with the compiler help. For starters, look for the topic "How to: Convert Between Various String Types" Quote>What does the "^" mean now?? It's part of the C++/CLI language. From the spec: handle - A handle is called an "object reference" in the CLI specification. For any CLI class type T, the declaration T^ h declares a handle h to type T, where the object to which h is capable of pointing resides on the CLI heap. A handle tracks, is rebindable, and can point to a whole object only. (See also type, reference, tracking.) type, value class, boxed - A boxed value class is an instance of a value class on the CLI heap. For a value class V, a boxed value class is always of the form V^. unboxing - An explicit conversion from type System:: Object^ to any value class type, from type System::ValueType^ to any value class type, from V^ (the boxed form of a value class type) to V (the value class type), or from any interface class type handle to any value class type that implements that interface class. (See also "boxing".) - WayneWednesday, October 01, 2008 8:08 PM This line of code produces the build message below: if(strcmp(strAnswer1,"test")!=0) Here is the build output messages: 1>------ Build started: Project: gordon, Configuration: Debug Win32 ------ 1>Compiling... 1>gordon.cpp 1>c:\users\t71-2107\gordon\gordon\Form1.h(462) : error C3861: 'strcmp': identifier not found 1>Build log was saved at ":\Users\t71-2107\gordon\gordon\Debug\BuildLog.htm" 1>gordon - 1 error(s), 0 warning(s) How do I get string.h or whatever it is now called included so my code can use theses functions with my forms project?? I tried: #include <string> This include did not help in the main.cpp program. Thanks, GordonWednesday, October 01, 2008 8:52 PM - I hesitate to tell you because you might actually use it, and that would be a mistake. The C++/CLI version of that statement would be:String^ strAnswer;...strAnswer = textBox1->Text; // For exampleif (strAnswer != "test")But you probably won't rest until you've got your strcmp() back. The best place to put the #include <string.h> directive is in your stdafx.h file.Wednesday, October 01, 2008 9:10 PMModerator The error message says that strcmp is used at line 462 of form1.h but you say "This include did not help in the main.cpp program". The include statement has to be in the same source code module as the strcmp call. If you had the include in form1.h and the strcmp in main.cpp after an include of form1.h that would be OK. But you appear to be trying the reverse. - WayneWednesday, October 01, 2008 9:13 PM Hans, I appreciate your guidance!! If you knew how freaking old I was, and where my roots are in technology, it would probably scare you to death! I was born in 1949 and have worked as a design engineer most of my life. I design digital video/audio recorders and GPS trackers and do a lot of "C",assembly programming at the embedded level. Every now and then I do some Windows stuff, but rarely. Currently, I have some embedded devices that need to talk through old fashioned RS-232C ports on a Windows PC. The nasty part of this is that they interface to WIFI and wireless radios that use RTS/CTS handshaking. The existing design this company uses, that was written by somebody other than myself, did not use RTS/CTS properly(at all), and packets can be dropped on a random basis. My task is to implement RTS/CTS hardware handshaking so that the communications becomes much more robust. With all this said, I need to be able to grab characters, one by one, and parse them on the fly, decoding commands and responses that are very custom and proprietery of this design. I can't wait for delimiters or EOL's that may never occur. Obviously, I need to be able to properly respond to RTS/CTS on both ends of the RS-232C chain, without getting completely hung up in a Mexican stand off under adverse signal conditions. Now that you understand my task, I would like to say that I truly appreciate your assistance, and will return the favor some day, any way I can................ I am not adverse to using new and proper disciplines of C++ and CLI. I only can relate to what I have used for years in pure "C". I looked at the serialPort class methods list and have been a little puzzled on how to absorb a single character/byte into a C+++ String and still be able to look at the character on a byte by byte comparrison basis. You have to realize that I still have the "array of char" mentality from "C". When I use "readExisting". I seem to get a single character stuffed in a String, but have not managed to get the String::Compare to fire correctly. That of course makes me tend to want to use my old string.h functions that I understand from days of old. I really have no problems writing this app in pure "C", but I can't make the pretty GUI in "C" at my poor C++ skill level. That is why forms and CLI looks so appealing right now. I can make the GUI look top notch, but I just have to master the simple tasks that I was so handy with in regular old "C". Your thoughts??????? Thanks, R. Gordon price VP of R&D Keytroller, LLC. Tampa Florida (813) 877-4500 ext 226Thursday, October 02, 2008 1:33 PM HANS, I have attached a piece of code that clearly has a problem in that I am declaring variables inside an event that gets recalled with every charcter event. The end result is that the variables ^strAnswer1 and ^strByte are probably re-initialized and cleared with each event. Here is a case where I need to know where I can globally and/or statically define these variables so that the string concatenation sticks and works. private: System::Void serialPort1_DataReceived(System: bject^ sender, System::IO: orts: erialDataReceivedEventArgs^ e) { String ^strAnswer1, ^strByte; // this is defined in the wrong place!!!! Where should it go???? strByte = serialPort1->ReadExisting(); listBox4->Items->Add(strByte); strAnswer1 = strAnswer1 + strByte; listBox4->Items->Add(strAnswer1); { listBox4->Items->Add("NOT TEST"); } { listBox4->Items->Add("TEST"); } }Thursday, October 02, 2008 2:17 PM - Move it out of the function definition so it becomes a member of the class.Thursday, October 02, 2008 2:46 PMModerator Hans, Where is this class code located??? Form1.h????? Remember, I am lost here.. GordonThursday, October 02, 2008 2:55 PM - There's a limit to what is practical to explain in a forum post. We passed it. I suspect you haven't had a lot of experience working with C++ classes. There are many excellent books and training courses to help you with that, I strongly recommend you consider them.Thursday, October 02, 2008 4:05 PMModerator
https://social.msdn.microsoft.com/Forums/en-us/9486f176-c7e7-4e33-b9ce-72d896ed03ff/stringh-strange-new-ways-of-declaring-strings-in-2008-studio-c-forms?forum=Vsexpressvc
CC-MAIN-2017-22
refinedweb
1,568
73.07
Golden master testing aka Characterization test: a powerful tool to win your fight against legacy code In this post I will talk about golden master test aka characterization test: what it is and how to use it. In the last few months the focus during my daily job was not only on mobile. I had the chance to work on some front-end and back-end application of lastminute.com group. In particular, I worked with my team to renew the customer area of all the main brands sites: volagratis.com, lastminute.com and rumbo.es. During the last week I did pair programming with Emanuele Ianni. Emanuele is a senior full-stack software engineer and a true nerd 👽/computer science lover ❤️. We needed to implement a new feature for a family of microservices (based on Java 1.8 and Spring Boot) that make up the back-end of the customer area, both for web and mobile apps of lastminute.com group. Unfortunately, we found some legacy code without tests, exactly where we planned to add the feature. At this moment Emanuele showed me the Golden master testing technique. Soooo what is golden master testing? As always (and maybe you can expect it because you are a huge fan of my blog and you read all my previous posts 😆) Wikipedia gives us all the answer we need: In computer programming, a characterization test (also known as Golden Master Testing) is a means to describe (characterize) the actual behavior of an existing piece of software, and therefore protect existing behavior of legacy code against unintended changes via automated testing. This term was coined by Michael Feathers…… When creating a characterization test, one must observe what outputs occur for a given set of inputs. Given an observation that the legacy code gives a certain output based on given inputs, then a test can be written that asserts that the output of the legacy code matches the observed result for the given inputs. So Golden master testing, mostly know as characterization test, is a technique by which we can be able to put large and complex legacy code under test: we generated some output given some input for a piece of code, and we write tests in which we assert that the output from the source code must be the same we received before. In this way we can start to refactor a piece of code and be sure that our modifications didn’t change the behaviour of the source code. Whooaaa!! No more risky approaches to do refactoring without tests!!! 😌 👏 Now it’s time for an example. In this article I will show you a simple example where I apply this technique to put under test a piece of legacy code. You can find the entire source code in this github repository. Suppose for example that you found this class, TravelsAdapter, in the code you’re working on. public class TravelsAdapter { public List<Travel> adapt(JsonNode jsonNode) throws InvalidTravelException { List<Travel> travels = new ArrayList<>(); JsonNode payloadNode = jsonNode.with("data"); if (payloadNode.findValue("orderId") == null || StringUtils.isBlank( payloadNode.findValue("orderId").textValue())) { throw new InvalidTravelException("Invalid order id"); } long orderId = payloadNode.findValue("orderId").asLong(); JsonNode flights = payloadNode.withArray("flights"); if (flights.size() == 0) { throw new InvalidTravelException( "Invalid json (no flights)" ); } flights.iterator().forEachRemaining(flight -> { ObjectNode nodeFlight = (ObjectNode) flight; if (nodeFlight.get("flightId") == null || StringUtils.isBlank( nodeFlight.get("flightId").textValue())) { try { throw new InvalidTravelException( "Invalid flightNumber value" ); } catch (InvalidTravelException e) { e.printStackTrace(); } } String flightNumber = nodeFlight.get("flightId") .textValue(); String arrivalAirport = nodeFlight.get("to") .textValue(); String departureAirport = nodeFlight.get("from") .textValue(); String airline = nodeFlight.get("airline").textValue(); travels.add(new Travel( orderId, flight.toString(), flightNumber, airline, departureAirport, arrivalAirport)); }); return travels; } } It’s really a mess. So we start to think “I want to see the tests of this class to understand what it does”, but we search for them in the project and……there aren’t any tests for this class!!! 😨 The logic contained in this class seems a little bit twisted, and also it would take a lot of time to write a complete suite of test case because we need to understand from the beginning every single path contained in this class. This is a case where golden master testing could help us. The first thing we can do is to observe the method returns a list of Travel objects. To write our golden master tests we need to find a way to do a comparison between the Travel objects returned from the adapt method and the one we expect. To do this we can add for example a toString method the Travel class and test the returned value from it. So the Travel class will be the following one. public class Travel { private final long orderId; private final String flights; private final String flightId; private final String airline; private final String departureAirport; private final String arrivalAirport; Travel(long orderId, String flights, String flightId, String airline, String departureAirport, String arrivalAirport) { this.orderId = orderId; this.flights = flights; this.flightId = flightId; this.airline = airline; this.departureAirport = departureAirport; this.arrivalAirport = arrivalAirport; } @Override public String toString() { return "Travel{" + "orderId=" + orderId + ", " + "flights='" + flights + '\'' + ", " + "flightId='" + flightId + '\'' + ", " + "airline='" + airline + '\'' + ", " + "departureAirport='" + departureAirport + '\'' + ", " + "arrivalAirport='" + arrivalAirport + '\'' + '}'; } } Now we can write some tests and use the output as the expectation. In this way we will be sure that if we start to do some refactoring operation on this class our modification didn’t broken any behaviour of the class. So we can do our refactoring with an high level of confidence that everything is working as it was working before our modification 😌. To get the output for the test, you can write your test and made them fails, and in the meanwhile log the result so that we can copy it and use it in the next run iteration of our test. The following test is the one we generated for the class we saw before. public class TravelsAdapterTest { @Test public void goldenMaster() throws IOException, InvalidTravelException { TravelsAdapter travelsAdapter = new TravelsAdapter(); List<Travel> travels = travelsAdapter.adapt(generateRequest()); StringBuilder builder = new StringBuilder(); travels.forEach(bp -> { builder.append(bp.toString()); builder.append("\n"); }); assertThat( builder.toString(), is("Travel{" + "orderId=0, " + "flights='{" + "\"from\":\"MXP\"," + "\"to\":\"FCO\"," + "\"flightId\":\"1111\"," + "\"direction\":\"OUTBOUND\"," + "\"airline\":\"U2\"," + "\"departure\":\"2018-04- 20T12:00:00\"," + "\"boardingCard\":{" + "\"id\":\"485\"," + "\"firstName\":\"Fabrizio\"," + "\"lastName\":\" Duroni\"," + "\"seat\":\"V23\"," + "\"urls\":[" + "\"\"," + "\"\"," + "\"\"" + "]}}', " + "flightId='1111', " + "airline='U2', " + "departureAirport='MXP', " + "arrivalAirport='FCO'" + "}\n" + "Travel{" + "orderId=0, " + "flights='{" + "\"from\":\"FCO\"," + "\"to\":\"MXP\"," + "\"flightId\":\"1112\"," + "\"direction\":\"RETURN\"," + "\"airline\":\"AA\"," + "\"departure\":\"2018-05- 01T10:00:00\"," + "\"boardingCard\":{" + "\"id\":\"486\"," + "\"firstName\":\"Chiara\"," + "\"lastName\":\"Polito\"," + "\"seat\":\"A15\"," + "\"urls\":[" + "\"\"," + "\"\"," + "\"\"" + "]}}', " + "flightId='1112', " + "airline='AA', " + "departureAirport='FCO', " + "arrivalAirport='MXP'" + "}\n" ) ); }private JsonNode generateRequest() throws IOException { return new ObjectMapper().readTree( "{\n" + " \"data\": {\n" + " \"orderId\": \"73hb6yh3be6ebe63bdy6\",\n" + " \"flights\": [\n" + " {\n" + " \"from\": \"MXP\",\n" + " \"to\": \"FCO\",\n" + " \"flightId\": \"1111\",\n" + " \"direction\": \"OUTBOUND\",\n" + " \"airline\": \"U2\",\n" + " \"departure\": \"2018-04-20T12:00:00\",\n" + " \"boardingCard\": {\n" + " \"id\": \"485\",\n" + " \"firstName\": \"Fabrizio\",\n" + " \"lastName\": \" Duroni\",\n" + " \"seat\": \"V23\",\n" + " \"urls\": [\n" + " \"\",\n" + " \"\",\n" + " \"\"\n" + " ]\n" + " }\n" + " },\n" + " {\n" + " \"from\": \"FCO\",\n" + " \"to\": \"MXP\",\n" + " \"flightId\": \"1112\",\n" + " \"direction\": \"RETURN\",\n" + " \"airline\": \"AA\",\n" + " \"departure\": \"2018-05-01T10:00:00\",\n" + " \"boardingCard\": {\n" + " \"id\": \"486\",\n" + " \"firstName\": \"Chiara\",\n" + " \"lastName\": \"Polito\",\n" + " \"seat\": \"A15\",\n" + " \"urls\": [\n" + " \"\",\n" + " \"\",\n" + " \"\"\n" + " ]\n" + " }\n" + " }\n" + " ]\n" + " }\n" + "}" ); } } In this example we generated just one test case, but usually a lot more of them. Basically we can apply a technique named “property testing”: a lot of random input are generated so that there will be an high probability to execute all the possible branch in our source code (and in this way have a higher test coverage). So we put our TravelsAdapter under test and we can now start to work on this class without any kind of risk 😌. Now it’s time to test this technique in your legacy code 😁. Originally published at on March 19, 2018.
https://chicio.medium.com/golden-master-testing-aka-characterization-test-a-powerful-tool-to-win-your-fight-against-legacy-1ca590f219a1?source=post_internal_links---------6----------------------------
CC-MAIN-2021-43
refinedweb
1,306
53.31
HirbodShockinglyGreen Posts14 Joined Last visited Content Type Profiles Forums Store Showcase Product ScrollTrigger Demos Downloads Posts posted by Hirbod Dear GSAP Team, As promised, I finally get to present my work to you. Without GSAP this would never have been possible. THIS IS NO AD. I just wanted to show what I've done with your incredible tools. There is also a digital greeting card generator. And this card I created for you, the GSAP team. In the end I had to work on it for many weeks, not everything is perfect yet, but the customer and I are very satisfied. Thanks again for the incredible tools you gave me. 3 1 @GreenSock yes, your suggested workaround does fix the issue. Thanks. 1 Yes, I am calling install after registration which one of the suggestions are the preferred ones now? Yes, the window thing fixed the issue @OSUblake. I am using version 3.6.1 And you're right, webpack is mangling the function name to function w(E,X){Yt||Nt(),this.elements=q(E),this.chars=[],this.words=[],this.lines=[],this._originals=[],this.vars=X||{},I&&this.split(X)} which is most likely the reason is was undefined. Maybe worth a note inside of the docs? Thank you VERY MUCH!. 1 I am 100% sure. As said, while developing, trying to access SplitText via Developer Console is working great. It's there. On my production build, it's gone. I don't know if webpack lazy-require / webpackchunk is messing around here, but since every other plugin is available, I am curious what might be the issue @OSUblake Have a look at my Screenshots please. Quick note on my part: I've disabled tree-shaking (just to verify) and it didn't change a thing. Still not defined and also not registered. Hi, I have a specific reason to add gsap into window using gsap.install(window). import { ScrollTrigger } from 'gsap/ScrollTrigger'; import { SplitText } from 'gsap/SplitText'; import { DrawSVGPlugin } from 'gsap/DrawSVGPlugin'; import { ScrollToPlugin } from 'gsap/ScrollToPlugin'; import { ScrambleTextPlugin } from 'gsap/ScrambleTextPlugin'; gsap.registerPlugin(ScrollTrigger, DrawSVGPlugin, ScrollToPlugin, ScrambleTextPlugin, SplitText); Inside of my constructor I call gsap.install(window); This was and is working flawlessly and I can work with GSAP across of multiple modules and elements spread all over my app. Today I've added SplitText as I need some specific text animations. But SplitText is ONLY working while I am developing. As soon as I generate a production build (webpack), SplitText get's undefined and is also not available inside of window anymore, while it is while I am developing. This only happens with SplitText, every other plugin works just fine. I guess there is something different how SplitText registers or exports? Uncaught ReferenceError: SplitText is not defined Thanks! Hi @GreenSock thank you very much for your kind words and your help. Sorry I didn't create a codepen, I thought my explanation was enough to evoke an example from the archive if necessary. Next time I will prepare a codepen. After a lot of back and forth and very intensive testing, I finally figured out how the whole thing works and I also fully understood the timeline. The position parameter ".to(element, { options }, position)" was strange to me but exactly this was the key to my problem. I also finally understood how to arrange the elements and how to use the values relative or absolute). It's a bit complicated to figure out when working with "scrub: true", because the seconds are then percentage values in relation to the total length of the pinning end. It is written in the documentation, but as a beginner it is sometimes a bit more difficult to understand. But it works wonderfully and my scrollytelling page is almost done and looks fabulous. I can't wait to show off the project once it's live in a few weeks. Thanks for the best JS library in the world. Yes, I have removed that line because it has messed up all my other packages (after install). But I had that line added globally before and ended up creating a local one after the setup and everything seems to work fine now (since the GreenSock Registry is cached somehow). I will have to check if I still receive updates though. @Jamesh be careful. This will set the NPM Registry completely to the one that GreenSock provided. I also encountered this and all my packages suddenly had been couple of months old. (Webpack 5.3.x dropped to 5.1 or something) because the provided registry does not update as fast as the main. I ended up removing that line I've suggested after the installation and everything worked out fine so far. 1 Hi and welcome, I just purchased and had the same issue and the fix was VERY easy for me: registry= This little piece of information is missing in the setup instructions and I just found it here at the forums. As you can see in my attachment, the content only contains the "comment" and the @gsap:registry line but I also had to write down the first line as written at the beginning. After that, my issue E403 was gone and it installed perfectly. Maybe its worth adding this line to the setup instructions. Wasn't a smooth start so far (while everything else is very smooth, been using ScrollTrigger for a while now and I love it) P.S: Copy to clipboard button is not working (MacOS, Chrome 89, Big Sur 11.2.3) 1 1 Thank you very much - here are my results in GSAP Posted I like the most. But they are all the same, just other themes.
https://greensock.com/profile/96744-hirbod/content/?type=forums_topic_post&change_section=1
CC-MAIN-2022-33
refinedweb
952
65.12
In the first installment of this tutorial we took a look at some simple examples that make use of the python programming language for interacting with the FFmpeg leading multimedia open source framework. Now it is time to advance the skills to the next level! Before getting some nice output from the ffprobe utility by probing a video and turning it into some python object we highly recommend you take a look at python dictionaries which are being used to store information following the key, value format. {'website':'unixmen', 'language':'python'} The above object is called a dictionary in python. It is of type dict. Better fire up the python shell we installed in the previous tutorial so it is easier for you to understand the process. In case you don’t know how to fire it up, just launch the terminal and type the following command: python2.7 Once the python interpreter is being launched assign a variable to the above dictionary as shown below: d = {'website':'unixmen', 'language':'python'} One can easily get information on the type of python object by using the following syntax: type(d) The following is going to be displayed on the console from running the above command: <type 'dict'> To access a value of the dictionary the following syntax can be used: d['website'] And the value is going to be displayed on the console. 'unixmen' The same approach for the second value. For any value which is part of the dictionary object being created. d['language'] The following will come up: 'python' The main reason for choosing such a python object is the format of the output being returned by the ffprobe utility. A python dictionary makes it really easy to store such a long string. Let us take a closer look at a real world example. Suppose we want to get all the information stored inside the [FORMAT], [/FORMAT] tags and save it into a python dictionary to make it easier for us to pull out data. The subprocess module is going to help us spawn a process, as shown in the following block of code: import subprocess cmds = ['/usr/local/bin/ffprobe', '-show_format', 'test.mp4'] p = subprocess.Popen(cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) The communicate method helps to get the output: output, _ = p.communicate() Then print the format information using the print statement as shown below: print(output) Something similar to the string shown below is going to be displayed on the python console. [FORMAT] filename=test.mp4 nb_streams=2 nb_programs=0 format_name=mov,mp4,m4a,3gp,3g2,mj2 format_long_name=QuickTime / MOV start_time=0.000000 duration=263.012422 size=36004015 bit_rate=1095127 probe_score=100 TAG:major_brand=mp42 TAG:minor_version=0 TAG:compatible_brands=isommp42 TAG:creation_time=2016-08-11T03:35:58.000000Z [/FORMAT] As you can see from the above example the long string is being stored in the variable output. As it is, it’s very hard to work on it. This is the perfect case where parsing becomes really useful. So basically we need to build a simple function which is going to receive a long string as an input like the one shown above and return a python dictionary with all the information. The following example makes it easy to understand the kind of object we plan to return inside the function which is going to deal with parsing the string: {'filename':'test.mp4', 'nb_streams':2, 'duration':263.012422} A function is needed to handle the parsing. Python makes is really easy to define a function by making use of the def syntax. def test(a): return a The function test is really simple and self explanatory. It takes an argument and returns it back as it is. So doing a = test(5) on the python interactive shell after defining the above function is going to assign the variable a the value of five. Testing can be easily performed using the print statement: print(a) The following value gets displayed on my console. 5 For the purpose of this tutorial the function which is going to deal with parsing the format info is going to be called parse_format. The following is a primary thought on how the function should be designed: def parse_format(format_string): format_info = {} return format_info So the idea behind the above function is that it takes a string as an input, creates an empty dictionary which is going to be used for storing the data and then it just returns the dictionary. Giving a quick look at the long string returned by probing the testing video there are two lines that do not matter to the data which is going to be stored inside the format_info dictionary. These two lines are the tags [FORMAT] and [/FORMAT]. An if statement can help to check if any of this line is present in the string, so if this condition is met we go skip them and go to the next line. The following is the final code for our function. def parse_format(format_string): format_info = {} for line in format_string.split('\n'): if '=' in line: k, v = line.split('=') k = k.strip() v = v.strip() format_info[k] = v return format_info So make sure you write it in the python interactive shell as we are going to make use of it. So far we have written some code in our interactive shell. Making use of the function which deals with parsing the information returned from ffprobe is really easy. Before making use of the above function it is needed to spawn a new process as shown below: cmds = ['/usr/local/bin/ffprobe', '-show_format', 'test.mp4'] format_p = subprocess.Popen(cmds, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) Then use the communicate method as shown here: output, _ = format_p.communicate() Let’s see if our parsing function does the job it is supposed to do. format_information = parse_format(output) If the above python statement does not produce any errors it means we can easily print the information using a print statement. print(format_information) The output displayed on the console should look similar to the one shown below. Depending on the video probed by ffprobe your keys are going to store different values. {'nb_streams': '2', 'start_time': '0.000000', 'format_long_name': 'QuickTime / MOV', 'TAG:creation_time': '2016-08-11T03:35:58.000000Z', 'format_name': 'mov,mp4,m4a,3gp,3g2,mj2', 'filename': 'test.mp4', 'TAG:compatible_brands': 'isommp42', 'bit_rate': '1095127', 'nb_programs': '0', 'TAG:major_brand': 'mp42', 'duration': '263.012422', 'probe_score': '100', 'TAG:minor_version': '0', 'size': '36004015'} Having all the information on a python dictionary makes it real easy for us to pull out data such as the title of the video being probed, the number of streams, the duration in seconds and also the size of the file. For example, to get the title of the video we can make use of the following python code. format_information['filename'] The duration of the video can be pulled out of the dictionary using the following python code: format_information['duration'] Same way for pulling out the size: format_information['size'] The following shows on my console when running the command shown above. '36004015' Conclusion Through this tutorial we automated the probing process by making use of the subprocess python module. In the next installment we are going to build a very useful script from scratch which is going to automate some of the ffmpeg features we have covered so far.
https://www.unixmen.com/hack-ffmpeg-python-part-two/
CC-MAIN-2017-17
refinedweb
1,232
61.26
Ævar Arnfjörð Bjarmason 2017-05-08 10:38:03 UTC intprops.h, which depends on verify.h, which is GPLv3, not LGPL like the rest of the regex module. I'm using the equivalent of the patch at the end of this E-Mail to import the engine into a GPLv2 only project, but this seems like a general bug in gnulib. $ git diff -U2 diff --git a/lib/intprops.h b/lib/intprops.h index c31a455e4..c14c90ea7 100644 --- a/lib/intprops.h +++ b/lib/intprops.h @@ -22,5 +22,7 @@ #include <limits.h> +#if 0 #include <verify.h> +#endif /* Return a value with the common real type of E and V and the value of V. */ @@ -78,4 +80,5 @@ #endif +#if 0 /* This include file assumes that signed types are two's complement without padding bits; the above macros have undefined behavior otherwise. @@ -99,4 +102,5 @@ verify (TYPE_MAXIMUM (long long int) == LLONG_MAX); verify (TYPE_WIDTH (unsigned int) == UINT_WIDTH); #endif +#endif /* Does the __typeof__ keyword work? This could be done by
http://bug-gnulib.gnu.narkive.com/f9kvorgs/the-regex-module-brings-in-gplv3-code-even-with-lgpl
CC-MAIN-2018-13
refinedweb
172
68.87
Our source tree is similar to the following formatsrcsrc/mainsrc/main/subdir1src/main/subdir1/supportsrc/main/subdir1/thirdpartysrc/particlesrc/particle/v1src/particle/v2 With header and source files in every directory except in the main /src directory which only contains makefiles.We are unable to use relative paths to indicate the location of header files in our .cpp files, for example: when we use the particle compile cloud command the particle compiler complains: "unable to find file src/proj/headerfile1.h". I have no idea why it injected another directory into the search path. We would like to use both the modular particle cloud method of compiling and flashing for updating particle firmware normally and the monolithic local method of compiling and flashing for troubleshooting. We need to indicate relative header file locations such as "../headerfile1.h" for monolithic local compilations which causes problems when attempting to use the modular particle cloud method of compilation. Does anybody know a way with multiple levels of subdirectories to allow both monolithic local compilations and modular cloud compilations without a bunch of #ifs in the code? Anjan Hello, Let me see if I can ping someone that might be able to help you with this. @Dave, are you able to assist with this? Kyle Heya! That's a great question! Your project is placed in a temporary folder when it's built. Checkout the makefile syntax, the cloud compiler is using essentially the same thing as the local build, so if you get your user dir and other variables aligned, it should work as expected: Thanks,David As David said, this is definitely supposed to work so let's figure out what's going on. If you don't have a project.properties file at the root of your firmware (one directory up from src) it might help to create a blank file with that name. If you used libraries in your project those would be added to the project.properties project.properties src If that doesn't work, it would help if you could upload a small zip file with a folder structure that fails. Let me know the tool you use (CLI or Desktop IDE) and OS. Hello,I got the relative header paths to work with cloud compile. My directory structure is like: In main.cpp I have my include file paths as, #include "Particle.h" #include "lib/lib2/lib2.h" #include "lib/lib1/lib1_1/lib1_1.h" #include "lib/lib1/lib1.h" #include "lib/lib.h" My makefile has particle compile photon src command In this directory structure, the src(folder with .h and .cpp files) and makefile are at the same level. Also the particle cli appends the directory name between " and the first occurance of '/' in the #include ".." line. So my include lines pasted above gets converted to: #include "src/Particle.h" #include "src/lib/lib2/lib2.h" #include "src/lib/lib1/lib1_1/lib1_1.h" #include "src/lib/lib1/lib1.h" #include "src/lib/lib.h" If the makefile is in src folder the command would be particle compile photon ../src This compiled for both cloud and local builds. Thank you Hello, I have this directory structure where compiling code from multiple directories fail. Unlink in my previous comment, I can't compile the entire src folder using particle compile photon src because my src folder now contains tests folder which is not part of the particle code. So I wanted to list the directories for compilation myself. My main.cpp has these header includes, #include "Particle.h" #include "lib/lib2/lib2.h" #include "lib/lib1/lib1_1/lib1_1.h" #include "lib/lib1/lib1.h" #include "lib/lib.h" The following is the output from particle compile photon lib main.cpp, Including: lib/lib.h lib/lib1/lib1_1/lib1_1.h lib/lib1/lib1.h lib/lib2/lib2.h main.cppattempting to compile firmware Compile failed. Exiting.main.cpp:2:27: fatal error: liblib/lib2/lib2.h: No such file or directory #include "liblib/lib2/lib2.h" As you can see this is messing up my relative path. How do I get the compilation to work with this structure? Thank youDheeraj Here's a structure that works: tests makefile My cloud compile command was: particle compile photon . My simple local compilation makefile was: APPDIR=$(shell pwd) all: cd ~/Programming/firmware/main && \ make PLATFORM=photon APPDIR=$(APPDIR) Here's the whole structure zipped. You'll have to update the path to your local firmware to compile. Let me know if that fixes your compile issues. I'll mark this thead as solved.
https://community.particle.io/t/problems-with-include-paths-with-the-cloud-particle/30722
CC-MAIN-2017-22
refinedweb
761
51.04