to

Fabrication of a magnetic ternary ZnFe2O4/TiO2/RGO Z-scheme system with efficient photocatalytic activity and easy recyclability

RSC Adv., 2020, 10,17293-17301
DOI: 10.1039/D0RA01880E, Paper
Open Access
Yuwei Sun, Jiashuang Lei, Yizhu Wang, Qian Tang, Chunli Kang
A magnetic separable Z-scheme composite based on ZnFe2O4, TiO2 nanosheets and RGO exhibits efficient photocatalytic degradation of p-NP.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Transformation of ZIF-8 nanoparticles into 3D nitrogen-doped hierarchically porous carbon for Li–S batteries

RSC Adv., 2020, 10,17345-17352
DOI: 10.1039/C9RA10063F, Paper
Open Access
Guiqiang Cao, Da Bi, Jingxiang Zhao, Jing Zheng, Zhikang Wang, Qingxue Lai, Yanyu Liang
A novel transformation strategy assisted with ammonia treatment was successfully developed to fabricate ZIF-8-derived nitrogen-doped hierarchically porous carbon (NHPC/NH3).
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Ferroelectric P(VDF-TrFE)/POSS nanocomposite films: compatibility, piezoelectricity, energy harvesting performance, and mechanical and atomic oxygen erosion

RSC Adv., 2020, 10,17377-17386
DOI: 10.1039/D0RA01769H, Paper
Open Access
Y. Z. Liu, H. Zhang, J. X. Yu, Z. Y. Huang, C. Wang, Y. Sun
Poly(vinylidene difluoride) (PVDF) and its copolymers as the polymers with the highest piezoelectric coefficient have been widely used as sensors and generators.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Deposition of an ultra-thin polyaniline coating on a TiO2 surface by vapor phase polymerization for electrochemical glucose sensing and photocatalytic degradation

RSC Adv., 2020, 10,17387-17395
DOI: 10.1039/D0RA01571G, Paper
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Sibani Majumdar, Debajyoti Mahanta
Here, we have synthesized an ultra-thin coating of polyaniline on a TiO2 nanoparticle surface (PANI–TiO2) using a simple vapor phase polymerization method.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Correction: Synthesis of α,β-unsaturated esters of perfluoropolyalkylethers (PFPAEs) based on hexafluoropropylene oxide units for photopolymerization

RSC Adv., 2020, 10,17416-17417
DOI: 10.1039/D0RA90036B, Correction
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Céline Bonneaud, Mélanie Decostanzi, Julia Burgess, Giuseppe Trusiano, Trevor Burgess, Roberta Bongiovanni, Christine Joly-Duhamel, Chadron M. Friesen
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Position-locking of volatile reaction products by atmosphere and capping layers slows down photodecomposition of methylammonium lead triiodide perovskite

RSC Adv., 2020, 10,17534-17542
DOI: 10.1039/D0RA03572F, Paper
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Fengshuo Zu, Thorsten Schultz, Christian M. Wolff, Dongguen Shin, Lennart Frohloff, Dieter Neher, Patrick Amsalem, Norbert Koch
Gas pressure and capping layers under ultrahigh vacuum prevent methylammonium lead triiodide photo-degradation due to efficient back-reaction of volatile compounds.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Boosting performances of triboelectric nanogenerators by optimizing dielectric properties and thickness of electrification layer

RSC Adv., 2020, 10,17752-17759
DOI: 10.1039/D0RA02181D, Paper
Open Access
Xiaofang Kang, Chongxiang Pan, Yanghui Chen, Xiong Pu
Enhanced output performances of a triboelectric nanogenerator (TENG) are achieved by optimizing the high-dielectric-constant filler content in the electrification layer and decreasing its thickness.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Work function modification of PEDOT:PSS by mixing with barium acetylacetonate

RSC Adv., 2020, 10,17673-17680
DOI: 10.1039/D0RA02575E, Paper
Open Access
K. L. Woon, W. S. Wong, N. Chanlek, H. Nakajima, S. Tunmee, V. S. Lee, A. Ariffin, P. Songsiriritthigul
Modification of poly(3,4-ethylenedioxythiophene)polystyrene sulfonate as electron injection layer.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Mechanochemical approach to synthesize citric acid-soluble fertilizer of dittmarite (NH4MgPO4·H2O) from talc/NH4H2PO4 mixture

RSC Adv., 2020, 10,17686-17693
DOI: 10.1039/D0RA00387E, Paper
Open Access
Yonghao Tan, Lin Sha, Nengkui Yu, Zhengshuo Yang, Jun Qu, Zhigao Xu
Dittmarite synthesis by a mechanochemical route for application as a citric acid-soluble fertilizer.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Europium oxide nanorod-reduced graphene oxide nanocomposites towards supercapacitors

RSC Adv., 2020, 10,17543-17551
DOI: 10.1039/C9RA11012G, Paper
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Parisa Aryanrad, Hamid Reza Naderi, Elmira Kohan, Mohammad Reza Ganjali, Masoud Baghernejad, Amin Shiralizadeh Dezfuli
Fast charge/discharge cycles are necessary for supercapacitors applied in vehicles including, buses, cars and elevators.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Elongated conductive structures in detonation soot of high explosives

RSC Adv., 2020, 10,17620-17626
DOI: 10.1039/D0RA01393E, Paper
Open Access
Nataliya P. Satonkina, Alexander P. Ershov, Alexey O. Kashkarov, Ivan A. Rubtsov
Micrographs of transmission electron microscopy of saved detonation products of benzotrifuroxane at different scales.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

A novel series of phenolic temozolomide (TMZ) esters with 4 to 5-fold increased potency, compared to TMZ, against glioma cells irrespective of MGMT expression

RSC Adv., 2020, 10,17561-17570
DOI: 10.1039/D0RA02686G, Paper
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Leroy Shervington, Oliver Ingham, Amal Shervington
The standard of care treatment for patients diagnosed with glioblastoma multiforme (GBM) is temozolomide (TMZ).
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Selective cytotoxic effect against the MDA-MB-468 breast cancer cell line of the antibacterial palindromic peptide derived from bovine lactoferricin

RSC Adv., 2020, 10,17593-17601
DOI: 10.1039/D0RA02688C, Paper
Open Access
Andrea Barragán-Cárdenas, Maribel Urrea-Pelayo, Víctor Alfonso Niño-Ramírez, Adriana Umaña-Pérez, Jean Paul Vernot, Claudia Marcela Parra-Giraldo, Ricardo Fierro-Medina, Zuly Rivera-Monroy, Javier García-Castañeda
The cytotoxic effect against the breast cancer cell line MDA-MB-468 of the palindromic peptide LfcinB (21–25)Pal: 1RWQWRWQWR9 and its analogous peptides, obtained via alanine scanning, was evaluated.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Electrochemical reduction of CO2 to ethylene on Cu/CuxO-GO composites in aqueous solution

RSC Adv., 2020, 10,17572-17581
DOI: 10.1039/D0RA02754E, Paper
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Nusrat Rashid, Mohsin Ahmad Bhat, U. K. Goutam, Pravin Popinand Ingole
Herein, we present fabrication of graphene oxide supported Cu/CuxO nano-electrodeposits which efficiently and selectively can electroreduce CO2 into ethylene with a faradaic efficiency of 34% and conversion rate of 194 mmol g−1 h−1 at −0.985 V vs. RHE.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Correction: Influence of co-cultures of Streptococcus thermophilus and probiotic lactobacilli on quality and antioxidant capacity parameters of lactose-free fermented dairy beverages containing Syzygium cumini (L.) Skeels pulp

RSC Adv., 2020, 10,16905-16905
DOI: 10.1039/D0RA90046J, Correction
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Sabrina Laís Alves Garcia, Gabriel Monteiro da Silva, Juliana Maria Svendsen Medeiros, Anna Paula Rocha de Queiroga, Blenda Brito de Queiroz, Daniely Rayane Bezerra de Farias, Joyceana Oliveira Correia, Eliane Rolim Florentino, Flávia Carolina Alonso Buriti
The content of this RSS Feed (c) The Royal Society of Chemistry




to

A poly(allylamine hydrochloride)/poly(styrene sulfonate) microcapsule-coated cotton fabric for stimulus-responsive textiles

RSC Adv., 2020, 10,17731-17738
DOI: 10.1039/D0RA02474K, Paper
Open Access
Zhiqi Zhao, Qiujin Li, Jixian Gong, Zheng Li, Jianfei Zhang
This study reports a stimulus-responsive fabric incorporating a combination of microcapsules, containing polyelectrolytes poly(allylamine hydrochloride) (PAH) and poly(styrene sulfonate) sodium salt (PSS), formed via a layer-by-layer (LBL) approach.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Preparation of phosphorus-doped porous carbon for high performance supercapacitors by one-step carbonization

RSC Adv., 2020, 10,17768-17776
DOI: 10.1039/D0RA02398A, Paper
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Guanfeng Lin, Qiong Wang, Xuan Yang, Zhenghan Cai, Yongzhi Xiong, Biao Huang
P-doped porous carbon can be prepared by one-step carbonization using biomass sawdust impregnated with a small amount of phosphoric acid.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

A chitosan-based edible film with clove essential oil and nisin for improving the quality and shelf life of pork patties in cold storage

RSC Adv., 2020, 10,17777-17786
DOI: 10.1039/D0RA02986F, Paper
Open Access
Karthikeyan Venkatachalam, Somwang Lekjing
This study assessed chitosan (CS)-based edible films with clove essential oil (CO) and nisin (NI) singly or in combination, for improving quality and shelf life of pork patties stored in cold conditions.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Ni stabilized rock-salt structured CoO; Co1−xNixO: tuning of eg electrons to develop a novel OER catalyst

RSC Adv., 2020, 10,17845-17853
DOI: 10.1039/D0RA03050C, Paper
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Rakesh Mondal, Himanshu Ratnawat, Sarvesh Kumar, Anil Kumar, Preetam Singh
Incorporation of Ni into CoO lattices helps to stabilize the rock salt structure and modulate the eg electrons to develop superior OER and ORR electrocatalysts.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Effect of Zn doping on phase transition and electronic structures of Heusler-type Pd2Cr-based alloys: from normal to all-d-metal Heusler

RSC Adv., 2020, 10,17829-17835
DOI: 10.1039/D0RA02951C, Paper
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Xiaotian Wang, Mengxin Wu, Tie Yang, Rabah Khenata
By first-principles calculations, for Heusler alloys Pd2CrZ (Z = Al, Ga, In, Tl, Si, Sn, P, As, Sb, Bi, Se, Te, Zn), the effect of Zn doping on their phase transition and electronic structure has been studied in this work.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Enhanced methane gas storage in the form of hydrates: role of the confined water molecules in silica powders

RSC Adv., 2020, 10,17795-17804
DOI: 10.1039/D0RA01754J, Paper
Open Access
Pinnelli S. R. Prasad, Burla Sai Kiran, Kandadai Sowjanya
Rapid and efficient methane hydrate conversions by utilising the water molecules confined in intra- and inter-granular space of silica powders.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Facile synthesis of a direct Z-scheme BiOCl–phosphotungstic acid heterojunction for the improved photodegradation of tetracycline

RSC Adv., 2020, 10,17369-17376
DOI: 10.1039/D0RA02396E, Paper
Open Access
Haijuan Tong, Bingfang Shi, Shulin Zhao
A one-step hydrothermal approach for synthesizing BiOCl–phosphotungstic acid (BiOCl–HPW) heterojunctions is proposed. The prepared BiOCl–HPW heterojunction exhibited good stability and photocatalytic activity.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Correction: Narrowing band gap and enhanced visible-light absorption of metal-doped non-toxic CsSnCl3 metal halides for potential optoelectronic applications

RSC Adv., 2020, 10,17869-17869
DOI: 10.1039/D0RA90054K, Correction
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Jakiul Islam, A. K. M. Akther Hossain
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Lithium metal deposition/dissolution under uniaxial pressure with high-rigidity layered polyethylene separator

RSC Adv., 2020, 10,17805-17815
DOI: 10.1039/D0RA02788J, Paper
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Shogo Kanamori, Mitsuhiro Matsumoto, Sou Taminato, Daisuke Mori, Yasuo Takeda, Hoe Jin Hah, Takashi Takeuchi, Nobuyuki Imanishi
The use of a high rigidity separator and application of an appropriate amount of pressure are effective approaches to control lithium metal growth and improve its cycle performance.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Synthesis of heteroatom-containing pyrrolidine derivatives based on Ti(O-iPr)4 and EtMgBr-catalyzed carbocyclization of allylpropargyl amines with Et2Zn

RSC Adv., 2020, 10,17881-17891
DOI: 10.1039/D0RA02677H, Paper
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Rita N. Kadikova, Ilfir R. Ramazanov, Azat M. Gabdullin, Oleg S. Mozgovoj, Usein M. Dzhemilev
The Ti(O-iPr)4 and EtMgBr-catalyzed regio and stereoselective carbocyclization of N-allyl-substituted 2-alkynylamines with Et2Zn, followed by deuterolysis or hydrolysis, affords the corresponding methylenepyrrolidine derivatives in high yields.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Nanoporous materials with predicted zeolite topologies

RSC Adv., 2020, 10,17760-17767
DOI: 10.1039/D0RA01888K, Paper
Open Access
  This article is licensed under a Creative Commons Attribution 3.0 Unported Licence.
Vladislav A. Blatov, Olga A. Blatova, Frits Daeyaert, Michael W. Deem
Topological exploration of crystal structures demonstrates the presence of known zeolites, inorganics, and MOFs in a database of predicted materials.
The content of this RSS Feed (c) The Royal Society of Chemistry




to

Anatomy of an HTML5 WordPress theme

This site has been written in HTML5 and used to use WordPress to manage the content. I’ll explain why I used HTML5, describe the structure of the theme templates, and show some of the ways I tried to tame WordPress’s tendency to add mess to the source code.

As this is my personal site I wanted to experiment with using HTML5, CSS3, and WAI-ARIA. All these documents are currently working drafts and subject to change. However, the web documents and applications of the future are going to be written in HTML5 and I wanted to see the benefits of using it to markup static documents. Using CSS 2.1, let alone the CSS3 selectors and properties that some browser vendors have implemented, has many advantages for controlling the presentation of semantically coded documents. For this reason I am not going to avoid using basic CSS 2.1 selectors just to faithfully reproducing this site’s design in IE6. However, I have tried to accommodate IE 7 and IE 8 users by using an HTML5 enabling script so that the new HTML5 elements can be styled in those browsers if users have Javascript enabled.

HTML5 templates

I started with a static prototype of this site developed on my local server. WordPress makes it very easy to create your own templates and, therefore, it is no problem to use HTML5. This theme only has 3 main templates: index, single, and archive. There are of course templates for 404s, attachments, comments, etc., but I won’t discuss them as they are all based on the 3 main templates. All the templates include ARIA roles as an accessibility aide.

The single.php template has this rough structure:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="default.css">
</head>

<body>
  <header role="banner"></header>
  <nav role="navigation"></nav>
  <article role="main">
    <header>
      <time datetime="YYYY-MM-DD"></time>
      <h1></h1>
    </header>
    <footer></footer>
  </article>
  <nav></nav>
  <aside role="complementary"></aside>
  <footer role="contentinfo">
    <small></small>
  </footer>
</body>
</html>

The first line of the document is the HTML5 DOCTYPE. The new <article> element contains the content of each post. The same structure is used for the index.php template except that there are several articles displayed on each page and the ARIA role value of main is not used. In contrast, the archive.php template houses all the article excerpts in a <section> element with the ARIA role of main because the list of archived posts is itself the main content of the document.

A clean theme

WordPress tends to add classes, elements, and other bits of code in certain places. I haven’t used any of the WordPress functions that add class names to the body and to elements wrapping a post and also wanted to avoid cluttering the source code with any other unnecessary markup. This required a bit of fiddling around with the theme’s functions.php file. I’m not a PHP developer so this might not be pretty!

Removing actions from wp_head()

WordPress has a hook called wp_head that sits in the header.php of most themes. To avoid it inserting unwanted code into the <head> of the document I used the remove_action function to disable the functions that were responsible. The following code was added to the functions.php file of my theme:

// Remove links to the extra feeds (e.g. category feeds)
remove_action( 'wp_head', 'feed_links_extra', 3 );
// Remove links to the general feeds (e.g. posts and comments)
remove_action( 'wp_head', 'feed_links', 2 );
// Remove link to the RSD service endpoint, EditURI link
remove_action( 'wp_head', 'rsd_link' );
// Remove link to the Windows Live Writer manifest file
remove_action( 'wp_head', 'wlwmanifest_link' );
// Remove index link
remove_action( 'wp_head', 'index_rel_link' );
// Remove prev link
remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 );
// Remove start link
remove_action( 'wp_head', 'start_post_rel_link', 10, 0 );
// Display relational links for adjacent posts
remove_action( 'wp_head', 'adjacent_posts_rel_link', 10, 0 );
// Remove XHTML generator showing WP version
remove_action( 'wp_head', 'wp_generator' );

Source: WPEngineer.com: Cleanup WordPress Header

Removing an empty <span>

If you want to create excerpts you can either write them into the excerpt box or use the <--more--> quicktag in the WordPress editor. I just wanted the first paragraph of my posts to be used as the excerpt and so using the in-editor tag was the most practical approach I was aware of. However, when you do this WordPress will insert an empty <span> in the post’s content. This element has an id so that the area following the excerpt can be targeted by “more” or “continue reading” links. I removed both the empty <span> and the jump link by adding the following code to the functions.php file of the theme:

// removes empty span
function remove_empty_read_more_span($content) {
  return eregi_replace("(<p><span id="more-[0-9]{1,}"></span></p>)", "", $content);
}
add_filter('the_content', 'remove_empty_read_more_span');

Source: Ganda Manurung: Remove Empty Span Tag On WordPress

// removes url hash to avoid the jump link
function remove_more_jump_link($link) {
  $offset = strpos($link, '#more-');
  if ($offset) {
    $end = strpos($link, '"',$offset);
  }
  if ($end) {
    $link = substr_replace($link, '', $offset, $end-$offset);
  }
  return $link;
}
add_filter('the_content_more_link', 'remove_more_jump_link');

Source: WordPress Codex: Customizing the Read More

Displaying images in the excerpt

For posts that display nothing but a photograph (yes, they will be shit but I’m hoping it gets me using my camera a bit more often) I wanted the image to show up in the archives. Equally, if the first paragraph of a post contained a link I wanted that to be preserved. The default the_excerpt() template tag doesn’t allow for this so it needed some modifying. I added a new function, which is just a modified version of the core excerpt function, to the functions.php file and then made sure that the template tag executed this function rather than the one contained in the core WordPress files.

function improved_trim_excerpt($text) {
   if ( '' == $text ) {
      $text = get_the_content('');
      $text = strip_shortcodes( $text );
      $text = apply_filters('the_content', $text);
      $text = str_replace(']]>', ']]&amp;gt;', $text);
      $text = strip_tags($text, '<p><img><a>');
      $excerpt_length = apply_filters('excerpt_length', 55);
      $words = explode(' ', $text, $excerpt_length + 1);
      if (count($words) > $excerpt_length) {
         array_pop($words);
         array_push($words, '[...]');
         $text = implode(' ', $words);
         $text = force_balance_tags($text);
      }
   }
   return $text;
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'improved_trim_excerpt');

Source: Aaron Russell: Improving WordPress’ the_excerpt() template tag

I prefer not to have empty elements in the markup and so I needed a way to conditionally insert the “Older entries”, “Newer Entries”, etc., links into templates. The solution I’m using here, which isn’t perfect, is to add this to functions.php:

function show_posts_nav() {
  global $wp_query;
  return ($wp_query->max_num_pages > 1);
}

Source: Eric Martin: Conditional navigation links in WordPress

And then to wrap the navigation markup in the templates with the following:

<?php if (show_posts_nav()) : ?>
<nav>
   <ul>
      <li><?php next_posts_link('&#171; Older Entries') ?></li>
      <li><?php previous_posts_link('Newer Entries &#187;') ?></li>
   </ul>
</nav>
<?php endif; ?>

Summary

It’s fairly easy to create a simple site with HTML5 and to use WordPress to deliver it. At the moment there are issues with Internet Explorer because you cannot style HTML5 elements unless you use Javascript. However, HTML5 redefines the meaning of certain elements (such as <dl>, which has become a more versatile “description list”) and allows block elements to be wrapped in a link. Therefore, there is still benefit in using the HTML5 DOCTYPE even if you do not make use of the new elements.

Further reading

  1. HTML5 working draft
  2. HTML5 differences from HTML4
  3. Accessible Rich Internet Applications (WAI-ARIA) 1.0




to

Photograph of a curious cow




to

Ladybird macro photographs

This morning hundreds of ladybirds were flying through the air and massing on the white walls of the house. I managed to get a few clear macro photographs.

The sun was shining and the ladybirds seemed to be attracted to anything white. I stuck a white T-shirt on and headed outside. Pretty soon I was covered in them and could pluck them from my shirt to get some close ups using my little Canon IXUS 60.

At some point a ladybird took off just before I tried to photograph it and I decided I’d try to capture that moment. A few minutes later I’d worked out that I could prompt one of the insects to walk up my finger like the stem of a flower, that they’d take off when they reached the tip, and that they took up a distinct posture just before their wing-case shot open.

The speed at which they prepare to take off, open their wings, and fly away is so quick that I just had to take the shot as soon as I saw a ladybird get into the “take-off position” and hope that I reacted fast enough to get a picture of the open wing-case.




to

Photogenic toad

This toad jumped out of the long grass near a pond and kindly let me take a few photographs of it.




to

Custom Tweet Button for WordPress

How to create a custom Tweet Button for WordPress using the bit.ly and Twitter APIs. The HTML and CSS is completely customisable and there is no need for JavaScript. PHP is used to automatically shorten and cache the URL of a post, fetch and cache the number of retweets, and populate the query string parameters in the link to Twitter.

The custom Tweet Button at the bottom of this post was created using this method. All the files are available on Github and released under MIT license. The PHP code was heavily influenced by the BackType Tweetcount plugin.

How to use

You’ll need your own bit.ly account and to be comfortable editing your theme’s functions.php, style.css, and template files. Be sure to make backups before you start making changes.

Step 1: Download the Custom Tweet Button for WordPress files from Github.

Step 2: Include the custom-tweet-button.php file in your theme’s functions.php file.

Step 3: Replace the bit.ly username, bit.ly API key, and Twitter username placeholders in the tweet_button function with your own. Your bit.ly credentials can be found on the “settings” page of your account.

Step 4: Add the custom Tweet Button CSS to your theme’s style.css file. Add the tweet.png image in your theme’s image folder. Make sure the image is correctly referenced in the CSS file.

Step 5: Call the function tweet_button in your template files (e.g. single.php) at the position(s) in the HTML you’d like the Tweet Button to appear:

if (function_exists('tweet_button')) {
   tweet_button(get_permalink());
}

Why make your own Tweet Button?

Making your own custom Tweet Button for WordPress has several additional advantages over using Twitter’s own offerings.

  • Full control over the HTML and CSS.
    Having full control over the HTML and CSS means that you can choose how to present your Tweet Button. I decided to reproduce the horizontal and vertical styles of Twitter’s own button. But any appearance is possible.

  • All click, traffic, and referrer data is stored in your bit.ly account.
    The URL for any published post is automatically shortened using the bit.ly service. The short URL is then passed to Twitter to ensure you can monitor the click and traffic data in your bit.ly account. The permalink is passed to Twitter in the counturl query string parameter to ensure that it counts the URL that your short URL resolves to.

  • No need for JavaScript or embedded iframes.
    The Tweet Button works without JavaScript. You have full control over any custom JavaScript enhancements you may wish to include. If you’d prefer Twitter’s share page to open in a pop-up window you can write your own JavaScript handler.

  • Faster page load.
    No external JavaScript or image files are loaded; both the short URL and retweet counts are cached.

  • Use the short URL and retweet count for other purposes.
    The short URLs and retweet counts are stored as post meta-data. This makes it easy to display this data anywhere else in a post. The retweet count data could be used for conditional template logic. For example, you could order posts based on the number of retweets, apply custom styles to your most retweeted posts, or display your most tweeted posts in a widget.

  • Easy to add Google Analytics campaign and event tracking.
    The Tweet Button is simple HTML and you have control over all the information that is sent to Twitter. Therefore, it is possible to use Google Analytics to help answer questions like: are people sharing your posts from the homepage or the post itself? If the Tweet Button is displayed above and below your posts, which gets the most clicks? How long do people take to click the Tweet Button? How many people are visiting my site thanks to links posted on Twitter using the Tweet Button?

  • Approximate the number of retweets for old posts.
    Before the release of the official Tweet Button, Twitter did not collect data on the number of times a URL was tweeted. This means your older posts may display far fewer retweets than actually occurred. However, there is a workaround. Use a service like Topsy, Backtype, or Tweetmeme to get the number of times your old post was retweeted. The difference between this and the number from Twitter’s APIs is the approximate number of retweets Twitter missed. To correct the retweet count for old posts add the number of missed retweets to a Custom Field called retweet_count_start.

How the custom Tweet Button works

Once a post is published its permalink URL is shortened using the bit.ly API.

The returned URL is permanently cached in the bitly_short_url Custom Field. The short URL is now part of the post’s general meta-data and can be used in contexts other than the Tweet Button.

The Twitter API is used to get the number of retweets for the post’s permalink URL. This number, along with the time at which it was requested, is cached in the retweet_cache Custom Field. When the cache interval has passed, an API call is made and the returned number of retweets is checked against the value stored in retweet_cache. If the returned number is greater, the value of retweet_cache is updated.

The content of the tweet is automatically created by setting several properties for the http://twitter.com/share URL. The post title makes up the message; the short URL is passed to Twitter as the URL to be displayed in the tweet; the permalink URL is passed to Twitter as the URL to be counted; and your username is declared.

$twitter_params =
'?text=' . urlencode($title) .
'&amp;url=' . urlencode($short_url) .
'&amp;counturl=' .urlencode($url).
'&amp;via=' . $twitter_via;

The default HTML output is very simple and can be fully customised. To display the count number vertically, add the class vcount.

<div class="twitter-share vcount>
   <a class="twitter-button"
      rel="external nofollow"
      title="Share this on Twitter"
      href="http://twitter.com/share?query-string-params"
      target="_blank">Tweet</a>
   <a class="twitter-count" href="http://twitter.com/search?q=url>259</a>
</div>

Further enhancements

Please apply any improvements or enhancements for the script against the source repository.




to

An introduction to CSS pseudo-element hacks

CSS is a versatile style language that is most frequently used to control the look and formatting of an HTML document based on information in the document tree. But there are some common publishing effects – such as formatting the first line of a paragraph – that would not be possible if you were only able to style elements based on this information. Fortunately, CSS has pseudo-elements and pseudo-classes.

As their names imply, they are not part of the DOM in the way that ‘real’ HTML elements and classes are. Instead, they are CSS abstractions that provide additional, and otherwise inaccessible, information about the document.

This article will discuss the CSS pseudo-elements that are part of CSS 2.1 – :first-letter, :first-line, :before, and :after – and how the :before and :after pseudo-elements can be exploited to create some interesting effects, without compromising the simplicity of your HTML. But first, let’s look at each type of pseudo-element and how to use them in their basic form.

The :first-line and :first-letter pseudo-elements

The :first-line pseudo-element lets you apply styles to the first formatted line of a block container element (i.e., elements with their display property set to block, inline-block, list-item, table-caption, or table-cell). For example:

p:first-line { font-weight: bold; }

…will change the first line of every paragraph to bold. The :first-line pseudo-element can be treated as if it were an extra HTML inline element wrapping only the first line of text in the paragraph.

The :first-letter pseudo-element lets you apply styles to the first letter (and any preceding punctuation) of the first formatted line of a block container element. No other inline content (e.g. an image) can appear before the text. For example:

p:first-letter { float: left; font-size: 200%; }

…will produce a basic ‘drop cap’ effect. The first letter of every paragraph will be floated left, and twice as large as the other letters in the paragraph. The :first-letter pseudo-element can be treated as if it were an extra HTML inline element wrapping only the first letter of text in the paragraph.

The :first-line and :first-letter pseudo-elements can only be attached to block container elements, but the first formatted line can be contained within any block-level descendant (e.g., elements with their display property set to block or list-item) in the same flow (i.e., not floated or positioned). For example, the following HTML fragment and CSS:

<div><p>An example of the first line of text being within a descendant element</p></div>

div:first-line { font-weight: bold; }

…would still result in a bold first line of text, because the paragraph’s text is the first formatted line of the div.

The :before and :after pseudo-elements

The :before and :after pseudo-elements are used to insert generated content before or after an element’s content. They can be treated as if they were extra HTML inline elements inserted just before and after the content of their associated element.

Generated content is specified using the content property which, in CSS 2.1, can only be used in conjunction with the :before and :after pseudo-elements. Furthermore, you must declare the content property in order to generate the :before and :after pseudo-elements.

The content property can take string, url(), attr(), counter() and counters() values. The url() value is used to insert an image. The attr() function returns as a string the value of the specified attribute for the associated element. The counter() and counters() functions can be used to display the value of any CSS counters.

For example, the following HTML fragment and CSS:

<a href="http://wikipedia.org">Wikipedia</a>

a:after { content: " (" attr(href) ")"; }

…would display the value of the href attribute after a link’s content, resulting in the following anchor text for the example above: Wikipedia (http://wikipedia.org). This can be a helpful way to display the destination of specific links in printed web documents.

Keep in mind that CSS is meant for adding presentation and not content. Therefore, the content property should be used with caution.

It’s also worth noting that the :first-letter and :first-line pseudo-elements apply to the first letter and first line of an element including any generated content inserted using the :before and :after pseudo-elements.

Browser support for pseudo-elements

The :first-letter and :first-line pseudo-elements were introduced in CSS1 and there is wide basic support for them. However, IE 6 and IE 7 have particularly buggy implementations; even modern browsers are not entirely consistent in the way that they handle the :first-line and :first-letter pseudo-elements (example bugs).

The :before and :after pseudo-elements were introduced in the CSS 2.1 specification and are fully implemented in Firefox 3.5+, IE 8+, Safari 3+, Google Chrome, and Opera. Modern versions of Firefox even support CSS transitions and animations applied to pseudo-elements. However, legacy browsers like IE 6 and IE 7 do not support the :before and :after pseudo-elements at all.

For more detailed information on pseudo-element browser support, browser bugs, and workarounds, have a look at Sitepoint’s reference and this article on IE 6/7 issues.

In most cases, the :before and :after pseudo-elements can be used as part of a ‘progressive enhancement’ approach to design and development, because IE 6 and IE 7 will simply ignore them altogether. Alternatively, Modernizr now includes a robust feature test for generated content, providing one way to specify fallbacks or enhancements depending on browser support. The important thing is to remember to check what happens in browsers where support is missing.

Alternative ways to use pseudo-elements

Let’s take a look at how the :before and :after pseudo-elements can be used as the basis for some interesting effects. Most of the time, this involves generating empty :before and :after pseudo-elements by declaring an empty string as the value of the content property. They can then be manipulated as if they were empty inline HTML elements, keeping your HTML clean and giving you full control of certain effects from within CSS style sheets.

Simple visual enhancements, like speech bubbles and folded corners, can even be created without the need for images. This relies on the fact that you can create simple shapes using CSS.

Several types of ‘CSS polygons’ can be created as a result of browsers rendering borders at an angle when they meet. This can be exploited to create triangles. For example, the following HTML fragment and CSS:

<div class="triangle"></div>

.triangle {
  width: 0;
  height: 0;
  border-width: 20px;
  border-style: solid;
  border-color: red transparent transparent;
}

…will create a downward pointing, red triangle. By varying the width, height, border-width, border-style, and border-color values you can produce different shapes and control their orientation and colour. For more information, be sure to read Jon Rogan’s summary of the technique.

The more advanced pseudo-element hacks use the extra background canvas afforded by each :before and :after pseudo-element. This can help you crop background images, control the opacity of background images, and ‘fake’ multiple backgrounds and borders in browsers without support for CSS3 multiple backgrounds (e.g., IE 8). Taken to ludicrous extremes, you can even build a whole CSS icon set. To start with, let’s look at some simple effects that can be created without images or presentational HTML.

Creating CSS speech bubbles

In this example, a quote is styled to look like a speech bubble, using CSS. This is done by creating a triangle using a pseudo-element, and then absolutely positioning it in the desired place. By adding position:relative to the CSS styles for the HTML element, you can absolutely position the :after pseudo-element relative to its associated element.

<div class="quote">[Quoted text]</div>

.quote {
  position: relative;
  width: 300px;
  padding: 15px 25px 20px;
  margin: 20px auto;
  font: italic 26px/1.4 Georgia, serif;
  color: #fff;
  background: #245991;
}

.quote:after {
  content: "";
  position: absolute;
  top: 100%;
  right: 25px;
  border-width: 30px 30px 0 0;
  border-style: solid;
  border-color: #245991 transparent;
}

There’s nothing stopping you from adding some CSS3 to further enhance the effect for capable browsers. This could be adding rounded corners to the box or applying a skew transform to the triangle itself. Fiddle with the code in this example.

Creating CSS ‘ribbons’

Using the same principle, you can create a CSS ribbon effect without images or extra HTML. This time the effect uses 2 pseudo-element triangles. The HTML fragment is still very simple.

<div class="container">
    <h1>Simple CSS ribbon</h1>
    <p>[other content]</p>
</div>

You then need to use negative margins to pull the h1 outwards so that it extends over the padding and beyond the boundaries of the container div. The HTML fragment above can be styled using the following CSS:

.container {
  width: 400px;
  padding: 20px;
  margin: 20px auto;
  background: #fff;
}

.container h1 {
  position: relative;
  padding: 10px 30px;
  margin: 0 -30px 20px;
  font-size: 20px;
  line-height: 24px;
  font-weight: bold;
  color: #fff;
  background: #87A800;
}

From here, you only need to add the pseudo-element triangles to create the ‘wrapping’ appearance associated with ribbons. The :before and :after pseudo-elements share many styles, so you can simplify the code by only overriding the styles that differ between the two. In this case, the triangle created with the :after pseudo-element must appear on the opposite side of the heading, and will be a mirror image of the other triangle. So you need to override the shared styles that control its position and orientation.

.container h1:before,
.container h1:after {
  content: "";
  position: absolute;
  top: 100%;
  left: 0;
  border-width: 0 10px 10px 0;
  border-style: solid;
  border-color: transparent #647D01;
}

/* override shared styles */
.container h1:after {
  left: auto;
  right: 0;
  border-width: 0 0 10px 10px;
}

Fiddle with the code in this example.

Creating CSS folded corners

The final example of this form of pseudo-element hack creates a simple CSS folded-corner effect. A pseudo-element’s border properties are set to produce two differently-coloured touching triangles. One triangle is a slightly darker or lighter shade of the box’s background colour. The other triangle matches the background colour of the box’s parent (e.g. white). The pseudo-element is then positioned in the top right corner of its associated element to complete the effect.

.note {
  position: relative;
  padding: 20px;
  margin: 2em 0;
  color: #fff;
  background: #97C02F;
}

.note:before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  border-width: 0 16px 16px 0;
  border-style: solid;
  border-color: #658E15 #fff;
}

Varying the size of the borders will vary the size and angle of the folded-corner. Fiddle with the code in this example.

Pseudo background-crop

Although creating polygons with pseudo-elements can produce some popular effects without images, the possibilities are inherently limited. But this is only one type of :before and :after pseudo-element hack. Treated as extra background canvases, they can be used to fill some gaps in existing browser support for CSS features.

One of those features is the cropping of background images. In the future, it’s likely that you’ll be able to crop background images using fragment identifiers, as is proposed in the CSS Image Values Module Level 3 draft. But at the moment no browsers support the use of fragment identifiers with bitmap images. Until they do, you can make use of this CSS 2.1 hack to emulate background image cropping in modern browsers.

The principle behind a ‘pseudo background-crop‘ is to apply a background-image to a pseudo-element rather than directly to an element in the HTML document. One of the applications of this technique is to crop icons that are part of a sprite.

For example, a web app might allow users to ‘save’, ‘edit’, or ‘delete’ an item. The HTML involved might look something like this:

<ul class="actions">
  <li class="save"><a href="#">Save</a></li>
  <li class="edit"><a href="#">Edit</a></li>
  <li class="delete"><a href="#">Delete</a></li>
</ul>

To enhance the appearance of these ‘action’ links, it is common to see icons sitting alongside the anchor text. For argument’s sake, let’s say that the relevant icons are part of a sprite that is organised using a 16px × 16px grid.

The :before pseudo-element – with dimensions that match the sprite’s grid unit – can be used to crop and display each icon. The sprite is referenced as a background image and the background-position property is used to control the precise positioning of each icon to be shown.

.actions a:before {
  content: "";
  float: left;
  width: 16px;
  height: 16px;
  margin: 0 5px 0 0;
  background: url(sprite.png);
}

.save a:before { background-position: 0 0; }
.edit a:before { background-position: -16px 0; }
.delete a:before { background-position: -32px 0; }

Using pseudo-elements like this helps to avoid the need to either add liberal amounts of white space to sprites or use empty HTML elements to do the cropping. Fiddle with the code in this example.

Pseudo background-position

The CSS 2.1 specification limits the values of background-position to horizontal and vertical offsets from the top-left corner of an element. The CSS Backgrounds and Borders Module Level 3 working draft includes an improvement to the background-position property to allow offsets to be set from any side. However, Opera 11+ is currently the only browser to have implemented it.

But by using pseudo-elements, it’s possible to emulate positioning a background image from any side in any browser with adequate CSS 2.1 support –’pseudo background-position‘.

Once a pseudo-element is created, it must be absolutely positioned in front of the associated element’s background but behind its content, so as not to prevent users from being able to select text or click on links. This is done by setting a positive z-index on the element and a negative z-index on the pseudo-element.

#content {
  position: relative;
  z-index: 1;
}

#content:before {
  content: "";
  position: absolute;
  z-index: -1;
}

Now the pseudo-element can be sized and positioned to sit over any area within (or beyond) the element itself, without affecting its content. This is achieved by using any combination of values for the top, right, bottom, and left positional offsets, as well as the width, and height properties. It is the key to their flexibility.

In this example, a 200px × 300px background image is applied to the pseudo-element, which is also given dimensions that match those of the image. Since the pseudo-element is absolutely positioned, it can be offset from the bottom and right of the associated HTML element.

#content {
  position: relative;
  z-index: 1;
}

#content:before {
  content: "";
  position: absolute;
  z-index: -1;
  bottom: 10px;
  right: 10px;
  width: 200px;
  height: 300px;
  background: url(image.jpg);
}

Many other hacks and effects are possible using the :before and :after pseudo-elements, especially when combined with CSS3. Hopefully this introduction to pseudo-elements, and how they can be exploited, will have inspired you to experiment with them in your work.

The future of pseudo-elements

The way that pseudo-elements are used will continue to change as CSS does. Some new applications will emerge, and existing ones will fade away as browser implementation of ‘CSS3 modules’ continues to improve.

Generated content and pseudo-elements themselves are likely to undergo changes too. The CSS3 Generated and Replaced Content Module introduced a two-colon format for pseudo-elements (i.e., ::before) to help distinguish between pseudo-classes and pseudo-elements. But for compatibility with previous levels of CSS, pseudo-elements do not require two colons. Most modern browsers support both formats, but it is not supported by IE 8 and the single-colon format ensures greater backwards compatibility.

The proposed extensions to pseudo-elements included the addition of nested pseudo-elements (::before::before), multiple pseudo-elements (::after(2)), wrapping pseudo-elements (::outside), and the ability to insert pseudo-elements into later parts of the document (::alternate). However, the CSS3 Generated and Replaced Content Module is undergoing significant changes.

This article was originally published in .net magazine in April 2011




to

“Mobile first” CSS and getting Sass to help with legacy IE

Taking a “mobile first” approach to web development poses some challenges if you need to provide a “desktop” experience for legacy versions of IE. Using a CSS pre-processor like Sass can help.

As of Sass 3.2, there is another way of catering for IE, described by Jake Archibald.

One aspect of a “mobile first” approach to development is that your styles are usually gradually built up from a simple base. Each new “layer” of CSS adds presentational adjustments and complexity, via CSS3 Media Queries, to react to and make use of additional viewport space. However, IE 6/7/8 do not support CSS3 Media Queries. If you want to serve IE 6/7/8 something more than just the base CSS, then you need a solution that exposes the “enhancing” CSS to those browsers.

An existing option is the use of a CSS3 Media Query polyfill, such as Respond.js. However, there are some drawbacks to this approach (see the project README), such as the introduction of a JavaScript dependency and the XHRing of your style sheets, which may introduce performance or cross-domain security issues. Furthermore, adding support for CSS3 Media Queries is probably not necessary for these legacy browsers. The main concern is exposing the “enhancing” CSS.

Another method, which Jeremy Keith has described in his post on Windows mobile media queries, is to use separate CSS files: one basic global file, and an “enhancing” file that is referenced twice in the <head> of the document. The “enhancing” file is referenced once using a media attribute containing a CSS3 Media Query value. This prevents it being downloaded by browsers (such as IE 6/7/8) which do not support CSS3 Media Queries. The same file is then referenced again, this time wrapped in an IE conditional comment (without the use of a CSS3 Media Query value) to hide it from modern browsers. However, this approach becomes somewhat cumbersome, and introduces multiple HTTP requests, if you have multiple breakpoints in your responsive design.

Getting Sass to help

Sass 3.1 provides some features that help make this second approach more flexible. The general advantages of the Sass-based approach I’ve used are:

  1. You have full control over how your style sheets are broken up and reassembled.
  2. It removes the performance concerns of having to reference several separate style sheets for each breakpoint in the responsive design, simply to cater for IE 6/7/8.
  3. You can easily repeat large chunks of CSS in separate compiled files without introducing maintenance problems.

The basic idea is to produce two versions of your compiled CSS from the same core code. One version of your CSS includes CSS3 @media queries and is downloaded by modern browsers. The other version is only downloaded by IE 6/7/8 in a desktop environment and contains no CSS3 @media queries.

To do this, you take advantage of the fact that Sass can import and compile separate .scss/.sass files into a single CSS file. This allows you to keep the CSS rules used at any breakpoint completely separate from the @media query that you might want it to be a part of.

This is not a CSS3 Media Query polyfill, so one assumption is that IE 6/7/8 users will predominantly be using mid-size screens and should receive styles appropriate to that environment. Therefore, in the example below, I am making a subjective judgement by including all the breakpoint styles up to a width of 960px but withholding those for any breakpoints beyond that.

The ie.scss file imports numerous other files, each containing a layer of CSS that builds upon the previous each layer of CSS. No CSS3 @media queries are contained within the files or the ie.scss file. It then compiles to a single CSS file that is designed to be served only to IE 6/7/8.

// ie.scss

@import "base";
@import "320-up";
@import "480-up";
@import "780-up";
@import "960-up";

The style.scss file imports the code for each breakpoint involved in the design (including any beyond the limit imposed for legacy versions of IE) but nests them within the relevant CSS3 @media query. The compiled version of this file is served to all browsers apart from IE 6/7/8 and IEMobile.

// style.scss

@import "base";
@media (min-width:320px) {
    @import "320-up"; }
@media (min-width:480px) {
    @import "480-up"; }
@media (min-width:780px) {
    @import "780-up"; }
@media (min-width:960px) {
    @import "960-up"; }
@media (min-width:1100px) {
    @import "1100-up"; }

The resulting CSS files can then be referenced in the HTML. It is important to hide the ie.css file from any IE-based mobile browsers. This ensures that they do not download the CSS meant for desktop versions of IE.

<!--[if (gt IE 8) | (IEMobile)]><!-->
<link rel="stylesheet" href="/css/style.css">
<!--<![endif]-->

<!--[if (lt IE 9) & (!IEMobile)]>
<link rel="stylesheet" href="/css/ie.css">
<![endif]-->

This Sass-enabled approach works just as well if you need to serve a basic style sheet for mobiles without CSS3 Media Query support, and prevent those devices from downloading the CSS used to adapt the layout to wider viewports. For example, you can avoid importing base.scss into the ie.scss and style.scss files. It can then be referenced separately in the HTML.

<link rel="stylesheet" href="/css/base.css">
<link rel="stylesheet" href="/css/style.css" media="(min-width:320px)">

<!--[if (lt IE 9) & (!IEMobile)]>
<link rel="stylesheet" href="/css/ie.css">
<![endif]-->

You’ll notice that I didn’t wrap the style.css reference in a conditional comment to hide it from legacy versions of IE. It’s not necessary this time because the value of the media attribute is not understood by legacy versions of IE, and the style sheet will not be downloaded.

In different circumstances, different combinations of style sheets and media attribute values will be more appropriate.

Summary

Even if you want to don’t want to use any of the Sass or SCSS syntax, the pre-processor itself can help you to write your CSS in a “mobile first” manner (with multiple breakpoints), provide a “desktop” experience for IE 6/7/8, and avoid some of the performance or maintenance concerns that are sometimes present when juggling the two requirements.

I’m relatively new to using Sass, so there may be even better ways to achieve the same result or even to prevent the inclusion of IE-specific CSS unless the file is being compiled into a style sheet that only IE will download.




to

Moving from London to San Francisco

I recently moved from London to San Francisco to work at Twitter, as a Software Engineer. This is a rough guide – in the spirit of @chanian’s tutorial for Canadians – based on my experience of relocating, the mistakes I made along the way, and some information I wish I’d had. Use it at your own risk – don’t assume any legal truths; research things for yourself before making decisions!

I’m not going to cover anything about the US visa process. The company that has offered you employment in the US is likely to work with immigration lawyers who will handle (or guide you through) the visa application and processing. I’m also going to assume that your employer is providing temporary accommodation or that you are organising your own (e.g., via Airbnb) while you search for an apartment. Most of this article relates to things you will need to do once you arrive in San Francisco and soon after, but that you should spend some time thinking about beforehand.

Get a phone

You’ll need a US mobile/cell number pretty quickly, especially if you’re apartment-hunting.

The US telecom market isn’t great and will leave you nostalgic for the halcyon days of the EU-regulated, pro-consumer market you’ve left behind. For example, it’s now illegal to unlock a phone from a carrier unless you have that carrier’s permission to do so. Furthermore, if you do get a phone from a carrier (as part of your contract deal), you should be aware of whether or not you will be locked into a proprietary network, like Verison’s CDMA. Without a US credit history, you should expect to pay a sizable deposit when entering into a contract.

One way to reduce the cost of a phone contract is to bring your own phone to the party. If you bring a phone from the UK, make sure to check that your charger will work on US voltage. With an unlocked, GSM-supporting phone you can look to carriers like T-Mobile who offer various “value” and no-annual-contract plans. These prices are significantly cheaper because they don’t subsidise the purchase of a new phone. You’re likely to find “unlimited” data plans easier to come by than they are in the UK.

You’re shit-out-of-luck if you’re thinking you’d prefer a European-style pay-as-you-go (PAYG) approach. The options are thin on the ground. Any airtime you buy means just that – any time you spend talking or texting – so you pay to send and receive calls or SMS’s. My experience suggests that some networks recycle phone numbers or sell on your details. I still receive random texts addressed to previous owners of my phone number, and get messages from marketing companies who have miraculously acquired my personal details, an irritation that is compounded by the fact that it costs you money to be harassed.

If you’re determined to go the PAYG route, the nearest US equivalent is probably AT&T’s GoPhone SIM or Net10. You’ll have to purchase a phone and credit up front; top ups can be purchased in store, at some supermarkets, or done over the phone. This may also be the first time you encounter the US concept of a “restocking fee” – a method of dissuading you from returning items by charging you to do so. The restocking fee for the burner phone I first purchased was almost as much as the phone itself.

Open a bank account, transfer money

Make this a top priority. You should open a bank account as soon as you arrive in the US, especially as some banks will initially let you do so without a Social Security Number or permanent address.

Until you open a US bank account, you’ll be haemorrhaging money on fees levied by your UK bank for dollar transactions, and subject to poor exchange rates.

Choose a bank

San Francisco has a large range of different bank brands to choose from, but you’re probably best sticking to the big name banks that have branches and ATMs throughout the city, such as Bank of America, Chase, or Wells Fargo. There are co-ops and niche services if that’s your thing. Be sure to do some preparatory research on which bank is best suited to your needs. It’s also worth checking if your bank in the UK has a reciprocal agreement with any bank operating in San Francisco; it may cut down the cost of moving your money. Friends recommended going with either Bank of America or Chase. I went with Bank of America, where the customer service was personal and friendly.

Banking fees are a matter of course in the US. In contrast to the UK, you’ll almost certainly be charged for withdrawing money from any ATMs that aren’t owned by your bank. You have to buy cheque books (“check” in American English) and pay a fee to transfer your money to accounts outside your bank. Accounts usually involve a monthly fee, although this is waived in certain situations, such as setting up your salary to be directly deposited. Expect to set up a current (“checking”) and savings account, and to be asked to make a minimum cash deposit to complete the process (at Bank of America it was $100).

Once you’re all set up, your debit card will be sent in the post – so make sure you’ll be at that address for at least another week. In the meantime you may get a temporary cash card to get at what you’ve already deposited. Even if you transfer more money in, your bank can limit the amount you can withdraw within the first 30 days of the account being open – presumably to combat fraud/laundering.

Transfer money

It’s essential that you transfer money from your UK bank as soon as possible. There are many factors to consider when calculating how much money you want to transfer.

  • You may enter the US up to 10 days before your visa is valid and you can start work.
  • You need money for food, transport, going out, a phone (and deposit), apartment applications, an apartment deposit, buying furniture, etc.
  • You might not be able to get paid until you have a Social Security Number.
  • You’re unlikely to get paid until the middle or end of the month you start working.
  • You’re very likely to get your first pay cheque given to you as a real cheque; your bank is then likely to withhold the vast majority of the cheque’s value for up to 28 days.
  • It will cost you several thousand dollars – a deposit and at least one month of rent – to secure an apartment. In general, landlords will not accept a UK banking cheque.
  • You’ll have to buy furniture and general household items if you aren’t shipping any from the UK.

All in all, this means you may end up without any significant US-earned money in your account for 30-45 days while making some of the biggest expenses you’re likely to have made for a while.

Transferring money to a US bank account can be done online via wire transfer between banks. Unfortunately, my bank in the UK – Santander – didn’t allow online wire transfers so I had to look for alternatives. You may want to research this prior to leaving the UK!

The Post Office provide a simple, secure, and fee-free service, but a poorer exchange rate. Looking around, I came across Currencyfair – a peer-to-peer currency exchange service. They provide online quotes without the need to sign up, they were very prompt and helpful in their replies to questions I had, and the exchange rate was very good. Overall, I saved quite a bit of money and I’d rely on them in the future.

Get a Clipper card

The Clipper card is San Francisco’s equivalent of London’s Oyster card. Getting one will take some of the pain out of using the various modes of public transport in San Francisco. You can get a Clipper card online and I’d suggest setting up “Autoload” (you’ll need a bank account) to get the card for free and never worry about remembering to top up your credit. Alternatively, you can buy them on the high street from shops like Walgreens.

Get a Social Security Number

Social Security recommend that you only apply for a Social Security Number once you’ve been in the US over 10 days.

My experience was that the process is quick and simple. You complete a short SSN application form ahead of time and take it to the nearest Social Security office along with the documentation they advise you to bring. Arrive first thing in the morning to avoid any wait. It can take a few weeks for your Social Security card to arrive so you may want to have it sent to your employer’s address if you don’t have a permanent address yet.

Once you have your Social Security Card, you should keep it safe and be judicious in giving your SSN out. However, you should provide it to your bank and employer as soon as possible.

Find somewhere to live

Living in the city of San Francisco is just one of the (more expensive) options available to you. I chose to live in the city but many of my friends and colleagues live in other areas, like the East Bay. Have a look around before making up your mind.

Rent is very expensive in San Francisco, even compared to prices in London, especially since it’s very rare to find furnished accommodation. It also appears to be rising at a staggering rate. However, buildings constructed before June 1979 are covered by San Francisco Rent Control which heavily constrains the rate at which your rent can increase once you become a tenant. Therefore, it’s worth taking the time to find somewhere that you could imagine living for a few years.

The rental market is extremely competitive. Many places rely on one-off, brief, herd-style viewings where you’re in the apartment with half a dozen other desperate people at the same time, and more arriving every minute. People hand over all their paperwork and a cash application fee (if applicable) there and then.

Things are made slightly harder because you’re unlikely to have any US credit history, which is something quite important over here. But an offer letter and salary details from a tech company seems to put you in good shape. It’s in your best interest to put together a dossier of papers to provide alongside any application you make. You should include scans of your employer’s offer letter, your visa, and ideally character references from a previous landlord, etc. Print out several copies to take with you to viewings. You might have to pay $30-$40 to make an application (which is meant to cover credit history checks), but I never did.

I found that using Craigslist or a listing aggregator like Lovely was the best way to find apartments for rent in the city. They will also help you to narrow your focus to the neighbourhoods that you’re most interested in (spend some time learning about the city). Before moving to San Francisco, I heard a lot of stories about how it was essential – if you are to have any hope – to be “first” to make contact with the poster of a listing, but my experience was that you’re generally given the date and time of a mass-viewing to attend. This means that making a good impression in person, and having a bit of a chat with your potential landlord or building-manager, is likely to improve your chances and help you make a decision. Be prepared for it to take a while to find an apartment – it took me over a month of searching.

Once you’ve found a place to rent and signed all the paperwork, call PG&E to create an account to pay for your heat and electricity. You can set up e-bills and automatic payments online once your account has been processed. It’s a good idea to sort out an ISP before you move in – I went with Sonic.net. Again, the monthly cost (which I was told includes 17 different taxes and “renting” of the router) is a little higher than you’d expect in the UK, and you can expect to pay an installation fee. Other things to do: get Renters Insurance and have your bank automatically mail out your monthly-rent check to your landlord or building manager. All these things are quick and easy to do.

If you’re interested in your renters rights, you can search the California Department of Consumer Affairs for information.

Buying stuff for your place

You’re going to need furniture and basic household items. There’s always Ikea, which is located in Emeryville across the bay. If you have any previous Ikea experience, you’ll know that it’s one of the most stressful shopping experiences imaginable. The Ikea in Emeryville is even worse but the prices are pretty good. You can get there by bus from San Francisco and have large items delivered, or sort out your own transport.

Other stores to look at include West Elm and Crate & Barrel; they sell nicer things but are significantly more expensive. Alternatively, there are a lot of independent and second-hand furniture shops in San Francisco, particularly in the Mission district and a few along Van Ness. They’re well worth checking out. Van Ness also has 3 or 4 stores that sell mattresses – Sleep Train came particularly well recommended. I’d suggest that you leverage the lower costs of similar mattresses online in order to significantly reduce the price of your purchase, while benefiting from the great service, free delivery, and returns policy of the high-street stores. And if you have no idea what you’re doing: home decor tips, infographics, and cheat sheets

Get a California I.D.

Once you have your SSN and have found a permanent address, you should apply for a California I.D. at the DMV. This is handy if you don’t want to carry your passport (with visa) around and don’t have alternative I.D., such as a driver’s licence. You should register for an appointment to avoid a long wait in line. It can take up to 60 days for your California I.D. to arrive.

Get a credit card

The U.S. revolves around consumer credit. You need to start building up a credit history as soon as possible if you want to avoid paying large deposits or higher prices. Ask your bank about the soonest that you can apply for a credit card and then start using it – buying on credit even if you don’t need to.

Inform HMRC and the Student Loans Company

Once you’re settled, you should make time to inform HMRC that you’ve left the UK. They’ll be able to assess your tax status. If you are repaying student loans, after 3 months in the US you’re expected to contact the Student Loans Company by completing an overseas income assessment form. They will then work out your repayments.

Welcome to the United States of America

Hopefully you settle in within a couple of months and get to know San Francisco. There are many faces to this city, but the social scene is pretty diverse and there are many restaurants, bars, cafes, parks, and attractions – plenty of places to explore and things to do while you find your feet.




to

Custom CSS preprocessing

Did you know that you can build your own CSS preprocessor with Node.js libraries? They can be used alongside established preprocessors like Sass, and are useful for defining tasks beyond preprocessing.

Libraries like Rework and PostCSS let you create and assemble an arbitrary collection of plugins that can inspect or manipulate CSS.

At the time of writing, Twitter uses Rework to perform various tasks against our CSS source code for twitter.com.

Creating a CSS preprocessor with Rework

At its core, Rework is a module that accepts a string of CSS, produces a CSS abstract syntax tree (AST), and provides an API for manipulating that AST. Plugins are functions that have access to the AST and a Rework instance. Rework lets you chain together different plugins and generate a string of new CSS when you’re done.

The source string is passed into the rework function and each plugin is applied with .use(fn). The plugins transform the data in the AST, and .toString() generates the new string of CSS.

Below is an example of a custom preprocessor script using Rework and Autoprefixer. It’s a simplified version of the transformation step we use for twitter.com’s CSS.

var autoprefixer = require('autoprefixer');
var calc = require('rework-calc');
var rework = require('rework');
var vars = require('rework-vars')();

var css = fs.readFileSync('./css/main.css', 'utf-8');

css = rework(css)
  .use(vars)
  .use(calc)
  .toString();

css = autoprefixer().process(css);

fs.writeFileSync('./build/bundle.css', css)

The script runs rework-vars, rework-calc, and then passes the CSS to Autoprefixer (which uses PostCSS internally) to handle the addition of any necessary vendor prefixes.

rework-vars provides a limited subset of the features described in the W3C-style CSS custom property spec. It’s not a polyfill!

Variables can be declared as custom CSS properties on the :root element, prefixed with --. Variables are referenced with the var() function, taking the name of a variable as the first argument and an optional fallback as the second.

For example, this source:

:root {
  --width-button: 200px;
}

.button {
  width: var(--width-button);
}

yields:

.button {
  width: 200px;
}

There are many different Rework plugins that you can use to create a custom preprocessor. A more complete list is available on npm. In order to limit the chances of long-term divergence between our source code and native CSS, I’ve chosen to stick fairly closely to features that are aligned with future additions to native CSS.

Creating your own Rework plugin

Rework plugins are functions that inspect or mutate the AST they are provided. Below is a plugin that rewrites the value of any font-family property to sans-serif.

module.exports = function plugin(ast, reworkInstance) {
  ast.rules.forEach(function (rule) {
    if (rule.type != 'rule') return;

    rule.declarations.forEach(function (declaration, index) {
      if (declaration.property == 'font-family') {
        declaration.value = 'sans-serif';
      }
    });
  });
};

Rework uses css-parse to create the AST. Unfortunately, both projects are currently lacking comprehensive documentation of the AST, but it’s not difficult to piece it together yourself.

Beyond preprocessing

Since Rework and PostCSS expose an AST and provide a plugin API, they can be used for other CSS tasks, not just preprocessing.

At Twitter, our CSS build pipeline allows you to perform custom tasks at 2 stages of the process: on individual files and on generated bundles. We use Rework at both stages.

Individual files are tested with rework-suit-conformance to ensure that the SUIT-style CSS for a component is properly scoped.

/** @define MyComponent */

:root {
  --property-MyComponent: value;
}

.MyComponent {}

Bundles are preprocessed as previously described, and also tested with rework-ie-limits to ensure that the number of selectors doesn’t exceed IE 8/9’s limit of 4095 selectors per style sheet.

Other tasks you can perform include generating RTL style sheets (e.g., css-flip) and extracting detailed information about the perceived health of your CSS (e.g., the number of different colours used, duplicate selectors, etc.).

Hopefully this has given you a small glimpse into some of the benefits and flexibility of using these tools to work with CSS.




to

How to test React components using Karma and webpack

I’m working on a project at Twitter that uses React and webpack. After a few conversations with @sokra last year, this is the setup I put in place for testing React components (authored using JSX and ES6) using Karma.

Dependencies

You’ll need to install various packages. It looks like a lot of dependencies, but all the non-Karma packages will be necessary for general module bundling during development.

Full set of required packages:

webpack entry file

If you use webpack-specific features in your modules (e.g., loaders, plugins) you will need to use webpack to build a test bundle. The fastest and simplest approach is to create a single, test-specific entry file.

Create a file named tests.bundle.js. Within this file, you create a webpack context to match all the files that conform to a naming pattern – in this case *.spec.js(x).

var context = require.context('.', true, /.+.spec.jsx?$/);
context.keys().forEach(context);
module.exports = context;

Next, you point Karma to this file.

Karma config

Karma is configured using a karma.conf.js file. The browsers, plugins, and frameworks are specified in the standard way.

Point Karma at the tests.bundle.js file, and run it through the relevant preprocessor plugins (see example below).

The karma-webpack plugin relies on 2 custom properties of the Karma config: webpack and webpackMiddleware. The value of the former must be a webpack config object.

module.exports = function (config) {
  config.set({
    browsers: [ 'Chrome' ],
    // karma only needs to know about the test bundle
    files: [
      'tests.bundle.js'
    ],
    frameworks: [ 'chai', 'mocha' ],
    plugins: [
      'karma-chrome-launcher',
      'karma-chai',
      'karma-mocha',
      'karma-sourcemap-loader',
      'karma-webpack',
    ],
    // run the bundle through the webpack and sourcemap plugins
    preprocessors: {
      'tests.bundle.js': [ 'webpack', 'sourcemap' ]
    },
    reporters: [ 'dots' ],
    singleRun: true,
    // webpack config object
    webpack: {
      devtool: 'inline-source-map',
      module: {
        loaders: [
          {
            exclude: /node_modules/,
            loader: 'babel-loader,
            test: /.jsx?$/
          }
        ],
      }
    },
    webpackMiddleware: {
      noInfo: true,
    }
  });
};

Rather than duplicating your webpack config, you can require it in the Karma config file and override the devtool value to get sourcemaps working.

var webpackConfig = require('./webpack.config');
webpackConfig.devtool = 'inline-source-map';

module.exports = function (config) {
  config.set({
    ...
    webpack: webpackConfig
  });
};

That’s all you need to do to configure Karma to use webpack to load your JSX, ES6 React components.




to

Using canvas to fix SVG scaling in Internet Explorer

Internet Explorer 9–11 suffer from various bugs that prevent proper scaling of inline SVG’s. This is particularly problematic for SVG icons with variable widths. This is the canvas-based hack I’ve been using to work around the issue.

A popular way to use SVG icons is to generate a spritemap of SVG symbol‘s that you then reference from elsewhere in a document. Most articles on the topic assume your icon dimensions are uniformly square. Twitter’s SVG icons (crafted by @sofo) are variable width, to produce consistent horizontal whitespace around the vectors.

Most browsers will preserve the intrinsic aspect ratio of an SVG. Ideally, I want to set a common height for all the icons (e.g., 1em), and let the browser scale the width of each icon proportionally. This also makes it easy to resize icons in particular contexts – just change the height.

Unfortunately, IE 9–11 do not preserve the intrinsic aspect ratio of an inline SVG. The svg element will default to a width of 300px (the default for replaced content elements). This means it’s not easy to work with variable-width SVG icons. No amount of CSS hacking fixed the problem, so I looked elsewhere – and ended up using canvas.

canvas and aspect ratios

A canvas element – with height and width attributes set – will preserve its aspect ratio when one dimension is scaled. The example below sets a 3:1 aspect ratio.

<canvas height="1" width="3"></canvas>

You can then scale the canvas by changing either dimension in CSS.

canvas {
  display: block;
  height: 2rem;
}

Demo: proportional scaling of canvas.

Fixing SVG scaling in IE

This makes canvas useful for creating aspect ratios. Since IE doesn’t preserve the intrinsic aspect ratio of SVG icons, you can use canvas as a shim. A canvas of the correct aspect ratio provides a scalable frame. The svg can then be positioned to fill the space created by this frame.

The HTML is straightforward:

<div class="Icon" role="img" aria-label="Twitter">
  <canvas class="Icon-canvas" height="1" width="3"></canvas>
  <svg class="Icon-svg">
    <use fill="currentcolor" xlink:href="#icon-twitter"></use>
  </svg>
</div>

So is the CSS:

.Icon {
  display: inline-block;
  height: 1em; /* default icon height */
  position: relative;
  user-select: none;
}

.Icon-canvas {
  display: block;
  height: 100%;
  visibility: hidden;
}

.Icon-svg {
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
}

Setting the canvas height to 100% means it will scale based on the height of the component’s root element – just as SVG’s do in non-IE browsers. Changing the height of the Icon element scales the inner SVG icon while preserving its 3:1 aspect ratio.

Demo: proportional scaling of svg in IE.

Creating an Icon component

The hack is best added to (and eventually removed from) an existing icon component’s implementation.

If you’re generating and inlining an SVG spritemap, you will need to extract the height and width (usually from viewBox) of each of your icons during the build step. If you’re already using the gulp-svgstore plugin, it supports extracting metadata.

Those dimensions need to be set on the canvas element to produce the correct aspect ratio for a given icon.

Example React component (built with webpack):

import iconData from './lib/icons-data.json';
import React from 'react';
import './index.css';

class Icon extends React.Component {
  render() {
    const props = this.props;
    const height = iconData[props.name.height];
    const width = iconData[props.name.width];

    // React doesn't support namespaced attributes, so we have to set the
    // 'use' tag with innerHTML
    const useTag = `<use fill="currentcolor"
                      xlink:href="#icon-${props.name}">
                    </use>`;

    return (
      <span className="Icon">
        <canvas className="Icon-canvas"
          height={height}
          width={width}
        />
        <svg className="Icon-svg"
          dangerouslySetInnerHTML={{__html: useTag}}
          key={props.name}
        />
      </span>
    );
  }
}

export default Icon;

When I introduced this hack to a code base at Twitter, it had no impact on the the rest of the team or the rest of the code base – one of the many benefits of a component-based UI.




to

Odisha to expedite chariot construction for Rath Yatra

The Home Ministry had on Thursday allowed chariot construction with a condition that no religious congregation should take place around the Ratha Khala.




to

Coronavirus | Maharashtra adds 1,089 new cases; Mumbai’s death toll stands at 462

Of the 1,089 new cases, Mumbai accounted for 748, with a cumulative tally of 12,142. With 75 new cases, Pune district’s tally has risen to 2,537.




to

Bihar government to do random testing of migrants on arrival

TrueNat machines will be used for the first time in the State for virus screening




to

APMC market to shut down for a week

The Agriculture Produces Market Committee (APMC) in Navi Mumbai on Friday decided to shut all five markets — vegetables, fruits, masala, grain and oni




to

Teltumbde in judicial custody till May 22

A special National Investigation Agency (NIA) court on Friday extended the judicial custody of academician Dr. Anand Teltumbde, arrested on April 14 i




to

Coronavirus | 30 more test positive in J&K, cases mount to 823

Bandipora tops the list with 134 cases, followed by Srinagar at 129




to

Crime Branch busts cigarette, tobacco smuggling racket

Material brought illegally in vehicles that had permission to carry fruits and vegetables




to

Army will not be called into Mumbai, assures Uddhav Thackeray

In his address, CM says lockdown cannot go on forever




to

International experts to be consulted on Styrene gas leak at Visakhapatnam

The NCMC chaired by Cabinet Secretary Rajiv Gauba met on Friday to review the situation arising out of the gas leak




to

Odisha drafts more than 2 lakh people into COVID-19 workforce

8,023 doctors, 8,296 staff nurses, 4,105 paramedics and lab technicians have been identified as dedicated COVID-19 service providers




to

Participators in Nizamuddin event must undergo test




to

COVID19 positive goes up to 16




to

Strawberry cultivator’s hope blighted with frustration