When studying modules, the first thing you hear is that they are very similar to classes. This is true in the way they are written and that they both hold methods, but that’s about the extent of their similarities. Although they can be used to do the same things at times, they should not be used interchangeably — there is a right and wrong construct to use. Since I covered classes in last week’s post, refer back to that if you need a refresher.
When thinking of modules, it’s safe to think of their purpose as providing a library of methods (usually across classes), while classes are used to make instances of itself (objects) with predefined methods and variables. You cannot instantiate a module. One of the main benefits of a module is how it acts a collection of methods that can be used by many classes.If you ever have a class that you are not creating instances of, it should probably be a module.
The second advantage of modules is namesapcing. Since modules are often loaded into programs from other files, the possibility of two methods having the identical names but different characteristics is very high. Modules takes care of this by namespacing. Without namespacing, it would be very confusing to know which of two identically names methods will be run by the program. To namespace, you would write the name of the module, plus two colons, followed by the method/class from the module. Like so, ModuleName::Method. This will explicitly refer to the method from that particular module if need be.
Here is how you would write a module and include that module in a class:
module ThisIsAModule
def method_1
things
end
end
class ThisIsAClass
include ThisIsAModule
def method_2
end
end


Useful set of tools for plotting network diagrams in any kind of project.
| Version: | 1.0.0 |
| Imports: | reshape2, ggplot2, grid |
| Published: | 2015-07-22 |
| Author: | Javier Celigueta Mu<c3><b1>oz |
| Maintainer: | Joaquin Bienvenido Ordieres Mere <j.ordieres at upm.es> |
| License: | GPL-3 |
| NeedsCompilation: | no |
| CRAN checks: | PlotPrjNetworks results |
| Reference manual: | PlotPrjNetworks.pdf |
| Package source: | PlotPrjNetworks_1.0.0.tar.gz |
| Windows binaries: | r-devel: PlotPrjNetworks_1.0.0.zip, r-release: PlotPrjNetworks_1.0.0.zip, r-oldrel: PlotPrjNetworks_1.0.0.zip |
| OS X binaries: | r-release: PlotPrjNetworks_1.0.0.tgz, r-oldrel: PlotPrjNetworks_1.0.0.tgz |
Please use the canonical form https://CRAN.R-project.org/package=PlotPrjNetworks to link to this page.


Programming Language - Subtyping
Some Good Subtyping Rules
- Width subtyping: A supertype can have a subset of fields with the same types, i.e., a subtype can have extra fields.
- Permutation subtypings: A supertype can have the same set of fields with the same types in a different order.
- Transitivity: if t1 is subtype of t2, and t2 is subtype of t3, then t1 is subtype of t3.
- Reflexivity: Every type is a subtype of itself.
Given the three features of (1) setting a field, (2) letting depth subtyping change the type of a field, and (3) having a sound type system actually prevent field-missing errors, we can have any two of the three, but not all of them.
Function Subtyping
Function subtyping contravariant in argument(s) and covariant in results.
If t3 is subtype of t1, and t2 is a subtype of t4, then t1 -> t2
is a subtype of t3 -> t4
.


North Dakota Library Resources
Go beyond Google.
Search local resources.
Any
Title
Author
Subject
ISBN
Looking for more?
Search Databases
Need help with Databases?


|
| def | __init__ (self, name=None, poolSize=1024) |
| |
| def | accelerate (self, time, stepCount=1, stepTime=0.0) |
| |
| def | addForce (self, force) |
| |
| def | cleanup (self) |
| |
| def | disable (self) |
| |
| def | enable (self) |
| |
| def | getEmitter (self) |
| |
| def | getFactory (self) |
| |
| def | getName (self) |
| | Getters ##. More...
|
| |
| def | getNode (self) |
| |
| def | getPoolSizeRanges (self) |
| |
| def | getRenderer (self) |
| |
| def | isEnabled (self) |
| |
| def | printParams (self, file=sys.stdout, targ='self') |
| |
| def | removeForce (self, force) |
| |
| def | setEmitter (self, type) |
| |
| def | setFactory (self, type) |
| |
| def | setRenderer (self, type) |
| |
| def | setRenderNodePath (self, nodePath) |
| |
| Public Member Functions inherited from ParticleSystem |
| | __init__ (const ParticleSystem copy) |
| | Copy Constructor. More...
|
| |
| | __init__ (int pool_size) |
| | Default Constructor. More...
|
| |
| | addSpawnTemplate (ParticleSystem ps) |
| |
| | clearFloorZ () |
| |
| | clearSpawnTemplates () |
| |
| | clearToInitial () |
| | Resets the system to its start state by resizing to 0, then resizing back to current size. More...
|
| |
| bool | getActiveSystemFlag () |
| |
| float | getBirthRate () |
| |
| BaseParticleEmitter | getEmitter () |
| |
| BaseParticleFactory | getFactory () |
| |
| float | getFloorZ () |
| |
| bool | getIWasSpawnedFlag () |
| |
| int | getLitterSize () |
| |
| int | getLitterSpread () |
| |
| int | getLivingParticles () |
| |
| bool | getLocalVelocityFlag () |
| |
| int | getPoolSize () |
| |
| BaseParticleRenderer | getRenderer () |
| |
| NodePath | getRenderParent () |
| |
| float | getSoftBirthRate () |
| |
| bool | getSpawnOnDeathFlag () |
| |
| PandaNode | getSpawnRenderNode () |
| |
| NodePath | getSpawnRenderNodePath () |
| |
| float | getSystemAge () |
| |
| bool | getSystemGrowsOlderFlag () |
| |
| float | getSystemLifespan () |
| |
| float | getTicsSinceBirth () |
| |
| | induceLabor () |
| | Forces the birth of a particle litter this frame by resetting _tics_since_birth. More...
|
| |
| | render () |
| | Populates an attached GeomNode structure with the particle geometry for rendering.  More...
|
| |
| | softStop (float br) |
| | Causes system to use birth rate set by set_soft_birth_rate() More...
|
| |
| | update (float dt) |
| |
| | writeFreeParticleFifo (Ostream out, int indent) |
| | Write a string representation of this instance to <out>. More...
|
| |
| | writeSpawnTemplates (Ostream out, int indent) |
| | Write a string representation of this instance to <out>. More...
|
| |
| Public Member Functions inherited from Physical |
| | __init__ (const Physical copy) |
| | copy constructor (note- does deep copy of pn's) but does NOT attach itself to its template's physicsmanager. More...
|
| |
| | __init__ (int total_objects, bool pre_alloc) |
| | Default Constructor The idea here is that most physicals will NOT be collections of sets (i.e. More...
|
| |
| | addAngularForce (AngularForce f) |
| | Adds an angular force to the force list. More...
|
| |
| | addLinearForce (LinearForce f) |
| | Adds a linear force to the force list. More...
|
| |
| | addPhysicsObject (PhysicsObject po) |
| | Adds an object to the physics object vector. More...
|
| |
| | clearAngularForces () |
| | Erases the angular force list. More...
|
| |
| | clearLinearForces () |
| | Erases the linear force list. More...
|
| |
| | clearPhysicsObjects () |
| | Erases the object list. More...
|
| |
| AngularForce | getAngularForce (int index) |
| |
| list | getAngularForces () |
| |
| LinearForce | getLinearForce (int index) |
| |
| list | getLinearForces () |
| |
| int | getNumAngularForces () |
| |
| int | getNumLinearForces () |
| |
| const PhysicsObjectCollection | getObjects () |
| |
| PhysicsObject | getPhysBody () |
| |
| PhysicalNode | getPhysicalNode () |
| |
| NodePath | getPhysicalNodePath () |
| |
| PhysicsManager | getPhysicsManager () |
| |
| float | getViscosity () |
| | Get the local viscosity. More...
|
| |
| | output (Ostream out) |
| | Write a string representation of this instance to <out>. More...
|
| |
| | removeAngularForce (AngularForce f) |
| | removes an angular force from the force list More...
|
| |
| | removeLinearForce (LinearForce f) |
| | removes a linear force from the force list More...
|
| |
| | setViscosity (float viscosity) |
| | Set the local viscosity. More...
|
| |
| | write (Ostream out, int indent) |
| | Write a string representation of this instance to <out>. More...
|
| |
| | writeAngularForces (Ostream out, int indent) |
| | Write a string representation of this instance to <out>. More...
|
| |
| | writeLinearForces (Ostream out, int indent) |
| | Write a string representation of this instance to <out>. More...
|
| |
| | writePhysicsObjects (Ostream out, int indent) |
| | Write a string representation of this instance to <out>. More...
|
| |
| Public Member Functions inherited from TypedObject |
| TypeHandle | getType () |
| |
| int | getTypeIndex () |
| | Returns the internal index number associated with this object's TypeHandle, a unique number for each different type. More...
|
| |
| bool | isExactType (TypeHandle handle) |
| | Returns true if the current object is the indicated type exactly. More...
|
| |
| bool | isOfType (TypeHandle handle) |
| | Returns true if the current object is or derives from the indicated type. More...
|
| |
| Public Member Functions inherited from ReferenceCount |
| int | getRefCount () |
| | Returns the current reference count. More...
|
| |
| | ref () |
| | Explicitly increments the reference count. More...
|
| |
| bool | testRefCountIntegrity () |
| | Does some easy checks to make sure that the reference count isn't completely bogus. More...
|
| |
| bool | testRefCountNonzero () |
| | Does some easy checks to make sure that the reference count isn't zero, or completely bogus. More...
|
| |
| bool | unref () |
| | Explicitly decrements the reference count. More...
|
| |


Migrating a Windows Install to a New Macbook
Recently here at Headspring my workstation got upgraded from a PC laptop to a Macbook Pro. While I was excited about the new hardware and taking the plunge into Mac OS X (that’s the Roman numeral ten, not the 24th letter of the alphabet), I still needed to be able to run Windows and Visual Studio. This post summarizes the various options I explored, and my final setup.
Multiboot or Virtual Machine?
Multibooting is using a software tool that hooks your computer’s normal power on sequence and provides you a way to choose what operating system you want to load.
Microsoft has supported multibooting since Windows XP as way to install new versions of Windows while still keeping older versions for your legacy software that won’t work on the newer Windows version. It’s also been possible to multiboot Linux and Windows for a long time.
A virtual machine is software that pretends to be a computer, and runs another operating system inside of it. You can use a virtual machine to run an instance of Windows 98 while booted into Windows 7 for example.
The advantage to multibooting is performance - running an operating system inside a virtual machine causes it to run more slowly than it would if it was natively booted - but the disadvantage is you can only work within the one operating system you booted into.
Virtual machines can perform slower, but allow you to run both operating systems at the same time.
I’ve done multibooting with multiple versions of Windows and Linux in the past. It works well, but its amazing how much of a psychological barrier having to boot into an alternate OS to do something gets created. “I got an email response…I need to go update that spreadsheet…rats, it’s in the other OS…I really don’t want to close everything and reboot, I’ll do it later…”.
The new workstation is top of the line: Intel I7, 16GB memory, solid state hard disk. It would be more than capable of running Windows in a virtual machine without much overhead. Choosing a virtual machine over multibooting was a pretty easy choice.
There were several candidates for the virtual machine software - VMWare Fusion, Oracle VirtualBox, and Parallels Desktop. VirtualBox was ruled out pretty quickly as underperforming. Parallels and Fusion are fairly similar. We ended up going with Parallels.
How I Migrated My Old Windows Install to Parallels
I didn’t want to have to start over with a brand new install of Windows, my old setup was perfectly fine. Fortunately Parallels supports migrating Windows from your old PC to your new Mac. It took three tries before I figured out the best way to do it, so I wanted to share and hopefully save someone else the learning experience. It wasn’t painful, but did consume a fair amount of wasted setup time.
There are several options for doing the migration: using a special USB cable you can buy from Parallels, over the network, or copying to an external hard drive.
We didn’t buy the cable, so attempt number one was over the wireless network. Big mistake. It took over twenty hours to transfer, and the virtual machine wouldn’t boot afterwards. Somehow it got corrupted during the transfer.
Attempt number two was copying to external storage. This took about as long, and was going to take another twenty hours to pull off the drive to the Macbook.
Fortunately at this point a coworker intervened and told me using a network crossover would be much quicker.\
What You’ll Need
The new Macbooks don’t have a built in ethernet port, so you’ll need a Thunderbolt to NIC adapter for this. You’ll also need an ethernet crossover cable - this is a special cable that crosses the wires from plug to the other, allowing you to connect two computers directly as if they were both on a network. Because it’s a direct connection there’s virtually no transfer overhead at all.
Performing the Transfer
On your Windows machine you need to go download and install Parallels Transporter. Start Parallels Transporter. The screen looks like this:
On the Mac download Parallels 8 and start it. Click File..Migrate. This will launch the migration wizard.
If you haven’t already done so, connect the crossover between the two computers. Choose Network. Choose IP Address instead. Select your Windows computer from the list. Alternately you can use ipconfig on your Windows machine to get your IP address and specify it manually if needed.
When asked how to configure the image, choose Like a PC. You can customize the settings later, but if you choose Like a Mac, Parallels will automatically copy your Documents folder into your Home directory in Mac OS, leaving you with two copies of everything.
That’s it! Using a crossover took about two hours - much faster than using the wireless network or copying it to external storage. When the transfer was complete, the virtual machine started without any issues (well, almost - I had to reactivate Windows) and I didn’t have to setup (and endlessly tweak) a new install.
Wrapping Up
I’m still getting used to my new Mac. There’s a lot that’s different from Windows and I’m now fighting twenty years of muscle memory (I started using Windows on version 3.11 in 1993). I plan on writing a follow up post on adjusting from Windows to Mac OS sometime in the future.
The transition pain is more than worth it - there are a lot of advantages to using a Mac with Windows. The hardware is rock solid, fast, and very light (it’s less than half the weight of my old workstation). The Retina display is gorgeous and highly readable. Also of note is the ability to now develop for multiple platforms - I can still use Visual Studio for .NET development, but also write apps for IOS and MacOS as well. Support for platforms like Ruby and node.js are also better on Mac than Windows.
Are you running Windows on a Mac? Are you using Parallels, or something else? Share your experiences or current setup in the comments!


RetailMeNot: Letter from the CEO
New Deal Alerts are here!
First, as one of our loyal customers at RetailMeNot, I’d like to apologize to you. We know you want simple, easy ways to save. Unfortunately, over the past few years, our Deal Alerts have fallen short.
That’s why I’m excited to share our new and improved Deal Alerts with you. Not only do they look better, they work better.
Sign up and see for yourself. Choose your favorite stores and never miss out on a great deal again.
And to celebrate, now through May 1st you can enter to win $100 just by signing up for Deal Alerts from the stores you love. We’re picking five winners each day!
Happy savings,
Cotter Cunningham
CEO, RetailMeNot
Sign up and enter at www.retailmenot.com/alerts
Copyright 2013. RetailMeNot, Inc. 301 Congress Avenue, Suite 700, Austin, Texas 78701
To opt-out please reply to this email with UNSUBSCRIBE in the subject line.


A place for Black/African, Latinx, Southeast Asian, and Indigenous people to connect with employers that align with their values, and build community with people that understand their perspective.
{{ item.text }}
{{ item.reference }}
Gain marketable skills with professional certificate courses from top universities
NO, you can sign up for a FREE TaSA account and immediately access all of our basic features including auditable edX courses from prestigious universities such as Harvard, MIT, Columbia, Stanford etc. We also offer premium membership options which enable access to certificate courses from Tier 1 and Ivy League institutions, as well as other enhanced job search and networking features.
Through our partnership with edX you get up to a 40% DISCOUNT on online Professional Certificate
courses from some of the world’s most prestigious universities, such as: Harvard, MIT, Columbia,
Cornell, Dartmouth, Stanford etc.
You get FREE access to:
NO! TaSA was designed for continental and Diaspora Africans (see AU definition of Diaspora Africans) at all stages of their professional journey regardless of their country of birth or country of residence. So whether you're an African American that was born and raised in the U.S.; An Afro-Caribbean that hails from the Islands; or an Afro-Latinx from Central or South America, we consider you a part of the global African talent pool, and therefore TaSA is for you.
NO! Though the discounted access to edX courses are only available to TaSA members/people with a TaSA account.
NO. Any Continental or Diaspora African can sign up for a FREE TaSA account and immediately access all of our basic features including auditable edX courses from prestigious universities such as Harvard, MIT, Columbia, Stanford etc.
Benefits of a TaSA partnership include but are not limited to:
NO! TaSA was designed for continental and Diaspora Africans (see AU definition of Diaspora Africans) at all stages of their professional journey regardless of their country of birth or country of residence. So whether you're an African American that was born and raised in the U.S.; An Afro-Caribbean that hails from the Islands; or an Afro-Latinx from Central or South America, we consider you a part of the global African talent pool, and therefore TaSA is for you.
Your Institution will have access to the entire edX course catalogue and we can filter courses to match your institutional preference.
Course start and end dates are determined by the course provider. That said, we work closely with edX and our University partners to optimize alignment between our University partners' academic calendar and the start and end date of select course offerings.
No.
To incentivize timely course completion, we strongly encourage partners to offer our provided courses as co-requisites alongside existing curricula offerings. A student who fails to complete a course within the allotted time in this scenario will be subject to institutional policies regarding this course outcome.
The price of courses will vary based on a variety of factors including whether or not it is a certificate granting course. For this reason, pricing will be based on the suite of courses you choose. Regardless of your selection, as a part of our social impact mission, TaSA is committed to ensuring up to a 40% discount (to university partners) on the actual value of edX provided courses.
No. You can start a company account and create a company profile on TaSA for free. We also offer premium membership accounts.
Benefits of a TaSA account to your company are as follows:
TaSA (Talent Source Africa) aims to cultivate the largest network of African and diaspora talent in the world. So whether you're looking to hire, market to, connect with, learn from, or simply breathe with Black and African people on the continent and in the diaspora, look no further than TaSA.
NO, The cost of job postings on TaSA are variable with factors such as length (how long you want it to be up) of posting; the level of targeting (do you want it to go to a particular audience) and industry impacting pricing. We do offer client-friendly pricing options including per-per-click postings (you pay only when job seekers click on your posting). To get a quote based on your precise needs please click here.


Aidan's Jukebox Player
Now playing: Test song - please ignore
Queued Songs:
To queue songs, jukebox.st-aidans.com


Bill Doolin, Laurie McLeod
"This paper draws on these two strands of research to complement the analysis of project-related artefacts as boundary objects with a sociomaterial perspective on such objects and the practices within which they are constituted."
"The contribution of this combined approach is illustrated using the findings of a longitudinal case study of IS development. We trace the production and use of a prototype, the various people and practices with which it was associated, the multiple sociomaterial configurations that constituted it as a boundary object, and the social and material consequences of its use."


Atletico go third as Morata's scoring streak rolls on
Atletico Madrid striker Alvaro Morata scored for the sixth game in a row to help his side to a 3-1 win at home to struggling Espanyol on Sunday, taking them up to third in La Liga.
MADRID: Atletico Madrid striker Alvaro Morata scored for the sixth game in a row to help his side to a 3-1 win at home to struggling Espanyol on Sunday, taking them up to third in La Liga.
Espanyol, who have only won twice in the league this season, took the lead against the run of play in the 38th minute when midfielder Sergi Darder fired home from just outside the area.
Atletico levelled on the stroke of halftime when Angel Correa glanced a header over the line following a goal-bound cross from Morata, with the goal eventually being awarded following a VAR review for a possible offside.
The home side had a penalty appeal turned down early in the second half after another VAR review but eventually took the lead in the 58th minute when Morata raced on to a pass from Vitolo and lashed the ball past visiting keeper Diego Lopez.
Koke struck the third in stoppage time, controlling a cut-back from Diego Costa and rolling the ball into the net to seal a much-needed win after five draws in Atleti's last six league games and defeat by Bayer Leverkusen in the Champions League.
The victory sees Atletico climb above Real Sociedad into third on 24 points after 13 games, one behind leaders Barcelona and second-placed Real Madrid who each have a game in hand.
(Reporting by Richard Martin; editing by Ken Ferris)


Share Better.
Leading the next generation of photo sharing on mobile devices.
mobile moments better.
Let's face it ... mobile photography and the sharing economy are here to stay.
The problem is that the services we use today have become overly crowded
with so many posts and ads that, honestly, it's difficult to stay interested.
Plus, we don’t socially share everything with everyone offline, so why should we online?
In today's sharing economy there are companies that are focused on building many valuable marketplaces.
For example, our homes (hospitality), our cars (transportation),
our stuff (consumer goods) and more.
Yet, when it comes to our most precious asset, our time (attention), there is no marketplace available — at least not without
constant interruptions and distractions.
We wanted sharing moments to be more fun, more collaborative, and more useful.
We wanted a better way to organize and share our moments with people
who share our interests and without all the noise and clutter.
So, we created one.
poppo is the next generation of photo sharing.
Beautifully designed with smaller screens in mind, poppo empowers people
to create collaborative photo albums based on our shared moments and interests.


Pear Mail
From Phpmaniac
Contents |
What is the Pear Mail extension
The Pear mail extension is an easy object oriented approach to sending email with PHP.
It can allow you to send multi-part MIME email without needing to know how things like boundaries and mime types work.
Why
PHP already has the command mail which can send email, and it's already built into the base of PHP.
This method is good, and I have used it many times, but in order to send complex emails including attachments and protect against mail header injection attacks, you need to have an in depth understanding of how email and MIME works.
The Pear Mail extension allows us to do this easily, quickly, and more importantly, it has been tested thoroughly, probably more so than any email code that we write.
Installing the Pear mail extension
If you already have pear installed on your server, you can install the pear mail extension by entering the following command.
# pear install mail # pear install Net_SMTP # pear install mail_mime
This will put the libraries that we need to use in PHP's include path for your operating system.
Sending your first email
This example shows how to create an email which will display html in html capable email clients, and text in non capable email clients.
-
<?
-
include('Mail.php');
-
include('Mail/mime.php');
-
-
// Constructing the email
-
$sender = "Leigh<EMAIL_ADDRESS>// Your name and email address
-
$recipient = "Leigh<EMAIL_ADDRESS>// The Recipients name and email address
-
$subject = "Test Email"; // Subject for the email
-
$text = 'This is a text message.'; // Text version of the email
-
$html = '
This is a html message
'; // HTML version of the email
-
$crlf = "\n";
-
$headers = array(
-
'From' => $sender,
-
'Return-Path' => $sender,
-
'Subject' => $subject
-
);
-
-
// Creating the Mime message
-
$mime = new Mail_mime($crlf);
-
-
// Setting the body of the email
-
$mime->setTXTBody($text);
-
$mime->setHTMLBody($html);
-
-
$body = $mime->get();
-
$headers = $mime->headers($headers);
-
-
// Sending the email
-
$mail =& Mail::factory('mail');
-
$mail->send($recipient, $headers, $body);
-
?>
Adding attachments
Adding one attachment
Adding 1 or many attachments is easy, adding the attachment is done by calling the addAttachment method, This method can be called multiple times to add multiple attachemnts.
boolean addAttachment (string $file, string [$c_type = 'application/octet-stream'], string [$name = ], boolean [$isfile = TRUE], string [$encoding = 'base64'])
Variables:
- $file: either the variable containing the content of a file, or the path of the file itself
- $c_type: content type, meaning the mime type of file eg. text/plain, text/csv, Application/pdf
- $name: The name of the file as you want it to appear in the email, this should be unique
- $isFile: whether the variable $file is the path to the file, or the content of the file
- $encoding: This should usually be left as the default unless you know what you are doing
Attachments can be either stored in a variable, or in a file on the servers file system. in this first example I will create a small text file named 'hello text.txt', with the words 'Hello World!' in it.
-
<?
-
include('Mail.php');
-
include('Mail/mime.php');
-
-
// Constructing the email
-
$sender = "Leigh<EMAIL_ADDRESS>// Who your name and email address
-
$recipient = "Leigh<EMAIL_ADDRESS>// The Recipients name and email address
-
$subject = "Test Email"; // Subject for the email
-
$text = 'This is a text message.'; // Text version of the email
-
$html = '
This is a html message
'; // HTML version of the email
-
$crlf = "\n";
-
$headers = array(
-
'From' => $sender,
-
'Return-Path' => $sender,
-
'Subject' => $subject
-
);
-
-
// Creating the Mime message
-
$mime = new Mail_mime($crlf);
-
-
// Setting the body of the email
-
$mime->setTXTBody($text);
-
$mime->setHTMLBody($html);
-
-
// Add an attachment
-
$file = "Hello World!"; // Content of the file
-
$file_name = "Hello text.txt"; // Name of the Attachment
-
$content_type = "text/plain"; // Content type of the file
-
$mime->addAttachment ($file, $content_type, $file_name, 0); // Add the attachment to the email
-
-
$body = $mime->get();
-
$headers = $mime->headers($headers);
-
-
// Sending the email
-
$mail =& Mail::factory('mail');
-
$mail->send($recipient, $headers, $body);
-
?>
Adding multiple attachments
As in the previous section, adding multiple attachments is as rasy as calling addAttachment again. In this example I will send an email with two text attachments.
-
<?
-
include('Mail.php');
-
include('Mail/mime.php');
-
-
// Constructing the email
-
$sender = "Leigh<EMAIL_ADDRESS>// Who your name and email address
-
$recipient = "Leigh<EMAIL_ADDRESS>// The Recipients name and email address
-
$subject = "Test Email"; // Subject for the email
-
$text = 'This is a text message.'; // Text version of the email
-
$html = '
This is a html message
'; // HTML version of the email
-
$crlf = "\n";
-
$headers = array(
-
'From' => $sender,
-
'Return-Path' => $sender,
-
'Subject' => $subject
-
);
-
-
// Creating the Mime message
-
$mime = new Mail_mime($crlf);
-
-
// Setting the body of the email
-
$mime->setTXTBody($text);
-
$mime->setHTMLBody($html);
-
-
// Add an attachment
-
$file = "Hello World!"; // Content of the file
-
$file_name = "Hello text.txt"; // Name of the Attachment
-
$content_type = "text/plain"; // Content type of the file
-
$mime->addAttachment ($file, $content_type, $file_name, 0); // Add the attachment to the email
-
-
// Add a second attachment
-
$file = "Hello World! Again :)"; // Content of the file
-
$file_name = "Hello text 2.txt"; // Name of the Attachment
-
$content_type = "text/plain"; // Content type of the file
-
$mime->addAttachment ($file, $content_type, $file_name, 0); // Add the attachment to the email
-
-
$body = $mime->get();
-
$headers = $mime->headers($headers);
-
-
// Sending the email
-
$mail =& Mail::factory('mail');
-
$mail->send($recipient, $headers, $body);
-
?>
Adding an attachment from the file system
Adding an attachment from the file system is easy, instead of specifying the contents of the file, we enter the path to the file and change the $isFile variable. In this example I will attach a PDF called 'example.pdf' which is located in the same folder as this script.
-
<?
-
include('Mail.php');
-
include('Mail/mime.php');
-
-
// Constructing the email
-
$sender = "Leigh<EMAIL_ADDRESS>// Who your name and email address
-
$recipient = "Leigh<EMAIL_ADDRESS>// The Recipients name and email address
-
$subject = "Test Email"; // Subject for the email
-
$text = 'This is a text message.'; // Text version of the email
-
$html = '
This is a html message
'; // HTML version of the email
-
$crlf = "\n";
-
$headers = array(
-
'From' => $sender,
-
'Return-Path' => $sender,
-
'Subject' => $subject
-
);
-
-
// Creating the Mime message
-
$mime = new Mail_mime($crlf);
-
-
// Setting the body of the email
-
$mime->setTXTBody($text);
-
$mime->setHTMLBody($html);
-
-
// Add an attachment
-
$file = "example.pdf"; // Content of the file
-
$file_name = "example.pdf"; // Name of the Attachment
-
$content_type = "Application/pdf"; // Content type of the file
-
$mime->addAttachment ($file, $content_type, $file_name, 1); // Add the attachment to the email
-
-
$body = $mime->get();
-
$headers = $mime->headers($headers);
-
-
// Sending the email
-
$mail =& Mail::factory('mail');
-
$mail->send($recipient, $headers, $body);
-
?>
Notice specifically in this example that I kept the file name in the email the same as the original, although I could just as easily change it. Additionally the the last variable in the method addAttachment was 1, this is to tell it that $file is the path to the file.
Sending to multiple recipients
The Pear mail package can accept an array of recipients or a list of comma separated email addresses. In this example we will use an array called $recipients.
For the best performance sending to multiple recipients we should use SMTP as it only has to connect to the SMTP server once.
-
<?
-
include('Mail.php');
-
include('Mail/mime.php');
-
-
// Constructing the email
-
$sender = "Leigh<EMAIL_ADDRESS>// Who your name and email address
-
$recipients = array();
-
$recipients[] = "Leigh account 1<EMAIL_ADDRESS>// Recipient name and email address
-
$recipients[] = "Leigh account 2<EMAIL_ADDRESS>// Recipient name and email address
-
$subject = "Test Email"; // Subject for the email
-
$text = 'This is a text message.'; // Text version of the email
-
$html = '
This is a html message
'; // HTML version of the email
-
$crlf = "\n";
-
$headers = array(
-
'From' => $sender,
-
'Return-Path' => $sender,
-
'Subject' => $subject
-
);
-
-
// Creating the Mime message
-
$mime = new Mail_mime($crlf);
-
-
// Setting the body of the email
-
$mime->setTXTBody($text);
-
$mime->setHTMLBody($html);
-
-
$body = $mime->get();
-
$headers = $mime->headers($headers);
-
-
// Sending the email
-
$mail =& Mail::factory('mail');
-
$mail->send($recipients, $headers, $body);
-
?>
Sending using SMTP
This example shows how to send an email using SMTP instead of the built in PHP mail() function. This is useful if you want to send using a remote server.
-
<?
-
include('Mail.php');
-
include('Mail/mime.php');
-
-
// Constructing the email
-
$sender = "Leigh<EMAIL_ADDRESS>// Your name and email address
-
$recipient = "Leigh<EMAIL_ADDRESS>// The Recipients name and email address
-
$subject = "Test Email"; // Subject for the email
-
$text = 'This is a text message.'; // Text version of the email
-
$html = '
This is a html message
'; // HTML version of the email
-
$crlf = "\n";
-
$headers = array(
-
'From' => $sender,
-
'Return-Path' => $sender,
-
'Subject' => $subject
-
);
-
-
// Creating the Mime message
-
$mime = new Mail_mime($crlf);
-
-
// Setting the body of the email
-
$mime->setTXTBody($text);
-
$mime->setHTMLBody($html);
-
-
// Add an attachment
-
$file = "Hello World!";
-
$file_name = "Hello text.txt";
-
$content_type = "text/plain";
-
$mime->addAttachment ($file, $content_type, $file_name, 0);
-
-
// Set body and headers ready for base mail class
-
$body = $mime->get();
-
$headers = $mime->headers($headers);
-
-
// SMTP params
-
$smtp_params["host"] = "smtp.example.com"; // SMTP host
-
$smtp_params["port"] = "25"; // SMTP Port (usually 25)
-
-
// Sending the email using smtp
-
$mail =& Mail::factory("smtp", $smtp_params);
-
$result = $mail->send($recipient, $headers, $body);
-
if($result === 1)
-
{
-
echo("Your message has been sent!");
-
}
-
else
-
{
-
echo("Your message was not sent: " . $result);
-
}
-
?>
Sending using authenticated SMTP
This example shows how to send an email using SMTP authentication. This particular example uses gmail to send. Gmails requirements for sending via SMTP are SMTP authentication with TLS. Fortunately, when we use authentication with Pear Mail, the connection is automatically TLS.
The difference between This example, and the previous example just using SMTP is the addition of the following SMTP parameters.
$smtp_params["auth"] = true; $smtp_params["username"] =<EMAIL_ADDRESS>$smtp_params["password"] = "pass";
-
<?
-
include('Mail.php');
-
include('Mail/mime.php');
-
-
// Constructing the email
-
$sender =<EMAIL_ADDRESS>// Your email address
-
$recipient = "Leigh<EMAIL_ADDRESS>// The Recipients name and email address
-
$subject = "Test Email"; // Subject for the email
-
$text = 'This is a text message.'; // Text version of the email
-
$html = '
This is a html message
'; // HTML version of the email
-
$crlf = "\n";
-
$headers = array(
-
'From' => $sender,
-
'Return-Path' => $sender,
-
'Subject' => $subject
-
);
-
-
// Creating the Mime message
-
$mime = new Mail_mime($crlf);
-
-
// Setting the body of the email
-
$mime->setTXTBody($text);
-
$mime->setHTMLBody($html);
-
-
// Add an attachment
-
$file = "Hello World!";
-
$file_name = "Hello text.txt";
-
$content_type = "text/plain";
-
$mime->addAttachment ($file, $content_type, $file_name, 0);
-
-
// Set body and headers ready for base mail class
-
$body = $mime->get();
-
$headers = $mime->headers($headers);
-
-
// SMTP authentication params
-
$smtp_params["host"] = "smtp.gmail.com";
-
$smtp_params["port"] = "25";
-
$smtp_params["auth"] = true;
-
$smtp_params["username"] =<EMAIL_ADDRESS>-
$smtp_params["password"] = "pass";
-
-
// Sending the email using smtp
-
$mail =& Mail::factory("smtp", $smtp_params);
-
$result = $mail->send($recipient, $headers, $body);
-
if($result === 1)
-
{
-
echo("Your message has been sent!");
-
}
-
else
-
{
-
echo("Your message was not sent: " . $result);
-
}
-
?>
Security
One of the major concerns of people sending automated emails using PHP is header injection. Mail header injection is the process of inserting additional fields into the mail headers such as extra "bcc" and "to" fields. This can be used by spammers to utilize your server to send spam and consequently having your server blacklisted by real time blacklists.
Pear mail automatically sanitizes the headers you pass to it so that we don't have to worry about it. The following code is what is used to sanitize the headers.
-
/**
-
* Sanitize an array of mail headers by removing any additional header
-
* strings present in a legitimate header's value. The goal of this
-
* filter is to prevent mail injection attacks.
-
*
-
* @param array $headers The associative array of headers to sanitize.
-
*
-
* @access private
-
*/
-
function _sanitizeHeaders(&$headers)
-
{
-
foreach ($headers as $key => $value) {
-
$headers[$key] =
-
preg_replace('=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i',
-
null, $value);
-
}
-
}
Taken from Mail.php authored by Chuck Hagenbuch Copyright (c) 1997-2003 The PHP Group version 2.02 of the PHP license
Troubleshooting
Pear not up to date
If you get the following:
# pear install mail_mime pear/Mail_Mime requires PEAR Installer (version >= 1.6.0), installed version is 1.4.9 pear/Mail_mimeDecode requires PEAR Installer (version >= 1.6.0), installed version is 1.4.9 pear/Mail_mimeDecode requires package "pear/Mail_Mime" (version >= 1.4.0, excluded versions: 1.4.
Run the following to upgrade Pear and you will be able to install Mail/Mime:
# pear upgrade-all
Pear Channels protocol not up to date
If you get:
# pear install mail WARNING: channel "pear.php.net" has updated its protocols, use "channel-update pear.php.net" to update
Run the following to update:
# pear channel-update pear.php.net
Emails not being sent
View the return value form the line
$mail->send($recipient, $headers, $body);
eg.
echo($mail->send($recipient, $headers, $body));
|
|


To more safe internet.
On the Internet, we should check the page is safe. But it's a difficult thing. So, we made a community database for it. In this site, you can check the domain is safe or not.
This Project can check in GitHub
This database is mantained under this rules.


partekflow
Table of Contents
- Module Description - What the module does and why it is useful
- Setup - The basics of getting started with partekflow
- Usage - Configuration options and additional functionality
- Reference - An under-the-hood peek at what the module is doing and how
- Limitations - OS compatibility, etc.
- Development - Guide for contributing to the module
Module Description
The partekflow module installs, configures, and manages Partek Flow software package and service. Partek Flow is "designed specifically for the analysis needs of next generation sequencing applications including RNA, small RNA, and DNA sequencing" that includes a web interface for creation and utilization of custom pipelines. http://www.partek.com/partekflow
Setup
What partekflow affects
- User and Group: flow
- Group: flowuser
- RPM GPG Key: /etc/pki/rpm-gpg/partek-public.key
- Yumrepos for accessing partek flow RPM repositories. The stable repositories are enabled while the unstable ones are not.
- Package: partekflow
- File: /etc/partekflow.conf
- Catalina temp directory location
- Service: partekflowd
Beginning with partekflow
include partekflow
should be all that is needed to install, configure and start the partekflowd service. One can also pass parameters in to change the configuration:
class { 'partekflow':
config_catalina_tmpdir => '/home/flow/partek_flow/temp',
}
Usage
All parameters are passed to the main class via either puppet code or hiera. The other classes should not be called directly. Some usage examples are presented below.
Install and startup partekflowd service
include partekflow
Change the location of the CATALINA_TMPDIR setting in /etc/partekflow.conf
class { 'partekflow':
config_catalina_tmpdir => '/home/flow/partek_flow/temp',
}
or via hiera:
---
partekflow::config_catalina_tmpdir: '/home/flow/partek_flow/temp'
To use a different template for the partekflow.conf file
class { 'partekflow':
config_template => 'module_name/path/to/template.erb',
}
To disable the stable repsitory files but still have them present in /etc/yum.repos.d/
class { 'partekflow':
yumrepo_ensure_stable => true,
yumrepo_enabled_stable => false,
}
To use a local repository mirror instead of the Partek repositories
class { 'partekflow':
yumrepo_baseurl_server => 'http://yum.example.com',
yumrepo_baseurl_stablepath => '/path/to/stable',
yumrepo_baseurl_unstablepath => '/path/to/unstable',
}
To remove the unstable /etc/yum.repos.d/ files
class { 'partekflow':
yumrepo_ensure_unstable => false,
}
Reference
Generated puppet strings documentation with examples is available from https://millerjl1701.github.io/millerjl1701-partekflow/.
It's also included in the docs/ folder as simple html pages.
Classes
Public Classes
- partekflow: Main class. Contains or calls all other classes or defines.
Private Classes
- partekflow::config: Handles configuration of the service.
- partekflow::install: Handles the installation of the software.
- partekflow::service: Manages the partekflowd service.
Parameters
The partekflow::init class has the following parameters:
Stdlib::Absolutepath $config_catalina_tmpdir = '/opt/partek_flow/temp',
Stdlib::Absolutepath $config_file = '/etc/partekflow.conf',
Stdlib::Absolutepath $config_installdir = '/opt/partek_flow',
String $config_template = 'partekflow/partekflow.conf.erb',
String $package_ensure = 'present',
String $package_name = 'partekflow',
Boolean $service_enable = true,
Enum['running', 'stopped'] $service_ensure = 'running',
String $service_name = 'partekflowd',
String $user_comment = 'Partek Flow daemon',
Enum['present', 'absent'] $user_ensure = 'present',
Integer[1, 999] $user_gid = 495,
String $user_groupname = 'flowuser',
Integer[1, 999] $user_groupname_gid = 494,
Stdlib::Absolutepath $user_home = '/home/flow',
Boolean $user_managehome = true,
String $user_name = 'flow',
Stdlib::Absolutepath $user_shell = '/bin/sh',
Integer[1, 999] $user_uid = 495,
Optional[Stdlib::Httpurl] $yumrepo_baseurl_server = undef,
Optional[String] $yumrepo_baseurl_stablepath = undef,
Optional[String] $yumrepo_baseurl_unstablepath = undef,
Optional[Boolean] $yumrepo_enabled_stable = undef,
Optional[Boolean] $yumrepo_enabled_unstable = undef,
Optional[Boolean] $yumrepo_ensure_stable = undef,
Optional[Boolean] $yumrepo_ensure_unstable = undef,
Optional[Boolean] $yumrepo_manage = undef
Limitations
This module is written to work with Puppet 4.7 or higher. Hiera 5 data is embedded within the module as well for Puppet 4.9 or higher. The module depends on Puppet 4 data types provided by puppetlabs-stdlib as well as the treydock-gpg_key module.
Originally written for CentOS 6/7 systems, it could work on other osfamily RedHat distributions. While Partek Flow supports installation on Debian based distributions, this module does not at this time.
This module was written to reflect initial installation and configuration documentation provided by Partek. This is not an all inclusive module as there are configuration tasks that need to be done via the web UI to configure portions of the application. If you find some configuration option would be helpful for maintaining the software on your own servers, please submit an issue or pull request. The latest released version of Partek flow when this was written was: <IP_ADDRESS>9.278-1 and serves as a start point for reference. It is possible that this module will work with prior partekflow versions; however, that condition has not been tested.
While the module maintainer supports the puppet code contained in the module, support for the application or performance of the Partek Flow software should be directed toward Partek. The module maintainer does not have a relationship with Partek.
Development
Please see the CONTRIBUTING document for information on how to get started developing code and submit a pull request for this module. While written in an opinionated fashion at the start, over time this can become less and less the case.
Contributors
To see who is involved with this module, see the GitHub list of contributors or the CONTRIBUTORS document.


choose any one of the three and you will win or lose respectively by the choice given by the computer


--- title: An Ajax-Include Pattern for Modular Content excerpt: 'An Ajax-Include Pattern for Modular Content, to conditionally load nice-to-have content, by @scottjehl/@filamentgroup: http://t.co/YVIyC1bP' date: '2012-04-03 00:19:19 +0200' date_gmt: '2012-04-02 22:19:19 +0200' categories: - Webdev tags: - tweets - web - design - development ---
An Ajax-Include Pattern for Modular Content, to conditionally load nice-to-have content, by @scottjehl/@filamentgroup: http://t.co/YVIyC1bP


--- layout: post status: publish published: true title: I am a DevArchitect author: display_name: Tomas Restrepo login: tomasr email<EMAIL_ADDRESS>url: http://winterdom.com/ author_login: tomasr author_email<EMAIL_ADDRESS>author_url: http://winterdom.com/ wordpress_id: 256 wordpress_url: http://winterdom.com/2005/10/iamadevarchitect date: '2005-10-20 15:55:17 +0000' date_gmt: '2005-10-20 15:55:17 +0000' categories: - Development tags: [] comments: [] ---
Bill Gibson nails it. That's what I do. I am a devarchitect.


---
layout: post
title: surprised pigeon photooftheday nofilter nepal
date: '2015-07-05T21:27:57+02:00'
tags:
- Instagram
- PhotoOfTheDay
tumblr_url: http://deepredsky.tumblr.com/post/123286630214/surprised-pigeon-photooftheday-nofilter-nepal
---
surprised pigeon #photooftheday #nofilter #nepal


{% extends 'layout.html' %} {% block pageTitle %} Find support - results {% endblock %} {% block beforeContent %} {{ breadcrumb({ items: [ { href: "/landing-page", text: "Home" }, { href: "/mental-health-check-in/questions-1", text: "Questions: about you" } ], href: "/mental-health-check-in/questions-2", text: "Questions: your feelings" }) }} {% endblock %} {% block content %}
Based on what you've told us, we think these are the best ways to get help with what you're feeling right now. You don't need anyone else to refer you to be able to use any of them.


Welcome to the Dublin bus route checkup! Enter your bus stop number to see the next bus available. The number is normally four digits long.


Unicode library for C++ by Ross Smith
#include "unicorn/utf.hpp"
This module defines classes and functions for encoding, decoding, and
converting between the standard Unicode transformation formats: UTF-8, UTF-16,
and UTF-32. Encoded strings are stored in any of the standard C++ string
classes, with the encoding defined by the size of the code units: string
(or
Ustring
) holds UTF-8, u16string
holds UTF-16, and u32string
holds
UTF-32; wstring
may hold either UTF-16 or UTF-32, depending on the compiler.
| Flag | Description |
|---|---|
Utf:: ignore |
Assume valid UTF input |
Utf:: replace |
Replace invalid UTF with U+FFFD |
Utf:: throws |
Throw EncodingError on invalid UTF |
These bitmask flags are used in most encoding conversion functions, and some related functions, to indicate how to handle encoding errors in the input data.
The ignore
option is the default for the UTF conversion functions. This
tells the function to assume that the input is already known to be a valid UTF
encoding. If this is not true, behaviour is unspecified (but not undefined);
basically, the output will be garbage. The UTF conversion code is optimized
for this case.
The replace
option causes invalid input encoding to be replaced with the
standard Unicode replacement character (U+FFFD
). Error handling for invalid
UTF-8 subsequences follows the Unicode recommended behaviour (Unicode Standard
7.0, section 3.9, page 128).
The throws
option causes any input encoding error to throw an
EncodingError
exception.
Behaviour is unspecified if more than one of these flags is combined.
If ignoring errors sounds like an unsafe choice for the default action,
remember that the Unicorn library is designed with the intention that text
manipulation within a program will be done entirely in Unicode; text is
normally converted back and forth to other encodings, and checked for
validity, only at the point of input and output. Unlike the UTF conversion
functions in this module, the functions in unicorn/mbcs
that
convert between Unicode and other encodings default to Utf::replace
, and do
not accept the Utf::ignore
option.
class
EncodingError
: public std::runtime_error
EncodingError::
EncodingError
()
explicit EncodingError::
EncodingError
(const Ustring& encoding, size_t offset = 0, char32_t c = 0)
template <typename C> EncodingError::
EncodingError
(const Ustring& encoding, size_t offset, const C* ptr, size_t n = 1)
const char* EncodingError::
encoding
() noexcept const
size_t EncodingError::
offset
() const noexcept
An exception thrown to indicate a text encoding error encountered when
converting a string from one encoding to another, or when checking an encoded
string for validity. The offset of the offending data within the source string
(when available) can be retrieved through the offset()
method. If possible,
a hexadecimal representation of the offending data will be included in the
error message.
size_t
char_from_utf8
(const char* src, size_t n, char32_t& dst) noexcept
size_t
char_from_utf16
(const char16_t* src, size_t n, char32_t& dst) noexcept
size_t
char_to_utf8
(char32_t src, char* dst) noexcept
size_t
char_to_utf16
(char32_t src, char16_t* dst) noexcept
Read one character from src
(reading up to n
code units for the decoding
functions), and write the decoded or encoded form into dst
, returning the
number of code units read or written. If src
does not contain a valid
character, zero is returned and dst
is left unchanged. Behaviour is
undefined if a pointer argument is null.
template <typename C> size_t
code_units
(char32_t c)
Returns the number of code units in the encoding of the character c
, in the
UTF encoding implied by the character type C
, or zero if c
is not a valid
Unicode character.
template <typename C> bool
is_single_unit
(C c)
-- This code unit represents a character by itselftemplate <typename C> bool
is_start_unit
(C c)
-- This is the first code unit of a multi-unit charactertemplate <typename C> bool
is_nonstart_unit
(C c)
-- This is the second or subsequent code unit of a multi-unit charactertemplate <typename C> bool
is_invalid_unit
(C c)
-- This value is not a legal code unittemplate <typename C> bool
is_initial_unit
(C c)
-- Either a single unit or a start unitThese give the properties of individual code units. Exactly one of the first four functions will be true for any value of the argument.
template <typename C> class
UtfIterator
using UtfIterator::
code_unit
= C
using UtfIterator::
string_type
= basic_string<C>
using UtfIterator::
difference_type
= ptrdiff_t
using UtfIterator::
iterator_category
= std::bidirectional_iterator_tag
using UtfIterator::
pointer
= const char32_t*
using UtfIterator::
reference
= const char32_t&
using UtfIterator::
value_type
= char32_t
UtfIterator::
UtfIterator
() noexcept
explicit UtfIterator::
UtfIterator
(const string_type& src)
UtfIterator::
UtfIterator
(const string_type& src, size_t offset, uint32_t flags = 0)
size_t UtfIterator::
count
() const noexcept
size_t UtfIterator::
offset
() const noexcept
UtfIterator UtfIterator::
offset_by
(ptrdiff_t n) const noexcept
const C* UtfIterator::
ptr
() const noexcept
const string_type& UtfIterator::
source
() const noexcept
string_type
str
() const
bool UtfIterator::
valid
() const noexcept
std::basic_string_view<C> UtfIterator::
view
() const noexcept
This is a bidirectional iterator over any UTF-encoded text. The template
argument type (C
) is the code unit type of the underlying encoded string,
the encoding form is determined by the size of the code unit. The iterator
dereferences to a Unicode character; incrementing or decrementing the iterator
moves it to the next or previous encoded character. The iterator holds a
reference to the underlying string; UTF iterators are invalidated by any of
the same operations on the underlying string that would invalidate an ordinary
string iterator.
The constructor can optionally take an offset into the subject string; if the offset points to the beginning of an encoded character, the iterator will start at that character. If the offset does not point to a character boundary, it will be treated as an invalid character; such an iterator can be incremented to the next character boundary in the normal way, but decrementing past that point has unspecified behaviour.
The flags
argument determines the behaviour when invalid encoded data is
found, as described above. If an EncodingError
exception is caught and
handled, the iterator is still in a valid state, and can be dereferenced
(yielding U+FFFD
), incremented, or decremented in the normal way.
When invalid UTF-8 data is replaced, the substitution rules recommended in the Unicode Standard (section 3.9, table 3-8) are followed. Replacements in UTF-16 or 32 are always one-for-one.
Besides the normal operations that can be applied to an iterator,
UtfIterator
has some extra member functions that can be used to query its
state. The source()
function returns a reference to the underlying encoded
string. The offset()
and count()
functions return the position and length
(in code units) of the current encoded character (or the group of code units
currently being interpreted as an invalid character). The view()
function
returns the same sequence of code units as a string view.
The offset_by()
function returns an iterator moved by the specified number
of code units. The resulting offset will be clamped to the bounds of the
source string; behaviour is the same as for the constructor if it is not on a
character boundary.
The ptr()
function returns a pointer to the start of the encoded character,
a pointer to the end of the underlying string if the iterator is past the end,
or a null pointer if the iterator was default constructed.
The str()
function returns a copy of the code units making up the current
character. This will be empty if the iterator is default constructed or past
the end, but behaviour is undefined if this is called on any other kind of
invalid iterator.
The valid()
function indicates whether the current character is valid; it
will always be true if Utf::ignore
was set, and its value is unspecified on
a past-the-end iterator.
If the underlying string is UTF-32, this is just a simple pass-through iterator, but if one of the non-default error handling options is selected, it will check for valid Unicode characters and treat invalid code points as errors.
using
Utf8Iterator
= UtfIterator<char>
using
Utf16Iterator
= UtfIterator<char16_t>
using
Utf32Iterator
= UtfIterator<char32_t>
using
WcharIterator
= UtfIterator<wchar_t>
using
Utf8Range
= Irange<Utf8Iterator>
using
Utf16Range
= Irange<Utf16Iterator>
using
Utf32Range
= Irange<Utf32Iterator>
using
WcharRange
= Irange<WcharIterator>
Convenience aliases for specific iterators and ranges.
template <typename C> UtfIterator<C>
utf_begin
(const basic_string<C>& src, uint32_t flags = 0)
template <typename C> UtfIterator<C>
utf_end
(const basic_string<C>& src, uint32_t flags = 0)
template <typename C> Irange<UtfIterator<C>>
utf_range
(const basic_string<C>& src, uint32_t flags = 0)
These return iterators over an encoded string.
template <typename C> UtfIterator<C>
utf_iterator
(const basic_string<C>& src, size_t offset, uint32_t flags = 0)
Returns an iterator pointing to a specific offset in a string.
template <typename C> basic_string<C>
u_str
(const UtfIterator<C>& i, const UtfIterator<C>& j)
template <typename C> basic_string<C>
u_str
(const Irange<UtfIterator<C>>& range)
These return a copy of the substring between two iterators.
template <typename C> class
UtfWriter
using UtfWriter::
code_unit
= C
using UtfWriter::
string_type
= basic_string<C>
using UtfWriter::
difference_type
= void
using UtfWriter::
iterator_category
= std::output_iterator_tag
using UtfWriter::
pointer
= void
using UtfWriter::
reference
= void
using UtfWriter::
value_type
= char32_t
UtfWriter::
UtfWriter
() noexcept
explicit UtfWriter::
UtfWriter
(string_type& dst) noexcept
UtfWriter::
UtfWriter
(string_type& dst, uint32_t fags) flagst
bool UtfWriter::
valid
() const noexcept
This is an output iterator that writes encoded characters onto the end of a
string. As with UtfIterator
, the encoding form is determined by the size of
the code unit type (C
), and behaviour is undefined if the destination string
is destroyed while the iterator exists. Changing the destination string
through other means is allowed, however; the UtfWriter
will continue to
write to the end of the modified string.
If an exception is thrown, nothing will be written to the output string.
Otherwise, the flags
argument and the valid()
function work in much the
same way as for UtfIterator
.
using
Utf8Writer
= UtfWriter<char>
using
Utf16Writer
= UtfWriter<char16_t>
using
Utf32Writer
= UtfWriter<char32_t>
using
WcharWriter
= UtfWriter<wchar_t>
Convenience aliases for specific iterators.
template <typename C> UtfWriter<C>
utf_writer
(basic_string<C>& dst, uint32_t flags = 0) noexcept
Returns an encoding iterator writing to the given destination string.
template <typename C1, typename C2> void
recode
(const basic_string<C1>& src, basic_string<C2>& dst, uint32_t flags = 0)
template <typename C1, typename C2> void
recode
(const basic_string<C1>& src, size_t offset, basic_string<C2>& dst, uint32_t flags = 0)
template <typename C1, typename C2> void
recode
(const C1* src, size_t count, basic_string<C2>& dst, uint32_t flags = 0)
template <typename C2, typename C1> basic_string<C2>
recode
(const basic_string<C1>& src, uint32_t flags = 0)
template <typename C2, typename C1> basic_string<C2>
recode
(const basic_string<C1>& src, size_t offset, uint32_t flags)
Encoding conversion functions. These convert from one UTF encoding to another;
as usual, the encoding forms are determined by the size of the input (C1
)
and output (C2
) code units. The input string can be supplied as a string
object (with an optional starting offset), or a code unit pointer and length
(a null pointer is treated as an empty string).
The last two versions return the converted string instead of writing it to a destination string passed by reference; in this case the output code unit type must be supplied explicitly as a template argument.
The flags
argument has its usual meaning. If the Utf::ignore
flag is used,
and the source and destination code units are the same size, the string will
simply be copied unchanged. If the Utf::throws
flag is used, and the
destination string was supplied by reference, after an exception is thrown the
destination string will contain the successfully converted part of the string
before the error.
template <typename C> Ustring
to_utf8
(const basic_string<C>& src, uint32_t flags = 0)
template <typename C> u16string
to_utf16
(const basic_string<C>& src, uint32_t flags = 0)
template <typename C> u32string
to_utf32
(const basic_string<C>& src, uint32_t flags = 0)
template <typename C> wstring
to_wstring
(const basic_string<C>& src, uint32_t flags = 0)
template <typename C> NativeString
to_native
(const basic_string<C>& src, uint32_t flags = 0)
These are just shorthand for the corresponding invocation of recode()
.
template <typename C> void
check_string
(const basic_string<C>& str)
template <typename C> bool
valid_string
(const basic_string<C>& str) noexcept
These check for valid encoding. If the string contains invalid UTF,
valid_string()
returns false
, while check_string()
throws
EncodingError
.
template <typename C> basic_string<C>
sanitize
(const basic_string<C>& str)
template <typename C> void
sanitize_in
(basic_string<C>& str)
Ensure that the string is a valid UTF encoding, by replacing any invalid data
with the U+FFFD
replacement character.
template <typename C> size_t
valid_count
(const basic_string<C>& str) noexcept
Finds the position of the first invalid UTF encoding in a string. The return
value is the offset (in code units) to the first invalid code unit, or npos
if no invalid encoding is found.


# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Utilities for console input and output.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import codecs
import locale
import re
import math
import multiprocessing
import os
import sys
import threading
import time
try:
import fcntl
import termios
import signal
_CAN_RESIZE_TERMINAL = True
except ImportError:
_CAN_RESIZE_TERMINAL = False
try:
get_ipython()
except NameError:
OutStream = None
IPythonIOStream = None
stdio = sys
else:
try:
from IPython.zmq.iostream import OutStream
from IPython.utils import io
# On Windows in particular this is necessary, as the io.stdout stream
# in IPython gets hooked up to some pyreadline magic to handle colors
stdio = io
IPythonIOStream = io.IOStream
except ImportError:
OutStream = None
IPythonIOStream = None
stdio = sys
try:
import IPython # pylint: disable=W0611
# This is just to set a flag that IPython is installed at all
_HAVE_IPYTHON = True
except ImportError:
_HAVE_IPYTHON = False
from ..config import ConfigurationItem
from ..extern import six
from ..extern.six.moves import range
from .misc import deprecated, isiterable
__all__ = [
'isatty', 'color_print', 'human_time', 'human_file_size',
'ProgressBar', 'Spinner', 'print_code_line', 'ProgressBarOrSpinner']
# Only use color by default on Windows if IPython is installed.
USE_COLOR = ConfigurationItem(
'use_color', sys.platform != 'win32' or _HAVE_IPYTHON,
'When True, use ANSI color escape sequences when writing to the console.')
from ..import UNICODE_OUTPUT
IS_PY3 = sys.version_info[0] == 3
_DEFAULT_ENCODING = 'utf-8'
[docs]def isatty(file):
"""
Returns `True` if `file` is a tty.
Most built-in Python file-like objects have an `isatty` member,
but some user-defined types may not, so this assumes those are not
ttys.
"""
if (multiprocessing.current_process().name != 'MainProcess' or
threading.current_thread().getName() != 'MainThread'):
return False
if (OutStream is not None and
isinstance(file, OutStream) and
file.name == 'stdout'):
return True
elif hasattr(file, 'isatty'):
return file.isatty()
return False
def _color_text(text, color):
"""
Returns a string wrapped in ANSI color codes for coloring the
text in a terminal::
colored_text = color_text('Here is a message', 'blue')
This won't actually effect the text until it is printed to the
terminal.
Parameters
----------
text : str
The string to return, bounded by the color codes.
color : str
An ANSI terminal color name. Must be one of:
black, red, green, brown, blue, magenta, cyan, lightgrey,
default, darkgrey, lightred, lightgreen, yellow, lightblue,
lightmagenta, lightcyan, white, or '' (the empty string).
"""
color_mapping = {
'black': '0;30',
'red': '0;31',
'green': '0;32',
'brown': '0;33',
'blue': '0;34',
'magenta': '0;35',
'cyan': '0;36',
'lightgrey': '0;37',
'default': '0;39',
'darkgrey': '1;30',
'lightred': '1;31',
'lightgreen': '1;32',
'yellow': '1;33',
'lightblue': '1;34',
'lightmagenta': '1;35',
'lightcyan': '1;36',
'white': '1;37'}
if sys.platform == 'win32' and OutStream is None:
# On Windows do not colorize text unless in IPython
return text
color_code = color_mapping.get(color, '0;39')
return '\033[{0}m{1}\033[0m'.format(color_code, text)
def _decode_preferred_encoding(s):
"""Decode the supplied byte string using the preferred encoding
for the locale (`locale.getpreferredencoding`) or, if the default encoding
is invalid, fall back first on utf-8, then on latin-1 if the message cannot
be decoded with utf-8.
"""
enc = locale.getpreferredencoding()
try:
try:
return s.decode(enc)
except LookupError:
enc = _DEFAULT_ENCODING
return s.decode(enc)
except UnicodeDecodeError:
return s.decode('latin-1')
def _write_with_fallback(s, write, fileobj):
"""Write the supplied string with the given write function like
``write(s)``, but use a writer for the locale's preferred encoding in case
of a UnicodeEncodeError. Failing that attempt to write with 'utf-8' or
'latin-1'.
"""
if IPythonIOStream is not None and isinstance(fileobj, IPythonIOStream):
# If the output stream is an IPython.utils.io.IOStream object that's
# not going to be very helpful to us since it doesn't raise any
# exceptions when an error occurs writing to its underlying stream.
# There's no advantage to us using IOStream.write directly though;
# instead just write directly to its underlying stream:
write = fileobj.stream.write
try:
write(s)
return write
except UnicodeEncodeError:
# Let's try the next approach...
pass
enc = locale.getpreferredencoding()
try:
Writer = codecs.getwriter(enc)
except LookupError:
Writer = codecs.getwriter(_DEFAULT_ENCODING)
f = Writer(fileobj)
write = f.write
try:
write(s)
return write
except UnicodeEncodeError:
Writer = codecs.getwriter('latin-1')
f = Writer(fileobj)
write = f.write
# If this doesn't work let the exception bubble up; I'm out of ideas
write(s)
return write
[docs]def color_print(*args, **kwargs):
"""
Prints colors and styles to the terminal uses ANSI escape
sequences.
::
color_print('This is the color ', 'default', 'GREEN', 'green')
Parameters
----------
positional args : str
The positional arguments come in pairs (*msg*, *color*), where
*msg* is the string to display and *color* is the color to
display it in.
*color* is an ANSI terminal color name. Must be one of:
black, red, green, brown, blue, magenta, cyan, lightgrey,
default, darkgrey, lightred, lightgreen, yellow, lightblue,
lightmagenta, lightcyan, white, or '' (the empty string).
file : writeable file-like object, optional
Where to write to. Defaults to `sys.stdout`. If file is not
a tty (as determined by calling its `isatty` member, if one
exists), no coloring will be included.
end : str, optional
The ending of the message. Defaults to ``\\n``. The end will
be printed after resetting any color or font state.
"""
file = kwargs.get('file', stdio.stdout)
end = kwargs.get('end', '\n')
write = file.write
if isatty(file) and USE_COLOR():
for i in range(0, len(args), 2):
msg = args[i]
if i + 1 == len(args):
color = ''
else:
color = args[i + 1]
if color:
msg = _color_text(msg, color)
# Some file objects support writing unicode sensibly on some Python
# versions; if this fails try creating a writer using the locale's
# preferred encoding. If that fails too give up.
if not IS_PY3 and isinstance(msg, bytes):
msg = _decode_preferred_encoding(msg)
write = _write_with_fallback(msg, write, file)
write(end)
else:
for i in range(0, len(args), 2):
msg = args[i]
if not IS_PY3 and isinstance(msg, bytes):
# Support decoding bytes to unicode on Python 2; use the
# preferred encoding for the locale (which is *sometimes*
# sensible)
msg = _decode_preferred_encoding(msg)
write(msg)
write(end)
def strip_ansi_codes(s):
"""
Remove ANSI color codes from the string.
"""
return re.sub('\033\[([0-9]+)(;[0-9]+)*m', '', s)
[docs]def human_time(seconds):
"""
Returns a human-friendly time string that is always exactly 6
characters long.
Depending on the number of seconds given, can be one of::
1w 3d
2d 4h
1h 5m
1m 4s
15s
Will be in color if console coloring is turned on.
Parameters
----------
seconds : int
The number of seconds to represent
Returns
-------
time : str
A human-friendly representation of the given number of seconds
that is always exactly 6 characters.
"""
units = [
('y', 60 * 60 * 24 * 7 * 52),
('w', 60 * 60 * 24 * 7),
('d', 60 * 60 * 24),
('h', 60 * 60),
('m', 60),
('s', 1),
]
seconds = int(seconds)
if seconds < 60:
return ' {0:02d}s'.format(seconds)
for i in xrange(len(units) - 1):
unit1, limit1 = units[i]
unit2, limit2 = units[i + 1]
if seconds >= limit1:
return '{0:02d}{1}{2:02d}{3}'.format(
seconds // limit1, unit1,
(seconds % limit1) // limit2, unit2)
return ' ~inf'
[docs]def human_file_size(size):
"""
Returns a human-friendly string representing a file size
that is 2-4 characters long.
For example, depending on the number of bytes given, can be one
of::
256b
64k
1.1G
Parameters
----------
size : int
The size of the file (in bytes)
Returns
-------
size : str
A human-friendly representation of the size of the file
"""
suffixes = ' kMGTPEH'
if size == 0:
num_scale = 0
else:
num_scale = int(math.floor(math.log(size) / math.log(1000)))
if num_scale > 7:
suffix = '?'
else:
suffix = suffixes[num_scale]
num_scale = int(math.pow(1000, num_scale))
value = size / num_scale
str_value = str(value)
if str_value[2] == '.':
str_value = str_value[:2]
else:
str_value = str_value[:3]
return "{0:>3s}{1}".format(str_value, suffix)
[docs]class ProgressBar(six.Iterator):
"""
A class to display a progress bar in the terminal.
It is designed to be used either with the `with` statement::
with ProgressBar(len(items)) as bar:
for item in enumerate(items):
bar.update()
or as a generator::
for item in ProgressBar(items):
item.process()
"""
def __init__(self, total_or_items, file=None):
"""
Parameters
----------
total_or_items : int or sequence
If an int, the number of increments in the process being
tracked. If a sequence, the items to iterate over.
file : writable file-like object, optional
The file to write the progress bar to. Defaults to
`sys.stdout`. If `file` is not a tty (as determined by
calling its `isatty` member, if any), the scrollbar will
be completely silent.
"""
if file is None:
file = stdio.stdout
if not isatty(file):
self.update = self._silent_update
self._silent = True
else:
self._silent = False
if isiterable(total_or_items):
self._items = iter(total_or_items)
self._total = len(total_or_items)
else:
try:
self._total = int(total_or_items)
except TypeError:
raise TypeError("First argument must be int or sequence")
else:
self._items = iter(range(self._total))
self._file = file
self._start_time = time.time()
self._should_handle_resize = (
_CAN_RESIZE_TERMINAL and isatty(self._file))
self._handle_resize()
if self._should_handle_resize:
signal.signal(signal.SIGWINCH, self._handle_resize)
self._signal_set = True
else:
self._signal_set = False
self._human_total = human_file_size(self._total)
self.update(0)
def _handle_resize(self, signum=None, frame=None):
if self._should_handle_resize:
# Don't import numpy at module level since it may not be
# available in all contexts that this module is imported
import numpy as np
data = fcntl.ioctl(self._file, termios.TIOCGWINSZ, '\0' * 8)
arr = np.fromstring(data, dtype=np.int16)
terminal_width = arr[1]
else:
try:
terminal_width = int(os.environ.get('COLUMNS'))
except (TypeError, ValueError):
terminal_width = 78
self._bar_length = terminal_width - 37
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if not self._silent:
if exc_type is None:
self.update(self._total)
self._file.write('\n')
self._file.flush()
if self._signal_set:
signal.signal(signal.SIGWINCH, signal.SIG_DFL)
def __iter__(self):
return self
def __next__(self):
try:
rv = next(self._items)
except StopIteration:
self.__exit__(None, None, None)
raise
else:
self.update()
return rv
[docs] def update(self, value=None):
"""
Update the progress bar to the given value (out of the total
given to the constructor).
"""
if value is None:
value = self._current_value = self._current_value + 1
else:
self._current_value = value
if self._total == 0:
frac = 1.0
else:
frac = float(value) / float(self._total)
file = self._file
write = file.write
bar_fill = int(float(self._bar_length) * frac)
write('\r|')
color_print('=' * bar_fill, 'blue', file=file, end='')
if bar_fill < self._bar_length:
color_print('>', 'green', file=file, end='')
write('-' * (self._bar_length - bar_fill - 1))
write('|')
if value >= self._total:
t = time.time() - self._start_time
prefix = ' '
elif value <= 0:
t = None
prefix = ''
else:
t = ((time.time() - self._start_time) * (1.0 - frac)) / frac
prefix = ' ETA '
write(' {0:>4s}/{1:>4s}'.format(
human_file_size(value),
self._human_total))
write(' ({0:>6s}%)'.format('{0:.2f}'.format(frac * 100.0)))
write(prefix)
if t is not None:
write(human_time(t))
self._file.flush()
def _silent_update(self, value=None):
pass
@classmethod
[docs] def map(cls, function, items, multiprocess=False, file=None):
"""
Does a `map` operation while displaying a progress bar with
percentage complete.
::
def work(i):
print(i)
ProgressBar.map(work, range(50))
Parameters
----------
function : function
Function to call for each step
items : sequence
Sequence where each element is a tuple of arguments to pass to
*function*.
multiprocess : bool, optional
If `True`, use the `multiprocessing` module to distribute each
task to a different processor core.
file : writeable file-like object, optional
The file to write the progress bar to. Defaults to
`sys.stdout`. If `file` is not a tty (as determined by
calling its `isatty` member, if any), the scrollbar will
be completely silent.
"""
results = []
if file is None:
file = stdio.stdout
with cls(len(items), file=file) as bar:
step_size = max(200, bar._bar_length)
steps = max(int(float(len(items)) / step_size), 1)
if not multiprocess:
for i, item in enumerate(items):
results.append(function(item))
if (i % steps) == 0:
bar.update(i)
else:
p = multiprocessing.Pool()
for i, result in enumerate(
p.imap_unordered(function, items, steps)):
bar.update(i)
results.append(result)
p.close()
p.join()
return results
@deprecated('0.3', alternative='ProgressBar')
@classmethod
[docs] def iterate(cls, items, file=None):
"""
Iterate over a sequence while indicating progress with a progress
bar in the terminal.
::
for item in ProgressBar.iterate(items):
pass
Parameters
----------
items : sequence
A sequence of items to iterate over
file : writeable file-like object, optional
The file to write the progress bar to. Defaults to
`sys.stdout`. If `file` is not a tty (as determined by
calling its `isatty` member, if any), the scrollbar will
be completely silent.
Returns
-------
generator :
A generator over `items`
"""
if file is None:
file = stdio.stdout
return cls(items, file=file)
[docs]class Spinner(object):
"""
A class to display a spinner in the terminal.
It is designed to be used with the `with` statement::
with Spinner("Reticulating splines", "green") as s:
for item in enumerate(items):
s.next()
"""
_default_unicode_chars = "◓◑◒◐"
_default_ascii_chars = "-/|\\"
def __init__(self, msg, color='default', file=None, step=1,
chars=None):
"""
Parameters
----------
msg : str
The message to print
color : str, optional
An ANSI terminal color name. Must be one of: black, red,
green, brown, blue, magenta, cyan, lightgrey, default,
darkgrey, lightred, lightgreen, yellow, lightblue,
lightmagenta, lightcyan, white.
file : writeable file-like object, optional
The file to write the spinner to. Defaults to
`sys.stdout`. If `file` is not a tty (as determined by
calling its `isatty` member, if any), the scrollbar will
be completely silent.
step : int, optional
Only update the spinner every *step* steps
chars : str, optional
The character sequence to use for the spinner
"""
if file is None:
file = stdio.stdout
self._msg = msg
self._color = color
self._file = file
self._step = step
if chars is None:
if UNICODE_OUTPUT():
chars = self._default_unicode_chars
else:
chars = self._default_ascii_chars
self._chars = chars
self._silent = not isatty(file)
def _iterator(self):
chars = self._chars
index = 0
file = self._file
write = file.write
flush = file.flush
try_fallback = True
while True:
write('\r')
color_print(self._msg, self._color, file=file, end='')
write(' ')
try:
if try_fallback:
write = _write_with_fallback(chars[index], write, file)
else:
write(chars[index])
except UnicodeError:
# If even _write_with_fallback failed for any reason just give
# up on trying to use the unicode characters
chars = self._default_ascii_chars
write(chars[index])
try_fallback = False # No good will come of using this again
flush()
yield
for i in range(self._step):
yield
index = (index + 1) % len(chars)
def __enter__(self):
if self._silent:
return self._silent_iterator()
else:
return self._iterator()
def __exit__(self, exc_type, exc_value, traceback):
file = self._file
write = file.write
flush = file.flush
if not self._silent:
write('\r')
color_print(self._msg, self._color, file=file, end='')
if exc_type is None:
color_print(' [Done]', 'green', file=file)
else:
color_print(' [Failed]', 'red', file=file)
flush()
def _silent_iterator(self):
color_print(self._msg, self._color, file=self._file, end='')
self._file.flush()
while True:
yield
[docs]class ProgressBarOrSpinner(object):
"""
A class that displays either a `ProgressBar` or `Spinner`
depending on whether the total size of the operation is
known or not.
It is designed to be used with the `with` statement::
if file.has_length():
length = file.get_length()
else:
length = None
bytes_read = 0
with ProgressBarOrSpinner(length) as bar:
while file.read(blocksize):
bytes_read += blocksize
bar.update(bytes_read)
"""
def __init__(self, total, msg, color='default', file=None):
"""
Parameters
----------
total : int or None
If an int, the number of increments in the process being
tracked and a `ProgressBar` is displayed. If `None`, a
`Spinner` is displayed.
msg : str
The message to display above the `ProgressBar` or
alongside the `Spinner`.
color : str, optional
The color of `msg`, if any. Must be an ANSI terminal
color name. Must be one of: black, red, green, brown,
blue, magenta, cyan, lightgrey, default, darkgrey,
lightred, lightgreen, yellow, lightblue, lightmagenta,
lightcyan, white.
file : writable file-like object, optional
The file to write the to. Defaults to `sys.stdout`. If
`file` is not a tty (as determined by calling its `isatty`
member, if any), only `msg` will be displayed: the
`ProgressBar` or `Spinner` will be silent.
"""
if file is None:
file = stdio.stdout
if total is None or not isatty(file):
self._is_spinner = True
self._obj = Spinner(msg, color=color, file=file)
else:
self._is_spinner = False
color_print(msg, color, file=file)
self._obj = ProgressBar(total, file=file)
def __enter__(self):
self._iter = self._obj.__enter__()
return self
def __exit__(self, exc_type, exc_value, traceback):
return self._obj.__exit__(exc_type, exc_value, traceback)
[docs] def update(self, value):
"""
Update the progress bar to the given value (out of the total
given to the constructor.
"""
if self._is_spinner:
next(self._iter)
else:
self._obj.update(value)
[docs]def print_code_line(line, col=None, file=None, tabwidth=8, width=70):
"""
Prints a line of source code, highlighting a particular character
position in the line. Useful for displaying the context of error
messages.
If the line is more than `width` characters, the line is truncated
accordingly and '…' characters are inserted at the front and/or
end.
It looks like this::
there_is_a_syntax_error_here :
^
Parameters
----------
line : unicode
The line of code to display
col : int, optional
The character in the line to highlight. `col` must be less
than `len(line)`.
file : writeable file-like object, optional
Where to write to. Defaults to `sys.stdout`.
tabwidth : int, optional
The number of spaces per tab (``'\\t'``) character. Default
is 8. All tabs will be converted to spaces to ensure that the
caret lines up with the correct column.
width : int, optional
The width of the display, beyond which the line will be
truncated. Defaults to 70 (this matches the default in the
standard library's `textwrap` module).
"""
if file is None:
file = stdio.stdout
if UNICODE_OUTPUT():
ellipsis = '…'
else:
ellipsis = '...'
write = file.write
if col is not None:
assert col < len(line)
ntabs = line[:col].count('\t')
col += ntabs * (tabwidth - 1)
line = line.rstrip('\n')
line = line.replace('\t', ' ' * tabwidth)
if col is not None and col > width:
new_col = min(width // 2, len(line) - col)
offset = col - new_col
line = line[offset + len(ellipsis):]
width -= len(ellipsis)
new_col = col
col -= offset
color_print(ellipsis, 'darkgrey', file=file, end='')
if len(line) > width:
write(line[:width - len(ellipsis)])
color_print(ellipsis, 'darkgrey', file=file)
else:
write(line)
write('\n')
if col is not None:
write(' ' * col)
color_print('^', 'red', file=file)
# The following four Getch* classes implement unbuffered character reading from
# stdin on Windows, linux, MacOSX. This is taken directly from ActiveState
# Code Recipes:
# http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/
#
class Getch(object):
"""Get a single character from standard input without screen echo.
Returns
-------
char : str (one character)
"""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
try:
self.impl = _GetchMacCarbon()
except (ImportError, AttributeError):
self.impl = _GetchUnix()
def __call__(self):
return self.impl()
class _GetchUnix(object):
def __init__(self):
import tty
import sys
import termios # import termios now or else you'll get the Unix
# version on the Mac
def __call__(self):
import sys
import tty
import termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows(object):
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
class _GetchMacCarbon(object):
"""
A function which returns the current ASCII key that is down;
if no ASCII key is down, the null string is returned. The
page http://www.mactech.com/macintosh-c/chap02-1.html was
very helpful in figuring out how to do this.
"""
def __init__(self):
import Carbon
Carbon.Evt # see if it has this (in Unix, it doesn't)
def __call__(self):
import Carbon
if Carbon.Evt.EventAvail(0x0008)[0] == 0: # 0x0008 is the keyDownMask
return ''
else:
#
# The event contains the following info:
# (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
#
# The message (msg) contains the ASCII char which is
# extracted with the 0x000000FF charCodeMask; this
# number is converted to an ASCII character with chr() and
# returned
#
(what, msg, when, where, mod) = Carbon.Evt.GetNextEvent(0x0008)[1]
return chr(msg & 0x000000FF)


Obtains network information about a specific host and stores the information in Ant properties. The following properties will be set when this Ant task is invoked:
host.name
host.address
| Attribute | Description | Required |
| host | Set the hostname used when obtaining network information. If no hostname is specified, the localhost information will be obtained. | No |
| echo | Print the host information to stdout | No |
Obtain the hostname and store the value in Ant properties:
<hostname/> <echo message="Hostname: ${host.name}"/> <echo message="IP Address: ${host.address}"/>


--- layout: post title: How to get Devise, Figaro, Heroku and emailing to Play Together Nicely date: 2013-07-11 15:15:09.000000000 -04:00 type: post published: true status: publish categories: - Rails tags: [] meta: _edit_last: '2' bwps_enable_ssl: '' _wp_old_slug: how-to-get-devise-figaro-heroku-and-sendgrid-to-work-together Layout: 1c _css_code: "div#social a img {\r\n padding: 0px ;\r\n margin: 10px 3px 0 0;\r\n}" author: login<EMAIL_ADDRESS>email<EMAIL_ADDRESS>display_name: Aimee Knight first_name: Aimee last_name: Knight ---
I recently made the switch over to SparkPost, which is one of Heroku’s newest add-ons (I also work there)! There is a free basic plan that includes up to 10K of emails a month. SparkPost has the highest inbox placement of any provider, and real-time analytics with over 40 different metrics. It's also built by Message Systems, which is the email provider for large scale companies like Facebook, Twitter, and Pinterest, so that made migration an easy choice! The move was straight forward, quick, and easy!
Once you have a card on file, just run
heroku addons:create sparkpost:free
to add SparkPost to your app.
I'm going to write this from the standpoint of where I was last week so here's some background. I, like many other newbies was happily going along completing various Rails Tutorials not aware that my "secret token" was being committed to my public GitHub repo for the world to see. For random tutorials this isn't really a problem, but when it's time to start an actual app you plan to deploy, then this is going to be necessary. The solution... environment variables. There are a ton of ways to go about hiding your apps token (and other confidential info like emails and passwords), but I opted for Figaro.
Configuration is pretty straight forward. Add Figaro to your Gemfile and run
$ bundle install
followed by
$ rails generate figaro:install
Figaro's generate command will create an application.yml file for you and automatically add it to your .gitignore!
Now, add the variables you want hidden into config/application.yml.
It will look something like this if you use Gmail:
(No, that's not actually my token. You can generate them whenever needed by running $ rake secret
in terminal.)
Then just access your environment variables wherever they're needed within your app. In config/initializers/secret_token.rb it would look something like this.
< title="secret_token.rb">MyApp::Application.config.secret_token = ENV["SECRET_TOKEN"] {% endhighlight %}Next, run
$ rake figaro:heroku
to add your environment variables to Heroku. If you're like me and want to see proof, you can run
$ heroku config
just to make sure they're there.
Now for the emails. (It's worth mentioning, that I used my gmail account initially). Heroku recommends SendGrid, and I'm glad I went this route. The basic plan is free and comes with 6K emails monthly. You'll need a credit card on file with Heroku, but there are no charges if you remain in that range.
Once you have a card on file, run
heroku addons:add sendgrid:starter
to add SendGrid to your app.
To generate your apps email run
$ heroku config:get SENDGRID_USERNAME
,
followed by
$ heroku config:get SENDGRID_PASSWORD
to generate your password.
Ok, almost there. Now back to your app's directory. In config/initializers/devise.rb, find
config.mailer_sender
and set that to your SendGrid email environment variable (that was generated for you when running the commands above). It will look like this:
Next, in envrionments/production.rb you'll need to include the following for Devise.
{% highlight ruby %} config.action_mailer.default_url_options = { :host => 'whatever-heroku-gives-you.herokuapp.com'} config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: "smtp.sendgrid.net", port: 25, domain: "heroku.com", authentication: "plain", enable_starttls_auto: true, user_name: ENV["SENDGRID_USERNAME"], password: ENV["SENDGRID_PASSWORD"] } {% endhighlight %}Run through your deploy process and you will be good to go!


Current filename format: ${title}, ${firstAuthor} et al., ${publishedYear}.pdf
You'll need to re-open the tabs for the new format to take effect.


Definitions of classes, methods, operators and functions for use in photobiology and radiation meteorology and climatology. Calculation of effective (weighted) and not-weighted irradiances/doses, fluence rates, transmittance, reflectance, absorptance, absorbance and diverse ratios and other derived quantities from spectral data. Local maxima and minima. Conversion between energy- and photon-based units. Wavelength interpolation. Astronomical calculations related solar angles and day length. Colours and vision. This package is part of the 'r4photobiology' suite, Aphalo P. J. (2015) <doi:10.19232/uv4pb.2015.1.14>.
| Version: | 0.9.25 |
| Depends: | R (≥ 3.4.0) |
| Imports: | stats, polynom (≥ 1.3-9), tibble (≥ 1.4.2), lubridate (≥ 1.7.4), plyr (≥ 1.8.4), dplyr (≥ 0.7.6), splus2R (≥ 1.2-2), zoo (≥ 1.8-3), rlang (≥ 0.2.2) |
| Suggests: | knitr (≥ 1.20), rmarkdown (≥ 1.10), testthat (≥ 2.0.0), roxygen2 (≥ 6.1.0) |
| Published: | 2018-12-11 |
| Author: | Pedro J. Aphalo [aut, cre], Titta K. Kotilainen [ctb], Glenn Davis [ctb] |
| Maintainer: | Pedro J. Aphalo <pedro.aphalo at helsinki.fi> |
| BugReports: | https://bitbucket.org/aphalo/photobiology/issues |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| URL: | https://www.r4photobiology.info/, https://bitbucket.org/aphalo/photobiology |
| NeedsCompilation: | no |
| Citation: | photobiology citation info |
| Materials: | README NEWS |
| CRAN checks: | photobiology results |
| Reference manual: | photobiology.pdf |
| Vignettes: |
User Guide: 1 Introduction User Guide: 2 Radiation User Guide: 3 Astronomy |
| Package source: | photobiology_0.9.25.tar.gz |
| Windows binaries: | r-devel: photobiology_0.9.25.zip, r-release: photobiology_0.9.25.zip, r-oldrel: photobiology_0.9.25.zip |
| OS X binaries: | r-release: photobiology_0.9.25.tgz, r-oldrel: photobiology_0.9.25.tgz |
| Old sources: | photobiology archive |
| Reverse depends: | photobiologyFilters, photobiologyLamps, photobiologyLEDs, photobiologyPlants, photobiologySensors, photobiologySun, photobiologyWavebands |
| Reverse imports: | ggspectra, photobiologyInOut |
Please use the canonical form https://CRAN.R-project.org/package=photobiology to link to this page.


Oops! We can not find your token in your browser cookies.
This can be due to the following reasons:
- Cookie has expired: Did you miss your token? No worries, you can re-request for one by re-authorizing.
- We cannot display your token since you have your cookies disabled. Follow this site to enable cookies.


Now with Flux Card you have more safety and flexability with your payments. When you receive your card, simply connect it to your smartphone and launch our app. This will allow you to generate as many virtual cards as you need.
Virtual cards will be verified by your physical card for in-store use.
Learn more about generating virtual cards
You can use your physical Flux Card for contactless use. With this card you will have as many accounts as you need. These accounts are accesible through your Flux Card app.
Each account will have a limit and safety options decided by you
Learn more about sub-account options
From login to individual card accounts, Flux Card offers more security features to protect you than standard available cards.
You will receive live notifications on all transactions to your phone. You have the option to accept or decline any transaction and place limits on each account.
Learn more about Flux Card security
Flux Card offers merchants and users more validation. The physical Flux Card will be used to verify in-store payments that are made using virtual cards.
This allows the Flux Card user to use their card anywhere in the world, without any scrutiny on the authentication.
Learn more about verification


Our bank is one of the best underwriter that offers you all kinds of loans
We will make our best to offer you best rate and affordable loans
Our bank endeavors to offer you the best interest rate loans. These loans are probably the lowest interest rates across the banking industries. Trust our bank and you will be rewarded
A personal loan can get you the money you need in short order if you qualify. Personal loans are a popular tool for consolidating and eliminating high interest credit card debt. Just like credit cards, our personal loans don’t require collateral — they are unsecured. But unlike most credit cards, most personal loans offer fixed interest rates and payments. Our bank offer personal loan at very low interest rate. You can:
Our bank offer a variety of business loans that can serve your business needs
Our bank's student loan, or education loan can cover up to 100% of eligible college costs, with additional benefits such as:
Learn more about our student loans


Toggle navigation
Flag
Dashboard
Please choose a room.
Question?
Enter a question for the TA
Ping
Click button below to request TA


TOMMY BOY A film review by Eric Grossman Copyright 1995 LOS ANGELES INDEPENDENT
After graduating from seven years of college with a D+ average, Tommy Callahan (Chris Farley) finds himself back in his hometown of Sandusky, Ohio where a top job in his father's factory awaits him. When Big Tom (Brian Dennehy) is struck by a fatal heart attack, the family business falls in danger of being bought out by a rival. It is up to Tommy and Richard Hayden (David Spade), an uptight but efficient company man, to keep Callahan Auto Parts from being cannibalized and sending Tommy and the town of Sandusky to ruin.
It has been a long time since "Saturday Night Live" produced a big-screen star in the likes of a Bill Murray or Eddie Murphy. Michael Myers and Dana Carvey found success in the WAYNE'S WORLD series but have never had a hit otherwise. Chris Farley, however, may be a different story.
Large and likable, Farley has what it takes to carry a movie. Whether he is struggling to change his clothes in an airplane lavatory or demonstrating the advantages of auto parts by lighting model cars on fire, his Tommy Boy is always fun to watch. Add Farley's gift for humor with his big-hearted sincerity and you have a comedian that audiences will want to see more of.
Spade is the opposite of Farley, deadpan and tiny, but he is equally entertaining. The two make an excellent team and if they can find themselves a more substantial vehicle than this, a great comedy might be born.
Director Peter Segal (NAKED GUN 33-1/3) keeps the pace moving and elevates the thin script by Fred Wolf and Bonnie and Terry Turner. To their credit, the filmmakers give Farley and Spade enough scenes to allow them to shine but they waste time on unnecessary sub-plots including one with Bo Derek and Rob Lowe as they try to steal away the factory.
TOMMY BOY is a mediocre movie but offers some good laughs because of the talents of Farley and Spade.
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


About me
Get to know me
About me
Get to know me
Websites
Illustrations
Photography
About me
Get to know me
About me
Get to know me


systemctl
Control the systemd system and service manager.
More information: home page
- Show all running services:
systemctl status
- List failed units:
systemctl --failed
- Start/Stop/Restart/Reload a service:
systemctl start|stop|restart|reload unit
- Show the status of a unit:
systemctl status unit
- Enable/Disable a unit to be started on bootup:
systemctl enable|disable unit
- Mask/Unmask a unit to prevent enablement and manual activation:
systemctl mask|unmask unit
- Reload systemd, scanning for new or changed units:
systemctl daemon-reload
- Check if a unit is enabled:
systemctl is-enabled unit