James Reads

HomeBlog

Week of Dec 9th, 2018

  • Learning Rust: hash map lookup/insert pattern

    In Suricata we’re experimenting with implementing app-layer parser in Rust. See Pierre Chifflier’s presentation at the last SuriCon: [pdf]. The first experimental parsers will soon land in master.

    Read at 09:53 am, Dec 10th

  • My experience with toxic teams

    I've quit my job several different times without anything lined up because of the working environment. It is never on a whim or because of a single incident. It is the result of months of trying to make it work and realizing that I am only being set up to fail on purpose.

    Read at 09:52 am, Dec 10th

  • Why Tumblr Banning Adult Content Is a Serious Problem

    For many of us, Tumblr was the place that we first got to discover and share our fandoms, art, and identities. Though some of us may have migrated to other platforms, the site has thrived as a place for communities to come together and explore.

    Read at 09:50 am, Dec 10th

  • The CRISPR Baby Scandal Gets Worse by the Day

    Updated on December 4 at 10:55 a.m. ET. Before last week, few people had heard the name He Jiankui. But on November 25, the young Chinese researcher became the center of a global firestorm when it emerged that he had allegedly made the first CRISPR-edited babies, twin girls named Lulu and Nana.

    Read at 09:48 am, Dec 10th

  • The biggest lie we still teach in American history classes

    One of my favorite writers, Gore Vidal, once described his country as the United States of Amnesia. “We learn nothing because we remember nothing,” he wrote. Vidal’s point is simple enough: America’s concept of itself is shaped by mythology, not by facts.

    Read at 09:36 am, Dec 10th

  • The Secret Playbook NY State Senate Democrats Used To 'Wipe The Floor' With Republicans

    Democratic leaders’ scheme to “cut the head off the IDC snake” was not forged in a dark alleyway or an Italian restaurant, but over egg whites. It was May 2017 when Democratic powerbroker Sen.

    Read at 09:30 pm, Dec 9th

  • Rivera: New Version of Single Payer Bill Coming in January

    ICYMI: We spoke last night on CapTon to Sen.

    Read at 04:58 pm, Dec 9th

  • NYC May Pull The Plug On Cashless Restaurants, Retailers

    Dos Toros is among the cashless chains that would have to change its ways under proposed legislation from Council Member Ritchie Torres.

    Read at 08:04 am, Dec 9th

  • Pushing the Envelope on Rent Reform in Albany 2019

    Today, New Yorkers are living in an era of mass displacement due to the skyrocketing cost of rent. This makes it absolutely imperative for rent-stabilized tenants to maintain their rights and for these rights to be extended to tenants currently living without them.

    Read at 08:03 am, Dec 9th

  • On WordPress + Git – Make WordPress Core

    .page-header .entry-header Can you believe it – we’ve made it through a State of the Word without anybody asking “when is WordPress moving to Git/GitHub?” You may, however, have caught a brief mention of issue trackers in relation to the Triage Team focus for 2019. While it’s very important to make the distinction between Git the version control system (VCS) and GitHub the service, as the answer usually goes, it’s understandably a continued area of interest. Many parts of WordPress have been developed using GitHub as the central tool, along with countless plugins and themes and even the WordPress book. Here’s the tl;dr (but you should definitely keep reading after this): Changing things up doesn’t just mean “let’s make the GitHub mirror at WordPress/wordpress-develop the canonical and migrate Trac tickets over” – it means imagining what kind of change would be a net benefit to the core development process and eventually the entire .org ecosystem, and then finding the right tools to do it. To that end, there is a group of people including myself (@helen), @desrosj, and @omarreiss who have been and will continue to be doing more coordinated research and planning around tooling. There is no current planned timeline nor is this a priority on top of the projects already enumerated for 2019, but any potential tooling change is being evaluated as it potentially relates to those projects, especially if it can better support phase 2 of Gutenberg development and the Triage Team. This is not about chasing the latest and greatest or evangelizing a preference – it’s important to identify the goals we have for the project and what pain points we are experiencing. More specifically than “democratizing publishing”, in the core development process we should be aiming for diverse participation, a faster-but-steady pace of development, predictable and timely feedback cycles, and continuing to build user trust among users of all types. Recent pain points have been merges between branches (especially 5.0 back to trunk), JavaScript package updating, and continued participation when projects move from plugins and GitHub into core and Trac. Roughly, here are some early thoughts on various moving pieces and potential future improvements. Repositories and Workflows SVN repositories would need to remain, essentially flipping the mirroring process to go from Git -> SVN, making SVN (and Git) repos on .org read-only Should the core build process continue to be handled as-is or should we move to something like Travis? Integration of more automated testing – visual regression, end-to-end, accessibility, performance Identification of the ideal lifecycle of an issue and process for a pull/merge request – design, docs, review, testing, etc. Identification of contribution workflows (contributor documentation, Git branching methodology, etc.) Security tracking and releasing Issue Tracker Critical for a Triage Team to review existing issues and to remain active going forward Potential for the bulk triage process to include migration from Trac to another tracker Any issue migration should be determine on a case by case basis by the Triage Team in collaboration with component maintainers; the most automation that should happen is a tool that takes a list of Trac tickets and imports them elsewhere Issue import process needs to take commenter attribution into account Trac would remain in a read-only state How are reports generated and used (i.e. is the built-in filtering capability enough in a given tool or will we need something more robust to support workflows) Is the issue tracker still the best place for feature requests? Implementation of issue templates Identifying existing custom integrations and whether those problems still exist and still need to be solved after a move Broader Ecosystem (later / bigger question mark) Connectors from GitHub to .org plugin and theme repos (GitHub Actions-powered build+deploy) Automated testing – sniffers, Tide, unit tests, WP and PHP compat testing, Theme Check Aligning plugin and theme review teams #git, #trac, #triage .entry-content .entry-meta #post-## #comments Post navigation #nav-below Source: On WordPress + Git – Make WordPress Core

    Read at 11:01 am, Dec 10th

  • Updating the Minimum PHP Version – Make WordPress Core

    .page-header .entry-header For the millions of sites already running WordPress 5.0, 85% are using PHP 5.6 or above. We’ve also recently observed that showing notifications to encourage users to upgrade their PHP version has been very effective. Yoast SEO experimented with this last year, and found that site owners upgraded their PHP version at twice the rate than before they were showed the notification. In light of that, I’d like to propose that in April 2019, we bump the minimum PHP version requirement to be 5.6. Sites that choose to remain on 5.5 or below will still receive security updates and possibly bug fixes, but would not be able to upgrade to the latest major WordPress version until they upgraded to a supported version of PHP. Similarly, I’d like to propose that in April 2019, we bump the minimum MySQL version requirement to be 5.5. 98.5% of WordPress 5.0 sites are using MySQL 5.5 and above. Depending upon feedback and effectiveness, we can follow up by bumping the required PHP version to 7 as early as December 2019. .entry-content .entry-meta #post-## #comments Post navigation #nav-below Source: Updating the Minimum PHP Version – Make WordPress Core

    Read at 10:53 am, Dec 10th

  • Welcome to Our Modern Hospital Where If You Want to Know a Price You Can Go Fuck Yourself - McSweeney’s Internet Tendency

    December 6, 2018 Welcome to Our Modern Hospital Where If You Want to Know a Price You Can Go Fuck Yourself   Welcome to America General Hospital! Seems you have an oozing head injury there. Let’s check your insurance. Okay, quick “heads up” — ha! — that your plan may not cover everything today. What’s that? You want a reasonable price quote, upfront, for our services? Sorry, let me explain a hospital to you: we give you medical care, then we charge whatever the hell we want for it. If you don’t like that, go fuck yourself and die. Honestly, there’s no telling what you’ll pay today. Maybe $700. Maybe $70,000. It’s a fun surprise! Maybe you’ll go to the ER for five minutes, get no treatment, then we’ll charge you $5,000 for an ice pack and a bandage. Then your insurance company will be like, “This is nuts. We’re not paying this.” Who knows how hard you’ll get screwed? You will, in three months. Fun story: This one time we charged two parents $18,000 for some baby formula. LOL! We pull that shit all the time. Don’t like it? Don’t bring a baby, asshole. Oh, I get it: you’re used to knowing a clear price for products and services. The difference is that medicine is complicated and scary — unlike, say, flying hundreds of people in a steel tube across an ocean, or selling them a six-ounce hand-held computer that plays movies and talks to satellites. Anyway, no need to think this through rationally while you’re vulnerable, right? Your head is really gushing, ma’am. Sure we could start posting prices and discussing our costs, but then it turns into a public debate about transparency, and people get all huffy and self-righteous about $15 pills of Tylenol, $93 to turn on a single goddamned light, or $5,000 worth of sanitary gloves. We’d rather just mail you a bill later for $97,000, full of obscure medical codes you can’t understand. Oh, you like understanding things? Here, maybe this will help: Hit your head, and talk to a doctor for one minute? $2,500, you idiot. Want your pesky appendix out? That’ll probably be $33,611. Or it could be $180,000. Shrug. Don’t know. Don’t care. Need an hour in the ER? How does $15,000-$50,000, sound? Hint: we don’t give a piss how it sounds you stupid fucking helpless human wallet. Our medical system strikes you as “insane?” Well, you can’t do much about that now. Except of course to go fuck yourself. Yes, ma’am, as a matter of fact, we do have a special room where you can go fuck yourself. Yes, it does cost money to use the room, and no I cannot tell you how much. Want a hint? It’s between $1 and $35,000 per minute. Will you be reserving the go fuck yourself room? Oh, you think you think we’re cruel and illogical? Well, no one forced you to come here. It’s your decision, you head-injured meatball. Feel free to go out into the parking lot and just die. I suggest you do that out in section F. Try to lean your corpse against a light pole. Our dead body disposal fee is $3.75 and is not covered by your shitty, confusing, out-of-network medical plan. So, will you be dying in our parking lot today, you pathetic, impotent, walking insurance code? Okay, great! Your husband will get a bill for that soon, and if he doesn’t like it, he can fuck himself too.   Source: Welcome to Our Modern Hospital Where If You Want to Know a Price You Can Go Fuck Yourself – McSweeney’s Internet Tendency

    Read at 08:33 am, Dec 10th

Week of Dec 2nd, 2018

  • ‘Productive’ Talk, but No Deal Between Trump and Cuomo on Hudson Tunnel

    He made a video to show President Trump how a critical tunnel under the Hudson River is falling apart. He flew down to Washington to make his case in person — again. But Gov. Andrew M.

    Read at 03:31 pm, Dec 7th

  • DACA Has Not Been Saved—and It May Be in Its Last Days

    If you read headlines in the last month, you might think that the Deferred Action for Childhood Arrivals program, known as DACA, was in good shape.

    Read at 03:26 pm, Dec 7th

  • Families Are Still Being Separated at the Border, Months After “Zero Tolerance” Was Reversed

    The Trump administration has quietly resumed separating immigrant families at the border, in some cases using vague or unsubstantiated allegations of wrongdoing or minor violations against the parents, including charges of illegally re-entering the country, as justification.

    Read at 09:12 am, Dec 6th

  • Neo-Nazi Who Allegedly Killed Heather Heyer In Charlottesville Said 'It Doesn't Fucking Matter' That She Died

    James Alex Fields expressed remorse immediately after driving his car into protesters but then referred to Heather Heyer as "that one girl who died, or whatever.

    Read at 08:12 am, Dec 6th

  • 'On Call' Oral Sex, Destroyed Evidence and Other Findings From the Sexual Misconduct Investigation of Former CBS Boss Les Moonves

    Les Moonves, the former chairman and chief executive of CBS, is in deep shit. CBS’ board of directors hired a team of outside lawyers to look into the deluge of sexual misconduct allegations levied against him. And as the New York Times found out, the results aren’t pretty.

    Read at 07:06 pm, Dec 5th

  • France Faces a Typical Facebook Revolution

    The liberating role social networks played during the Arab Spring and the Russian protests of 2011 and 2012 was widely lauded.

    Read at 07:05 pm, Dec 5th

  • Developer On Call

    For the system at work, I am on call one week every seven weeks. For most of the past ten years, I have been on organized on call rotations for the systems I have been developing. I think being on call is a logical way of taking responsibility for your work. You also learn a lot from it.

    Read at 06:59 pm, Dec 5th

  • City unions say they dread impact of single-payer proposal in Albany

    Public-sector unions are gearing up to fight legislation that would establish New York State as the health insurance provider for all residents, worried the sweeping bill would curtail their benefits and negotiating power.

    Read at 06:49 pm, Dec 5th

  • The Digital Maginot Line

    There is a war happening. We are immersed in an evolving, ongoing conflict: an Information World War in which state actors, terrorists, and ideological extremists leverage the social infrastructure underpinning everyday life to sow discord and erode shared reality.

    Read at 09:22 am, Dec 5th

  • WordPress 5.0 Targeted for December 6, Prompting Widespread Outcry Ahead of WordCamp US

    During last week’s core dev chat, Matt Mullenweg urged developers to consider WordPress 5.0 as “coming as soon as possible.” Nevertheless, his decision to set Thursday, December 6, for the new release date has taken many by surprise.

    Read at 09:05 am, Dec 5th

  • Psychiatry

    This is not an anti-psychiatry video. However, I think my experiences suggest that there are reasons to be cautious about, for instance, over-diagnosis, and profit-oriented clinical research.BECOME MY PATRON: https://www.patreon.com/contrapointsDONATE: https://www.paypal.com/cgi-bin/webscr...SUBSCRI

    Read at 10:54 pm, Dec 4th

  • The Apocalypse | ContraPoints

    Is it hot in here or is the world just like this now?✿Patreon: https://www.patreon.com/contrapoints✿Donate: https://paypal.me/contrapoints✿Merch: https://www.teepublic.com/stores/cont...✿Subscribe: https://www.youtube.com/c/ContraPoints✿Live Stream Channel: https://www.youtube.com/c/Contra

    Read at 10:31 pm, Dec 4th

  • How Does React Tell a Class from a Function?

    But React itself cares about the difference! In both cases React’s goal is to get the rendered node (in this example, <p>Hello</p>). But the exact steps depend on how Greeting is defined.

    Read at 06:58 pm, Dec 4th

  • “When You Get That Wealthy, You Start to Buy Your Own Bullshit”: The Miseducation of Sheryl Sandberg

    The ongoing three-way public-relations car wreck involving Washington, Facebook, and Sheryl Sandberg, the company’s powerful C.O.O., begs a question of America’s esteemed managerial class.

    Read at 01:56 pm, Dec 4th

  • Joe Crowley’s Parting Shot: Ousted by Ocasio-Cortez, He Undermined Barbara Lee in House Leadership Race

    The election of Rep. Hakeem Jeffries as House Democratic Caucus chair on Wednesday represented a symbolic and substantive comeback for the wing of the party that had suffered a stunning defeat last June, when Rep. Joe Crowley was beaten by primary challenger Alexandria Ocasio-Cortez.

    Read at 09:24 am, Dec 4th

  • Hot Module Replacement for Gutenberg Blocks

    For a year now at Human Made we have taken a ‘Gutenberg-first’ approach, considering how the new block editor can be the core of the solutions we propose to our clients.

    Read at 09:15 am, Dec 4th

  • Sheryl Sandberg Asked for Soros Research, Facebook Acknowledges

    Sheryl Sandberg asked Facebook’s communications staff to research George Soros’s financial interests in the wake of his high-profile attacks on tech companies, according to three people with knowledge of her request, indicating that Facebook’s second in command was directly involved in the soc

    Read at 09:10 am, Dec 4th

  • Sheryl Sandberg Emailed Staff To Conduct Research On Billionaire George Soros

    While Facebook maintains that Sandberg was not directly involved in a public relations firm's opposition research on Soros, it now acknowledges that she did in fact request research on the billionaire.

    Read at 01:01 am, Dec 4th

  • Mic has laid off the majority of its staff

    Mic is laying off the majority off its staff while the digital publisher works on a deal to sell the remainder of its assets to Bustle Digital Group. Mic CEO Chris Altchek announced the layoffs at a staff meeting this morning. Until today the company had employed more than 100 people.

    Read at 12:55 am, Dec 4th

  • Three Remarkable Things About Michael Cohen's Plea

    Michael Cohen’s decision to plead guilty to lying to Congress on Thursday was remarkable for three reasons. The first was that Cohen walked into a Manhattan federal courtroom unannounced. He did it by surprise.

    Read at 12:54 am, Dec 4th

  • What Happened When A White Cop Decided Not to Shoot a Black Man

    Mader was born in Wheeling, West Virginia, but grew up in Weirton. He went to the local high school and loved his early childhood — mostly, he said, because he got to spend lots of it outdoors. He wrestled and played soccer.

    Read at 12:49 am, Dec 4th

  • Cohen Pleads Guilty and Details Trump’s Involvement in Moscow Tower Project

    VideoMichael Cohen, President Trump’s former lawyer, pleaded guilty to lying to Congress about plans to build a tower for Mr. Trump in Russia. The admission is the latest twist in the onetime Trump loyalist’s deteriorating relationship with the president.

    Read at 11:58 pm, Dec 3rd

  • Cohen pleads guilty in new deal with Mueller in Trump-Russia probe

    Michael Cohen, President Trump’s longtime fixer, former personal attorney and confidant, pleaded guilty on Thursday to lying to Congress about the Russia investigation in a new deal with special counsel Robert Mueller.

    Read at 07:50 pm, Dec 3rd

  • Nodejs C++/JS Boundary: Crossing The Rubicon

    Most articles about Nodejs internals always talk about the C++/JS boundary and crossing it sorta thing. But most don’t usually go in-depth to explain what crossing the C++/JS boundary really meant and what crossing it is all about.

    Read at 07:38 pm, Dec 3rd

  • Mass router hack exposes millions of devices to potent NSA exploit

    More than 45,000 Internet routers have been compromised by a newly discovered campaign that’s designed to open networks to attacks by EternalBlue, the potent exploit that was developed by, and then stolen from, the National Security Agency and leaked to the Internet at large, researchers said Wedn

    Read at 07:34 pm, Dec 3rd

  • The Socialist Memelords Radicalizing Instagram

    “I was raised by parents and society to think socialism was the worst possible thing,” she told me in a direct message on Instagram. However, like a growing number of millennials, the dominant pro-capitalist narrative left her feeling disillusioned.

    Read at 07:30 pm, Dec 3rd

  • Testing Your Frontend with Cypress.io Framework

    In a rush? Skip to Cypress tutorial. Modern JavaScript frameworks present an easier and more organized way to create web applications. However, they also add complexity that sometimes breaks things in a subtle yet impactful way.

    Read at 07:25 pm, Dec 3rd

  • Why are tech companies making custom typefaces?

    “More than graphic design, typography is an expression of technology, precision and good order. Typography is no longer concerned with meeting the lofty and difficult demands of art but with satisfying, formally and functionally, the everyday requirements of a craft.

    Read at 07:16 pm, Dec 3rd

  • Taking the Path of Least Resistance in Small Stakes Poker Tournaments

    Only around the top 5% of starting hands in poker are favorites to be the best hand on the flop. This range primarily consists of big pairs and big Ax hands. Maybe another 5% of hands are favorites to flop so much equity that you are indifferent to getting called when you continuation bet.

    Read at 06:39 pm, Dec 3rd

  • Walter Tine’s Poker Odyssey, Part 4

    Winter break was interminable, nearly a month without poker.

    Read at 06:35 pm, Dec 3rd

  • The Biggest Limitations of Shove/Fold Poker Analysis

    My background is in turbo single-table tournaments, so I’ll always have a soft spot for shove/fold poker. Anytime I start coaching a player in turbo formats, I always ensure that they know the shove/fold ranges very well.

    Read at 06:30 pm, Dec 3rd

  • Hack Education Weekly News

    Each week, I gather a wide variety of links to education and education technology articles. All this feeds the review I write each December on the stories we are told about the future of education. But I’m putting that project on pause while I write my book.

    Read at 06:27 pm, Dec 3rd

  • Why Do We Write super(props)?

    I heard Hooks are the new hotness. Ironically, I want to start this blog by describing fun facts about class components. How about that! These gotchas are not important for using React productively. But you might find them amusing if you like to dig deeper into how things work.

    Read at 09:22 am, Dec 3rd

  • Capitalism without Capital

    For most of the 20th century, the market leaders in corporate America were big corporations that spent large sums of money in tangible assets.  They built things like refineries, manufacturing plants, and stores.  Think of companies like Standard Oil, AT&T, Sears, and General Motors.

    Read at 09:19 am, Dec 3rd

  • var to JIT

    In our previous article we described how the browser uses CSS to render beautiful pixels to the user’s screen. Although modern CSS can (and should!) be used to create highly interactive user experiences, for the last mile of interactivity, we need to dynamically update the HTML document.

    Read at 09:16 am, Dec 3rd

  • Somali workers in Minnesota force Amazon to negotiate

    Soon after Hibaq Mohamed immigrated to Minneapolis from Kenya, where she had been living as a refugee, in 2016 she got a job at a new Amazon warehouse near the city. At first, she enjoyed packing boxes for delivery to consumers.

    Read at 09:09 am, Dec 3rd

  • There May Never Be a Better Time to Unionize Your Workplace. Do It Now

    Let me tell you something real: Organize. Unionize. Your workplace. Now. This is the absolute best set of economic conditions you could have to help you to do it. IT WILL ONLY GET HARDER FROM HERE. ACT NOW.

    Read at 09:05 am, Dec 3rd

  • ‘It’s still a blast beating people’: St. Louis police indicted in assault of undercover officer posing as protester

    When a judge acquitted a white St. Louis police officer in September 2017 for fatally shooting a young black man, the city’s police braced for massive protests. But St. Louis Metropolitan Police Department Officer Dustin Boone wasn’t just prepared for the unrest — he was pumped.

    Read at 09:04 am, Dec 3rd

  • Fuck Bosses, Long Live Unions

    The entire editorial staff of the digital media company Mic was unceremoniously laid off yesterday ahead of a likely sale to Bustle CEO Bryan Goldberg.

    Read at 01:12 pm, Dec 2nd

  • Donald Trump Gave Russia Leverage Over His Presidency

    Shortly after President Donald Trump was inaugurated, he gave a combative press conference at which he was asked by a reporter, “I was just hoping that we could get a yes or no answer on these questions involving Russia.

    Read at 01:07 pm, Dec 2nd

  • Averting Climate Catastrophe: What DSA Should Do

    The United Nations Intergovernmental Panel on Climate Change (IPCC) recently released a report stating that “limiting global warming to 1.

    Read at 01:05 pm, Dec 2nd

  • FOSS is free as in toilet

    I am a bit dissatisfied with the use of the Tragedy of the commons to represent issues with free and open source software development. It is not an abstract resource that can be depleted when overused. It is not magically maintained if left alone.

    Read at 12:59 pm, Dec 2nd

  • Front-End Developers Have to Manage the Loading Experience

    Web performance is a huge complicated topic. There are metrics like total requests, page weight, time to glass, time to interactive, first input delay, etc. There are things to think about like asynchronous requests, render blocking, and priority downloading.

    Read at 12:57 pm, Dec 2nd

  • Google employees sign letter against censored search engine for China

    Google’s plan for returning to China, which is known as Project Dragonfly and would reportedly allow the Chinese government to blacklist certain search terms and control air quality data, has garnered significant backlash internally since it was first reported on in August.

    Read at 12:26 pm, Dec 2nd

  • Google Shut Out Privacy and Security Teams From Secret China Project

    The secrecy surrounding the work was unheard of at Google. It was not unusual for planned new products to be closely guarded ahead of launch. But this time was different.

    Read at 12:24 pm, Dec 2nd

  • Rory Young Reveals Background, Details of $100K Isolation Prop Bet

    Some are fascinated, some are sickened, some think it impossible and some believe they could do it tomorrow.

    Read at 12:16 pm, Dec 2nd

  • Trump abruptly cancels planned Putin meeting

    US President Donald Trump on Thursday abruptly canceled his meeting with Russian President Vladimir Putin two days before they were scheduled to sit down on the sidelines of the G20 summit.

    Read at 12:13 pm, Dec 2nd

  • Uber's Arbitration Policy Comes Back to Bite It in the Ass

    Uber CEO Dara KhosrowshahiPhoto: Michele Tantussi (Getty)Over 12,000 Uber drivers found a way to weaponize the ridesharing platform’s restrictive contract in what’s possibly the funniest labor strategy of the year.But first: a bit of background. One of the more onerous aspects of the gig economy is its propensity to include arbitration agreements in the terms of service—you know, the very long document no one really reads—governing the rights of its workers. These agreements prohibit workers from suing gig platforms in open court, generally giving the company greater leverage and saving it from public embarrassment. Sometimes arbitration is binding; in Uber’s case, driver’s can opt out—but only within 30 days of signing, and very few seem to realize they have the option.Until an unfavorable U.S. Supreme Court ruling earlier this year, independent contractors often joined class-action lawsuits anyway, arguing (sometimes successfully) that they ought to have been classified as employees from the get-go. With that avenue of remuneration cut off, a group of 12,501 Uber drivers found a new option that hinges on the company’s own terms of service. While arbitrating parties are responsible for paying for their own attorneys, the terms state that “in all cases where required by law, the Company [Uber] will pay the Arbitrator’s and arbitration fees.”If today’s petition in California’s Northern District Court is accurate, those arbitration fees add up rather quickly.A group of 12,501 drivers opted to take Uber at its word, individually bringing their cases up for arbitration, overwhelming the infrastructure that’s meant to divide and conquer. “As of November 13, 2018, 12,501 demands have been filed with JAMS,” the notice states. (JAMS refers to the arbitration service Uber uses for this purpose.) Continuing on, emphasis ours: “Of those 12,501 demands, in only 296 has Uber paid the initiating filing fees necessary for an arbitration to commence [...] only 47 have appointed arbitrators, and [...] in only six instances has Uber paid the retainer fee of the arbitrator to allow the arbitration to move forward.” (Emphasis ours.)While a JAMS representative was not immediately available for comment, the cause of the holdup is Uber itself, according to the notice:Uber knows that its failure to pay the filing fees has prevented the arbitrations from commencing. Throughout this process, JAMS has repeatedly advised Uber that JAMS is “missing the NON-REFUNDABLE filing fee of $1,500 for each demand, made payable to JAMS.” JAMS has also informed Uber that “[u]ntil the Filing Fee is received we will be unable to proceed with the administration of these matters.We have no reason to assume this fee would be different based on the nature of each case, so some back-of-the-envelope math indicates the filings alone would cost Uber—a company that already loses sickening amounts of money—over $18.7 million. We’ve reached out to Uber for comment and to learn if they have an estimate of what that number would be after attorney fees and other expenses.About the authorBryan MenegusSenior reporter PGP Fingerprint: 1905 9104 D967 2EB7 C3F5 68F9 9108 1434 C917 C1B9Source: Uber&#8217;s Arbitration Policy Comes Back to Bite It in the Ass

    Read at 08:54 am, Dec 7th

  • Why You Should Never, Ever Use Quora – Waxy.org

    Yesterday, Quora announced that 100 million user accounts were compromised, including private activity like downvotes and direct messages, by a “malicious third party.” Data breaches are a frustrating part of the lifecycle of every online service — as they grow in popularity, they become a bigger and bigger target. Nearly every major online service has had a security breach: Facebook, Google, Twitter, Yahoo, Tumblr, Uber, Evernote, eBay, Adobe, Target, Twitter, and Sony all extensively leaked user data in the last few years. Security breaches like these are a strong argument for using a password manager, but not a compelling reason to avoid a service you love, unless you plan to quit the internet entirely. But this does seem like a good time to remind you of all the other reasons why you should never, ever use Quora. Hoarding Knowledge Four years ago, Eric Mill wrote about Quora’s tendency to hoard knowledge, and nothing’s changed since. According to their About page, “Quora’s mission is to share and grow the world’s knowledge.” With 300 million monthly users, and nearly 40 million questions asked so far, they’re doing a good job of growing the world’s knowledge, but a terrible job of sharing it. All of Quora’s value is derived from the answers provided by its users, and they go to great lengths to make a well-designed platform for finding and replying to questions. But they do everything they can to make sure you can’t get those contributions back out. Quora has: No public API. No backup or export tools. Restricted access to answers without an account. Blocked scrapers and unofficial APIs, and deleted questions related to scraping on their site. Contrast that with Q&#38;A competitors Stack Overflow and Stack Exchange, which offers an API, a wealth of user-made tools and support community for it, a powerful Data Explorer for querying and exporting data, a liberal crawling policy, and doesn’t attempt to hide questions and answers behind authentication. They even proactively upload anonymized data dumps of all user-contributed content to the Internet Archive for posterity under a Creative Commons license. Hell, even Ask MetaFilter lets you export your history, and that was mostly built by one person. Blocking Preservation If you want to be generous, you could argue that it’s not a priority for them to build features like an API or export tools, especially as they’re still struggling to make money. But for years, Quora has also explicitly forbidden the Internet Archive from indexing their site. This is what you’ll see if you try to find any Quora page in the Wayback Machine’s index. Quora could do literally nothing, and the Internet Archive would actively preserve the work of their millions of users for the future, but they’ve chosen to exclude their site from being archived. In their robots.txt file, they elaborate on why they block the Wayback Machine, claiming they do it to protect their writers. People share a lot of sensitive material on Quora – controversial political views, workplace gossip and compensation, and negative opinions held of companies. Over many years, as they change jobs or change their views, it is important that they can delete or anonymize their previously-written answers. We opt out of the wayback machine because inclusion would allow people to discover the identity of authors who had written sensitive answers publicly and later had made them anonymous, and because it would prevent authors from being able to remove their content from the internet if they change their mind about publishing it. As far as we can tell, there is no way for sites to selectively programmatically remove content from the archive and so this is the only way for us to protect writers. If they open up an API where we can remove content from the archive when authors remove it from Quora, but leave the rest of the content archived, we would be happy to opt back in. The Internet Archive is a historical archive of the public internet, and Quora asking for the ability to selectively modify their archives is absurd. An API like they’re suggesting would be ripe for abuse. The Internet Archive inadvertently acts as a contingency for every startup’s short-sighted business plan, disastrous pivots, or acquisitions gone awry. When you run a social platform with content generated by the community, you have a larger responsibility not to burn their collective work to the ground. Part of that responsibility is participating in the web, and giving back what you take from it. From the Wayback Machine’s FAQ: Why is the Internet Archive collecting sites from the Internet? What makes the information useful? Most societies place importance on preserving artifacts of their culture and heritage. Without such artifacts, civilization has no memory and no mechanism to learn from its successes and failures. Our culture now produces more and more artifacts in digital form. The Archive’s mission is to help preserve those artifacts and create an Internet library for researchers, historians, and scholars. Quora’s closure isn’t a remote, distant possibility, and as a collection of uniquely personal stories and knowledge, there’s a strong argument for preserving it. Most VC-funded social platforms eventually shutter, and in many cases, the only remnants left are what was saved by volunteer archivists and the Internet Archive. All of Quora’s efforts to lock up its community’s contributions make it incredibly difficult to preserve when they go away, which they someday will. If you choose to contribute to Quora, they’re actively fighting to limit future access to your own work. Burning It Down Nearly ten years after its founding, Quora’s long-term prospects are still uncertain. They’ve raised over $225 million in four rounds of funding, most recently an $85 million Series D in April 2017 at a $1.7 billion valuation. Their self-serve ad platform launched last year, but have yet to report earnings. This is the first time in its nine-year history it’s made any money at all, which is better than nothing, but the sustainability of its model is still a question mark. At some point, the investors who dumped a quarter billion dollars into it will want a return on that investment. Last year, founder Adam D’Angelo indicated they expect to eventually IPO. But market conditions, combined with the results of their ad platform, may force them in different directions — a pivot, merger, or acquisition are always a possibility. When Quora shuts down, and it will eventually shut down one day, all of that collected knowledge will be lost unless they change their isolationist ethos. Back in 2012, Adam D’Angelo wrote, “We hope to become an internet-scale Library of Alexandria.” As long as Quora keeps boarding up the exits, we may see it end the same way. Source: Why You Should Never, Ever Use Quora – Waxy.org

    Read at 03:29 pm, Dec 6th

  • Why last night's surprise announcement of WordPress 5.0 was a concerning decision by Matt Mullenweg | Davis Shaver

    Last night around 8:30pm, Matt Mullenweg posted to WordPress’ Make blog that WordPress 5.0 would be released December 6, just two days from now. The decision contradicts earlier guidance issued by release lead Gary Pendergast, an Automattic employee. In an October blog post, Pendergast proposed a November 19 release date, with an additional caveat: We know there is a chance that 5.0 will need additional time, so these dates can slip by up to 8 days if needed. If additional time beyond that is required, we will instead aim for the following dates: Secondary RC 1: January 8, 2019Secondary Release: January 22, 2019 Pendergast confirmed on Slack that the intent was to avoid shipping during the holiday season. The current release date is November 19, but it can be pushed as late as November 27 if needed. To avoid the numerous holidays from the end of November through to January, we’ll move the release to January if more time is needed. Based on this, last night’s announcement seems totally out of left field. But a close reading of Matt Mullenweg’s Slack message over the past few weeks suggests that he was well aware that his plan differed from publicly available guidance. We didn’t know exactly what that would mean until last night though. In response to a November 28th question from Ben Keith about the apparent change of plans, Matt had demurred, saying simply that the earlier plan of avoiding December, “was based on the best information available at that time.” It is not clear what information changed regarding Pendergast’s avowed intent of avoiding the holiday season. If anything, it seems that Matt’s opinion changed, with him becoming more comfortable about the idea of a December release. In that November 28 chat, Matt expressed frustration with having to listen to feedback in public, instead preferring private video chats. these discussions are extremely hard to have in this forum because people bring lots of different personal, company, even vacation-related issues we aren’t deciding release dates for WP based on what a few dozen people in a Slack channel complain the loudest about Matt Mullenweg in Slack That November 28 conversation marks the last time that a release date was meaningfully discussed in the #core channel. Many expect that the release is meant to be done in time for WordCamp US, taking place this weekend in Nashville. Travel and other obligations related to WordCamp US are another major complicating factor that ecosystem companies have faced in preparing for the release. As Yoast SEO founder Joost de Valk explained in Slack this morning, Well my main reason for being annoyed is the fact that we’re proving our official announcements have no merit. If we weren’t planning on doing January, why’d we say so? If we said we’d skip December, why don’t we? My main concerns are about disrespect for the community. Not even readiness. As Daniel Bachhuber responded to Joost in regards to the disrespect for the community, I think a lot of community trust has been lost in the last few weeks. I don’t know what the longer-term ramifications are. WebDevStudios head Brad Williams offered his own take The most jarring thing about the Gutenberg release on Thursday is that there was zero public discussion about it. Wasn’t mentioned in the official WordPress #core slack and a number of WP Core Devs were unaware. Any non-Automatticians involved? Opposite of an open source project.— Brad Williams (@williamsba) December 4, 2018 WordPress has been built on respect for its users and backwards compatibility for many years. Rushed and clandestine decision-making contravenes those values. In addition to legitimate resource allocation issues, there also remain significant accessibility gaps with Gutenberg. As developer Luke Pettway commented on the blog post, If something isn’t accessible it isn’t innovative. The WordPress community deserved a formal opportunity to provide input once more on a release decision based on the current state of the software, and it deserved more than a couple days of leeway to the biggest WordPress release since 3.0. I am extremely excited for Gutenberg but I wish deeply that it’s launch were being handled with greater empathy and care. Your ad blocker is on.Read ad free. Sign up for our e-mail newsletter: OR Source: Why last night&#8217;s surprise announcement of WordPress 5.0 was a concerning decision by Matt Mullenweg | Davis Shaver

    Read at 04:17 pm, Dec 5th

  • PETA Compares 'Anti-Animal' Language to Racism and Homophobia

    Photo: iStockPeople for the Ethical Treatment of Animals wants you to know that if you say things like “Don’t beat a dead horse,” it’s the exact same thing as calling a black person the n-word.In the whitest, dumbest, most clueless and socially irresponsible tweet ever, PETA likened what they call “speciesism” or “anti-animal” language to using racist epithets like “nigger” or homophobic language like “faggot.”“Words matter, and as our understanding of social justice evolves, our language evolves along with it. Here’s how to remove speciesism from your daily conversations,” the organization wrote.The tweet was accompanied by a colorful chart that gave examples of what they consider to be anti-animal language along with suggestions for substitutions people can make to remove “speciesism” from their lives.They followed up with a second tweet that said, “Just as it became unacceptable to use racist, homophobic, or ableist language, phrases that trivialize cruelty to animals will vanish as more people begin to appreciate animals for who they are and start ‘bringing home the bagels’ instead of the bacon.”OK, PETA.I get it. You want us to stop eating bacon (we won’t). You want us to stop eating burgers (we won’t). You want to protect animals and sometimes you go to extremes to make your point.This ain’t it.How dare you even imply that “speciesism” is comparable to the racist language and its ties to racism? Are you saying you think being a meat eater is the same as being a racist? Are you fucking kidding?It is utterly and egregiously offensive to make the comparison you have made. Racist language is inextricably tied to racism, racial terrorism and racial violence. No matter how you try to twist it, it is not the same thing as using animals in a turn of phrase or enjoying a BLT.And as far as the so-called “evolution” of the meaning of “social justice,” please stop this. You don’t get to try to co-opt a phrase that represents movements across the globe to liberate, uplift and free oppressed people and liken it your crusade to stop people from eating carnitas tacos every Tuesday. That too is egregiously offensive. I don’t know what is going on with you, PETA. The way you keep amplifying your hyperbole in defense of protecting animals is bordering on hysterical propaganda at this point.Do better.Just like you came up with this nifty little chart of other phrases people can use so as to not offend your delicate sensitivities, find another way to categorize your movement that doesn’t erase already marginalized people doing their own work to remove oppression.I have linked a plethora of stories below so that you can understand what true social justice is. I suggest someone from your organization read them and learn something.In the meantime, stop being ridiculous.About the authorMonique Judge#TheRootAfterDark Columnist and News Writer for The Root. I said what I said. Period. Source: PETA Compares &#8216;Anti-Animal&#8217; Language to Racism and Homophobia

    Read at 04:05 pm, Dec 5th

  • Cardi B announces breakup with Offset - CNN

    The 25-year-old rapper posted a 42-second video on her Instagram account early Wednesday morning announcing the split. "So, everybody been bugging me and everything. And you know, I been trying to work things out with my baby father for a hot minute now," she said. "And we're really good friends and you know we're really good business partners and you know, he's always somebody that I run to, to talk to and we got a lot of love for each other, but things just haven't been working out between us for a long time," she added. Cardi went on to say, "And it's nobody's fault. It's just like I guess we grew out of love. But we're not together anymore. I don't know it might take time to get a divorce. And I'm going to always have a lot of love for him because he is my daughter's father and yeah."CNN has reached out to Cardi B's representatives for comment.Cardi and fellow rapper Offset, a member of hip-hop trio Migos, secretly married last September at their home in Atlanta. The couple welcomed their daughter, Kulture Kiari Cephus, in July. CNN's Lisa Respers France contributed to this report.Source: Cardi B announces breakup with Offset &#8211; CNN

    Read at 03:55 pm, Dec 5th

  • Interface vs Type alias in TypeScript 2.7 – Martin Hochel – Medium

    Why have I been blocked? This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data. Source: Interface vs Type alias in TypeScript 2.7 – Martin Hochel – Medium

    Read at 11:56 am, Dec 5th

  • Too Much Accessibility | CSS-Tricks

    By Chris Coyier On December 3, 2018 accessibility, semantics I like to blog little veins of thought as I see them. We recently linked to an article by Facundo Corradini calling out a tweet of ours where we used an &#60;em&#62; where we probably should have used an &#60;i&#62;. Bruce Lawson checks if screen readers are the victims of these semantic mistakes... Whenever I read “some browsers” or “some screenreaders”, I always ask “but which ones?”, as did Ilya Streltsyn, who asked me “what is the current state of the text-level semantics in HTML reality?” Léonie Watson to the rescue! Over Twitter, Watters wrote Most are capable of reporting these things on demand, but do not as standard. So you don’t hear the text/font characteristics being announced as you read, but you can query a character/word etc. to discover its characteristics. This is based on the visual presentation of the text though, rather than through any recognition of the elements themselves Which I suppose is to say that if you're really fretting about screen readers misinterpreting the nuanced usage of your semantic emphasis... you can relax on that one. Bruce's article led me toward Steve Faulkner's article "Screen Readers lack emphasis" from 2008. Using the semantic elements strong and em does not convey any useful information to users of JAWS or Window Eyes under typical browsing conditions. While it is good to know this, it is not a reason to not use these elements to convey meaning. Accessibility is not just about people with vision impairment, it’s about all user’s with disabilities, and web standards is not just about accessibility. So, not much has changed there in a decade. It's unclear to me if things should change here or not, but if virtual voices are improving, it stands to reason they could get better at voice inflections that convey emphasis. I certainly am thinking of voice emphasis when I write those HTML tags. This idea of too much accessibility has been a bit of a theme. Please don't read this article as suggesting that we worry too much about accessibility — only that it's possible to worry about the wrong things and even screw up accessibility in the process, just like anything else. Related Source: Too Much Accessibility | CSS-Tricks

    Read at 08:09 am, Dec 5th

  • What's Going to Happen to React Context? | Buttondown

    With the cool new stuff coming to React (Hooks/Suspense), what's going to happen to the context api? Earlier this year, the React team introduced the first...Source: What&#8217;s Going to Happen to React Context? | Buttondown

    Read at 08:06 am, Dec 5th

  • Why Do React Elements Have a $$typeof Property? | Overreacted

    You might think you’re writing JSX: But really, you’re calling a function: And that function gives you back an object. We call this object a React element. It tells React what to render next. Your components return a tree of them. If you used React you might be familiar with type, props, key, and ref fields. But what is $$typeof? And why does it have a Symbol() as a value? That’s another one of those things that you don’t need to know to use React, but that will make you feel good when you do. There’s also some tips about security in this post that you might want to know. Maybe one day you’ll write your own UI library and all of this will come in handy. I certainly hope so. Before client-side UI libraries became common and added basic protection, it was common for app code to construct HTML and insert it into the DOM: That works fine, except when your message.text is something like '&#60;img src onerror="stealYourPassword()"&#62;'. You don’t want things written by strangers to appear verbatim in your app’s rendered HTML. (Fun fact: if you only do client-side rendering, a &#60;script&#62; tag here wouldn’t let you run JavaScript. But don’t let this lull you into a false sense of security.) To protect against such attacks, you can use safe APIs like document.createTextNode() or textContent that only deal with text. You can also preemptively “escape” inputs by replacing potentially dangerous characters like &#60;, &#62; and others in any user-provided text. Still, the cost of a mistake is high and it’s a hassle to remember it every time you interpolate a user-written string into your output. This is why modern libraries like React escape text content for strings by default: If message.text is a malicious string with an &#60;img&#62; or another tag, it won’t turn into a real &#60;img&#62; tag. React will escape the content and then insert it into the DOM. So instead of seeing the &#60;img&#62; tag you’ll just see its markup. To render arbitrary HTML inside a React element, you have to write dangerouslySetInnerHTML={{ __html: message.text }}. The fact that it’s clumsy to write is a feature. It’s meant to be highly visible so that you can catch it in code reviews and codebase audits. Does it mean React is entirely safe from injection attacks? No. HTML and DOM offer plenty of attack surface that is too difficult or slow for React or other UI libraries to mitigate against. Most of the remaining attack vectors involve attributes. For example, if you render &#60;a href={user.website}&#62;, beware of the user whose website is 'javascript: stealYourPassword()'. Spreading user input like &#60;div {...userData}&#62; is rare but also dangerous. React could provide more protection over time but in many cases these are consequences of server issues that should be fixed there anyway. Still, escaping text content is a reasonable first line of defence that catches a lot of potential attacks. Isn’t it nice to know that code like this is safe? Well, that wasn’t always true either. And that’s where $$typeof comes in. React elements are plain objects by design: While normally you create them with React.createElement(), it is not required. There are valid use cases for React to support plain element objects written like I just did above. Of course, you probably wouldn’t want to write them like this — but this can be useful for an optimizing compiler, passing UI elements between workers, or for decoupling JSX from the React package. However, if your server has a hole that lets the user store an arbitrary JSON object while the client code expects a string, this could become a problem: In that case, React 0.13 would be vulnerable to an XSS attack. To clarify, again, this attack depends on an existing server hole. Still, React could do a better job of protecting people against it. And starting with React 0.14, it does. The fix in React 0.14 was to tag every React element with a Symbol: This works because you can’t just put Symbols in JSON. So even if the server has a security hole and returns JSON instead of text, that JSON can’t include Symbol.for('react.element'). React will check element.$$typeof, and will refuse to process the element if it’s missing or invalid. The nice thing about using Symbol.for() specifically is that Symbols are global between environments like iframes and workers. So this fix doesn’t prevent passing trusted elements between different parts of the app even in more exotic conditions. Similarly, even if there are multiple copies of React on the page, they can still “agree” on the valid $$typeof value. What about the browsers that don’t support Symbols? Alas, they don’t get this extra protection. React still includes the $$typeof field on the element for consistency, but it’s set to a number — 0xeac7. Why this number specifically? 0xeac7 kinda looks like “React”.Source: Why Do React Elements Have a $$typeof Property? | Overreacted

    Read at 07:05 pm, Dec 4th

  • NPC Minutes July 5, 2018 - Democratic Socialists of America (DSA)

    The NPC held a phone meeting July 5, 2018 on the new member surge after Alexandria Ocasio-Cortez’s win and electoral strategy for the 2018 midterms. You can find the minutes here.Source: NPC Minutes July 5, 2018 &#8211; Democratic Socialists of America (DSA)

    Read at 06:42 pm, Dec 4th

  • ‘Must be willing to work under pressure’ is a warning sign

    As a programmer looking for a job, you need to be on the lookout for badly managed companies. Whether it’s malicious exploitation or just plain incompetence, the less time you waste applying for these jobs, the better. Some warning signs are subtle, but not all. One of the most blatant is a simple phrase: “must be willing to work under pressure.” The distance between we and you Let’s take a look at some quotes from real job postings. Can you spot the pattern? “Ability to work under pressure to meet sometimes aggressive deadlines.” “Thick skin, ability to overcome adversity, and keep a level head under pressure.” “Ability to work under pressure and meet tight deadlines.” “Willing to work under pressure” and “working extra hours if necessary.” If you look at reviews for these companies, many of them mention long working hours, which is not surprising. But if you read carefully there’s more to it than that: it’s not just what they’re saying, it’s also how they’re saying it. When it comes to talking about the company values, for example, it’s always in the first person: “we are risk-takers, we are thoughtful and careful, we turn lead into gold with a mere touch of our godlike fingers.” But when it comes to pressure it’s always in the second person or third person: it’s always something you need to deal with. Who is responsible for the pressure? It’s a mysterious mystery of strange mystery. But of course it’s not. Almost always it’s the employer who is creating the pressure. So let’s switch those job requirements to first person and see how it reads: “We set aggressive deadlines, and we will pressure you to meet them.” “We will say and do things you might find offensive, and we will pressure you.” “We set tight deadlines, and we will pressure you to meet them.” “We will pressure you, and we will make you work long hours.” That sounds even worse, doesn’t it? Dysfunctional organizations (that won’t admit it) When phrased in the first person, all of these statements indicate a dysfunctional organization. They are doing things badly, and maybe also doing bad things. But it’s not just that they’re dysfunctional: it’s also that they won’t admit it. Thus the use of the second or third person. It’s up to you to deal with this crap, cause they certainly aren’t going to try to fix things. Either: Whoever wrote the job posting doesn’t realize they’re working for a dysfunctional organization. Or, they don’t care. Or, they can’t do anything about it. None of these are good things. Any of them would be sufficient reason to avoid working for this organization. Pressure is a choice Now, I am not saying you shouldn’t take a job involving pressure. Consider the United States Digital Service, for example, which tries to fix and improve critical government software systems. I’ve heard stories from former USDS employees, and yes, sometimes they do work under a lot of pressure: a critical system affecting thousands or tens of thousands of people goes down, and it has to come back up or else. But when the USDS tries to hire you, they’re upfront about what you’re getting in to, and why you should do it anyway. They explain that if you join them your job will be “untangling, rewiring and redesigning critical government services.”. Notice how “untangling” admits that some things are a mess, but also indicates that your job will be to make things better, not just to passively endure a messed-up situation. Truth in advertising There’s no reason why companies couldn’t advertise in the some way. I fondly imagine that someone somewhere has written a job posting that goes like this: “Our project planning is a mess. We need you, a lead developer/project manager who can make things ship on time. We know you’ll have to say ‘no’ sometimes, and we’re willing to live with that.” Sadly, I’ve never actually encountered such an ad in the real world. Instead you’ll be told “you must be able to work under pressure.” Which is just another way of saying that you should find some other, better jobs to apply to. Every painful failure taught me a lesson—but only after it was too late.Source: ‘Must be willing to work under pressure’ is a warning sign

    Read at 06:38 pm, Dec 4th

  • Making It Look Easy, Ocasio-Cortez Shuts Down Huckabee Family of Liars and Promotes Green New Deal in 54-Word Tweet

    Once again demonstrating her ability to use social media to simultaneously expose the lies of right-wing critics and clearly articulate a bold progressive agenda, Rep.-elect Alexandria Ocasio-Cortez (D-N.Y.) quickly disposed of former Arkansas Gov. Mike Huckabee's false claim that she compared her election victory to the moon landing, noting that she was actually referring to the "level of ambition" and "innovation" that will be necessary to implement a Green New Deal and confront the global climate crisis. "Leave the false statements to Sarah Huckabee," Ocasio-Cortez wrote, referring to President Donald Trump's press secretary and the former governor's daughter. "She's much better at it." A Green New Deal will take a level of ambition + innovation on the scale of the moon landing. We’ve been done it before, and can do it again. Leave the false statements to Sarah Huckabee. She’s much better at it. Also, you haven’t been a Governor of any state for 10+ years now. https://t.co/R7q5CkMw8Y — Alexandria Ocasio-Cortez (@Ocasio2018) December 3, 2018 The remarks Huckabee and right-wing publications seized upon and quickly took out of context came during a Capitol Hill press conference on Friday, during which Ocasio-Cortez said a Green New Deal is achievable because the United States has previously "done what we thought was impossible." "We went to the moon. We electrified the nation. We established civil rights. We enfranchised the country. We dig deep, and we did it," Ocasio-Cortez said. "We did it when no one else thought that we could. That's what we did when so many of us won an election this year." Following the press conference, Fox News host Sean Hannity tweeted out an article from his website headlined, "LUNAR LUNACY: Cortez Compares Her 2018 Election with the MOON LANDING, 'Establishing Civil Rights.'" In response, Ocasio-Cortez wrote: "Actually, we compared the effort of a Green New Deal to these movements because that is the scale of ambition, social justice, and organizing it will take to save our planet." The newly elected democratic socialist went on to urge people to tune in to Monday's climate town hall, where she will appear alongside Sen. Bernie Sanders (I-Vt.) and environmental experts to discuss the necessity of bold solutions like the Green New Deal to avert planetary catastrophe. Source: Making It Look Easy, Ocasio-Cortez Shuts Down Huckabee Family of Liars and Promotes Green New Deal in 54-Word Tweet

    Read at 06:23 pm, Dec 4th

  • You Can Stop Tweeting the NYTimes' Bari Weiss, Eve Peyser Thing

    Photo: GettyIf you’ve been online today (God help you) perhaps you’re aware that a piece masquerading as critical discourse—while really just being a coming together of two oversized egos—ran in the newspaper of record. In other news, it’s a day ending in y.Lord alive, online has been bad: media types justifying their friendships with people whose politics support atrocities at home and abroad, justifying why they’re not friends with those types, and wringing hands about whether they have the right friends at all.The moment is ripe for a reminder: No one cares about the machinations of media people. From the inside, it can be easy to conflate “Everyone on my Twitter feed is talking about this” with “This is important and normal people care.” The overlap here is slim, and it contains zero stories about media personalities jerking each other off.My final piece of advice, today and always: You absolutely do not have to tweet about this. You don’t need to have a measured take—or any public-facing take at all. Before you send a tweet, think to yourself: Why am I doing this? Interrogate why you’re posting about a thing we could all ignore. You will find yourself posting far less, and you’ll be all the better for it.Source: You Can Stop Tweeting the NYTimes&#8217; Bari Weiss, Eve Peyser Thing

    Read at 04:05 pm, Dec 4th

  • Hey WordPress Plugin Developers: Are Your Plugins Really Ready for Gutenberg?

    WordPress 5.0 is right around the corner with the flagship feature, the new Gutenberg editor, set to change the WordPress landscape dramatically. Gutenberg not only impacts how you write content in WordPress, but how developers build plugins for WordPress. Here at Delicious Brains we are working hard on the next version of our plugins, including making sure they are Gutenberg-compatible, but after chatting about Gutenberg the other day I thought it was high time I made sure my own plugins worked with the new editor as well. In this post I’ll walk you through the process I took for making Intagrate, my Instagram WordPress plugin, Gutenberg-compatible, which will hopefully get you started on making your own plugins Gutenberg-ready. Things to Consider Although there is a way to completely disable Gutenberg on sites by using the Classic Editor plugin, if your own plugin is used on sites you don’t control (very likely if the plugins are sold or available on the WordPress plugin repository) then you will need to ensure it still functions a s expected with Gutenberg. There is also no guarantee that Classic Editor will be around in the future. Plugins can widely differ in functionality and how they integrate with WordPress, and for a large number, I would expect Gutenberg to have little to no effect. For example, through extensive testing we found that Gutenberg has no apparent impact on how WP Offload Media works because it primarily deals with media uploads behind the scenes. (Okay, maybe just one issue with admin notices.) However, as Gutenberg stores its data in the post_content column of the posts table, we had to make sure WP Migrate DB Pro still handles the find and replace of URLs and paths within Gutenberg block data – which it does without any trouble 💪. However, there are a number of key areas of functionality that Gutenberg does have an impact on, so if your plugin has or uses them you should definitely read on. These areas include but aren’t limited to: Custom Post Types Custom Meta Boxes TinyMCE buttons or integration Testing Plugins with Gutenberg I would recommend doing any testing on a local development environment or a staging site, with a WordPress site that you don’t mind trying things out/breaking things on. To get the site running the new Gutenberg editor you’ve got two choices: Install the standalone Gutenberg plugin on a site running WordPress 4.9.x or earlier, or Get the site running the latest release candidate of WordPress 5.0. Although the Core development team are keeping all Gutenberg changes up-to-date across the plugin and the release branch, I’m personally using the WordPress 5.0 release candidate (RC1 at the time of writing) for my test site. It can be downloaded as a zip, or installed using the Beta Testing plugin. The ‘bleeding edge nightlies’ is the option you need: Once WordPress has been updated you should see the brand-new-yet-to-be-released splash page: Which means our Gutenberg test site is ready to go. Essential Plugin Maintenance for Gutenberg Compatibility Now that our test site is running the new Gutenberg editor it’s time to check if your plugin plays nice with it. It’s worth making it clear that the majority of this post is about making your plugin continue to work with Gutenberg as is, with the bare minimum effort. I will touch on making enhancements and deeper integrations later on in the post. Custom Post Types If your plugin registers custom post types then, like me, you will be pleasantly surprised to see that when you go to edit one of the posts it might still load the classic editor. This is more by luck than design. As it stands in WordPress currently, as Gary Pendergast explains, post types will only use the Gutenberg editor if: When registered (or using add_post_type_support()) declare that they support the ‘editor’ feature. When registered, set their show_in_rest setting to true (the default is false). But wait, my custom post declares support for ‘editor’ because I want users to add content with the old editor – the classic editor. But now ‘editor’ means the new block editor Gutenberg. Confused? Me too. The only reason the post type is using the classic editor still is because it was registered without the show_in_rest argument. The code was first written before the REST API existed and it has never needed to be exposed to the API. Therefore show_in_rest will default to false and Gutenberg won’t be loaded. However, as this trac ticket highlights, this behavior might not be the case forever so it’s worthwhile implementing a longer-term fix. To ensure the post type always uses the classic editor (while that’s still a thing), we can use a new filter: function igp_post_type_filter( $use_block_editor, $post_type ) { if ( 'instagrate_pro' === $post_type ) { return false; } return $use_block_editor; } add_filter( 'use_block_editor_for_post_type', 'igp_post_type_filter', 10, 2 ); The handling of custom meta boxes in the Gutenberg editor has come under some criticism due to the assumption that all meta boxes are compatible with Gutenberg unless told otherwise. This ‘opt-out not opt-in’ approach is problematic as it means when WordPress 5.0 drops, all custom meta boxes will be loaded on the block editor, ready or not. This will be fine for simple boxes, but anything really custom could break. The best course of action is to ensure the meta box works with Gutenberg, or better still convert it to a block (I’ll come to that), but if you can’t then you need to disable it for the block editor. The last parameter of the add_meta_box() function called $callback_args accepts an array of data which is sent to the meta box callback, and now accepts __block_editor_compatible_meta_box. When this is set to false the meta box will be turned off for the block editor: add_meta_box( 'igp_links', __( 'Useful Links', 'instagrate-pro' ), array( $this, 'meta_box_links' ), 'instagrate_pro', 'normal', 'low', array( '__block_editor_compatible_meta_box' =&#62; false ) ); This is far from ideal, and you are relying on either the site owner using the Classic Editor plugin or the post type not supporting the block editor in general. TinyMCE The classic editor relies on TinyMCE, the WYSIWYG HTML Editor. TinyMCE can be customized to add buttons, dropdowns and lots more. As the Gutenberg Migration guide states, there isn’t the same type of button in the new Gutenberg UI: While the Gutenberg Block API provides UI for inserting block-level elements, there are no Gutenberg equivalents for customizing the block toolbar or programmatically manipulating post content. My custom post type has quite a few buttons added to the WYSIWYG editor to make it easy for users to insert Instagram data tags, which would be lost if I couldn’t turn off Gutenberg for the post type: For now, the only course of action is to keep the post type using the classic editor so the TinyMCE buttons still work. It’s clear that the mass of buttons I’ve added is a hack that is unwieldy for users. At this point in my testing, I took a step back and started thinking how Gutenberg’s new UI and block-based experience is much slicker and easier to use than the classic editor. Possible Enhancements While testing the code to turn off Gutenberg for my custom post type I purposely loaded Gutenberg to see what would happen, expecting everything to break. Guess what? It didn’t. My metaboxes still loaded, and only my TinyMCE buttons were missing. It didn’t look half bad and I started to think about ways I could make my plugin interface work even better with Gutenberg. Shortcodes in Gutenberg Intagrate allows users to craft post content from Instagram media. If you want to show a video in your post content you need to add a shortcode to the post content in the custom post type. Shortcodes have always been a great way to control where dynamic content will be displayed on the front end. However, they have never been user-friendly (even when inserted by a TinyMCE button), and are definitely not WYSIWYG. Although shortcodes will still work in WordPress 5.0, blocks are the new way of accomplishing the same thing. [igp-video src="%%video%%" poster="%%image%%" size="large"] You can create dynamic blocks to replace the shortcode for the block editor, so I could replace the shortcode with a block to display the Instagram video, where users can configure video settings in the block sidebar. If I was in control of the whole site I could use Advanced Custom Fields (ACF) to register my block with PHP and define the block settings as an ACF Field Group. A block is so much more usable than a shortcode. Food for thought! We already discussed dealing with custom meta boxes that aren’t compatible with the block editor, but there are many custom meta boxes that could be replaced by Gutenberg. For example, some meta boxes have been created to store data that will be rendered in some shape or form on the front end, where shortcodes wouldn’t have cut it for users to add the data. In these cases creating a custom block instead of a custom meta box makes much more sense. If you do upgrade your meta box to a block, you would need to leave your legacy meta box code for sites that are using the Classic Editor plugin. In that case, you can use another $callback_arg when adding the meta box to tell WordPress to only load the meta box if the post type is using the classic editor: add_meta_box( 'igp_links', __( 'Useful Links', 'instagrate-pro' ), array( $this, 'meta_box_links' ), 'instagrate_pro', 'normal', 'low', array( '__block_editor_compatible_meta_box' =&#62; false, '__back_compat_meta_box' =&#62; true ) ); Both the callback arguments for meta boxes are documented here, along with a note about extra notices being added for incompatible meta boxes when the WP_DEBUG constant is turned on. Final Thoughts Through the process of making my plugins compatible with Gutenberg, I’ve seen just what an improvement Gutenberg is over the existing editor. Gutenberg is a powerful enhancement to the WordPress editing experience that plugin developers can leverage to make their plugins’ experience even better. If you develop a plugin that is used by others I recommend you take a look at not just making it continue to work with Gutenberg, but to start thinking about how you can improve it where possible by taking advantage of the new block-based editor. Have you already made your plugins compatible? Have I missed any tips for a successful conversion? Are you making your plugin’s user experience even better because of Gutenberg? Let us know in the comments below. About the Author Source: Hey WordPress Plugin Developers: Are Your Plugins Really Ready for Gutenberg?

    Read at 01:07 pm, Dec 4th

  • Converting a Shortcode to a Gutenberg Block

    How to Convert a Shortcode to a Gutenberg Block begin content columns end content columns By Daniel Bachhuber January 30, 2018 Shortcodes are a quintessential WordPress feature. They’ll continue to work when WordPress 5.0 is released, but should be converted to to Gutenberg blocks for the best possible user experience. Why are Shortcodes Popular? Shortcodes are popular because they let WordPress users store a macro in the editor that transforms into a beautiful butterfly on the frontend. For example, a GitHub Gist shortcode might like this in the editor: [gist url="https://gist.github.com/danielbachhuber/736d8200d1dea9976389482170d2db5a"] The same shortcode then renders to the following JavaScript on the frontend: &#60;script src="https://gist.github.com/danielbachhuber/736d8200d1dea9976389482170d2db5a.js"&#62;&#60;/script&#62; Your browser will then turn that JavaScript into something like this: “Macro” is a fundamental term in this example. What’s stored in the database is structured data that’s then dynamically transformed on display. This dynamic transformation makes it simpler to: Render different presentation in different contexts. For instance, AMP doesn’t support arbitrary JavaScript, so you might want to render a HTML link instead. Change the presentation in the future without updating all stored instances. For example, you may decide to wrap your &#60;script&#62; tag with a &#60;div class="github-gist"&#62;&#60;/div&#62; for easier styling. Standard Gutenberg blocks store pure static HTML in the database. A dynamic block gives you the same flexibility as a shortcode by delaying rendering to the point of presentation. Let’s recap with a comparison table:      Dynamic Block Standard Block Better user experience than shortcodes Yes Yes Render context-specific output on the frontend vs. RSS vs. AMP Yes No Change output without transforming all stored references Yes No Converting a Shortcode to a Dynamic Gutenberg Block Without any intervention, your existing shortcode will look like this in Gutenberg: Not any worse than the Classic Editor, but we could make it so much better! Let’s do so—there are two key components: Registering the block and its controls with JavaScript. Registering the dynamic block callback with PHP. Registering the Block and Its Controls in JavaScript To get a head start on creating a new Gutenberg block, first run wp scaffold block with WP-CLI v1.5.0 or later. This will set up a blocks folder in your plugin with some of the basic files: Make sure to load the scaffolded PHP file from your main plugin file, otherwise it won’t be loaded. We’re ready to dive into the Gutenberg block itself. Because this isn’t a comprehensive introduction, only an explanation of dynamic blocks, refer to the Gutenberg handbook to learn more. The block.js file (which you may see as index.js elsewhere) within your block folder is where you’ll be modifying the block’s JavaScript registration. The top of the JavaScript file might look something like this: ( function( wp ) { var el = wp.element.createElement; var __ = wp.i18n.__; // Visit https://wordpress.org/gutenberg/handbook/block-api/ to learn more wp.blocks.registerBlockType( 'github-gist-gutenberg-block/github-gist', { To register the block preview and controls, you’ll need to modify the edit callback. Then, modify the save callback to change what Gutenberg stores in post content in the database. Here’s an annotated version of the modifications we made to the GitHub Gist edit callback: /** * Called when Gutenberg initially loads the block. */ edit: function( props ) { var url = props.attributes.url &#124;&#124; '', focus = props.focus; // retval is our return value for the callback. var retval = []; // When the block is in focus or there's no URL value, // show the text input control so the user can enter a URL. if ( !! focus &#124;&#124; ! url.length ) { // Instantiate a TextControl element. var controlOptions = { // Existing 'url' value for the block. value: url, // When the text input value is changed, we need to // update the 'url' attribute to propagate the change. onChange: function( newVal ) { props.setAttributes({ url: newVal }); }, placeholder: __( 'Enter a GitHub Gist URL' ), }; retval.push( // el() is a function to instantiate a new element el( InspectorControls.TextControl, controlOptions ) ); } // Only add preview UI when there's a URL entered. if ( url.length ) { var id = 'gist-' + props.id; // setTimeout is used to delay the GitHub JSON API request // until after the block is initially rendered. From the response, // we update the rendered div. setTimeout(function(){ jQuery.getJSON( url.trim(//$/) + '.json?callback=?', function(data){ var div = jQuery('#'+id); div.html(''); var stylesheet = jQuery('&#60;link /&#62;'); stylesheet.attr('ref', 'stylesheet'); stylesheet.attr('href', data.stylesheet); stylesheet.attr('type', 'text/css'); div.append(stylesheet); div.append(data.div); }); }, 10 ); retval.push( el( 'div', { id: id } ) ); } return retval; } Here’s an annotated version of the GitHub Gist save callback: /** * Called when Gutenberg "saves" the block to post_content */ save: function( props ) { var url = props.attributes.url &#124;&#124; ''; // If there's no URL, don't save any inline HTML. if ( ! url.length ) { return null; } // Include a fallback link for non-JS contexts // and for when the plugin is not activated. return el( 'a', { href: url }, __( 'View Gist on GitHub' ) ); } Et voila! Your Gutenberg block’s JavaScript is registered. But you still need to register a callback in PHP to dynamically render it on the frontend. Registering the Dynamic Block Callback in PHP Fortunately, dynamic blocks can work interchangeably with your existing shortcode callback. Simply call register_block_type alongside your add_shortcode: /** * Register the GitHub Gist shortcode */ function gggb_init() { add_shortcode( 'github-gist', 'gggb_render_shortcode' ); register_block_type( 'github-gist-gutenberg-block/github-gist', array( 'render_callback' =&#62; 'gggb_render_shortcode', ) ); } add_action( 'init', 'gggb_init' ); When your block is rendered on the frontend, it will be processed by your render callback: function gggb_render_shortcode( $atts ) { if ( empty( $atts['url'] ) &#124;&#124; 'gist.github.com' !== parse_url( $atts['url'], PHP_URL_HOST ) ) { return ''; } return sprintf( '&#60;script src="%s"&#62;&#60;/script&#62;', esc_url( rtrim( $atts['url'], '/' ) . '.js' ) ); } Note: this render callback is intentionally different than the Gutenberg block’s edit callback. Our preference is to use GitHub’s provided JavaScript embed code because this lets GitHub change the embed’s behavior at a future date without requiring a developer to make changes. Just the Beginning Congrats, you did it! If you’ve made it this far, you’re either on top of your game or completely baffled. Here are some concepts we’ve touched on: Dynamic blocks are advantageous over standard blocks because they let you render different output based on context (frontend vs. RSS vs. AMP) and change the output at a future date without updating all stored references. Gutenberg blocks can be registered with both JavaScript and PHP. JavaScript registration gives you control over the editing interface, the block preview, and what ends up stored in post content. PHP registration enables you to dynamically handle rendering with a PHP callback. Even when you’re building a dynamic block, you’ll want to save some fallback HTML in the post content for when the plugin isn’t active, etc. For the GitHub Gist block, this is a View Gist on GitHub link. Check out the example code on GitHub and feel free to open a new issue if you have any questions. Thanks for reading! /.content /.node /.content /.block /.block Source: Converting a Shortcode to a Gutenberg Block

    Read at 01:07 pm, Dec 4th

  • Dilly Dilly: Modist Brewing Gets Cease-and-Desist From Budweiser - Thrillist

    Food &#38; Drink Bud Light Served Craft Brewery a Creative Cease-and-Desist via Medieval Scroll At this point, you've probably heard Bud Light's new nonsensical catchphrase thanks to the commercial that went viral. The meaningless "Dilly Dilly" has now graced novelty shirts, comments sections, and, as of Friday, a new beer.  Minneapolis-based Modist Brewing released a Mosaic Double IPA called Dilly Dilly on Friday. It didn't take long for Anheuser-Busch InBev to stop by to let them know the name wasn't going to fly. The bad news was delivered in an amusing (and quite public) way. Like the characters from the "Dilly Dilly" commercials, a town crier dropped by in medieval garb with a scroll proclaiming that Dilly Dilly beer needed to change its name. The messenger warned, "Disobedience will be met with additional scrolls, then a formal warning, then finally, a private tour of the pit of misery." The last was the locale for the second "Dilly Dilly" commercial. No pillory was involved at the Modist taproom, though. So, that's good.  Recommended Video The Definitive Eggnog Recipe You Need for the Holidays “A couple days ago we realized the slogan was trademarked by Bud Light, not as a beer but just as a slogan, and got a little scared there for a little bit,” co-founder Kale Anderson told Growler Magazine. “But then we said, ‘Screw it, let’s see what happens.’ And that’s what happens.” While Modist got a cease-and-desist about two-and-a-half hours after tapping the new brew, Bud said Modist could sell the rest of Dilly Dilly at the taproom under that name. And, since the 2018 Super Bowl will be in Minneapolis, A-B InBev offered the folks at Modist two "thrones" to watch the Super Bowl with the Bud Light team.  As seen above, the Modist team took it in stride and even pinned the scroll up on the wall behind the bar. The staff also joked that the beer would be renamed Coat Tails once this batch runs out. A representative tells Thrillist, "It'll probably just go away and not come back. We didn't brew all that much of it." h/t Star Tribune UPDATE:Modist announced on January 30 that it plans to raffle off the Super Bowl tickets from Bud Light. The proceeds will be donated to local charities. Starting Monday night, raffle tickets can be purchased at the brewery's taproom for $25 and there will only be a limited quantity so that people who buy tickets have a legitimate chance of winning. The only catch is that if you win "we’re going to force you to wear free Modist clothing and take some pictures for us inside of the stadium," according to the brewery's post. Oh, and the brewery is releasing another cheeky beer to coincide with all the hoopla. It's called Dungeon Juice. (A call out to another "Dilly Dilly" ad.) The juicy IPA is available in the Modist taproom starting Tuesday.  Located below in our pet stuffed raven's mouth is our official response to the clever cease and desist we got from the throne. A sincere thanks to @budlight for the opportunity to do some good. Full raffle/beer/charities/playground details available at: https://t.co/NOmU8BPbmt pic.twitter.com/DK7JhdNlU9— Modist Brewing (@ModistBrewing) January 29, 2018 Sign up here for our daily Thrillist email, and get your fix of the best in food/drink/fun. Dustin Nelson is a News Writer with Thrillist. He holds a Guinness World Record but has never met the fingernail lady. Follow him @dlukenelson. Source: Dilly Dilly: Modist Brewing Gets Cease-and-Desist From Budweiser &#8211; Thrillist

    Read at 12:13 pm, Dec 4th

  • In China, your car could be talking to the government

    SHANGHAI (AP) — When Shan Junhua bought his white Tesla Model X, he knew it was a fast, beautiful car. What he didn’t know is that Tesla constantly sends information about the precise location of his car to the Chinese government. Tesla is not alone. China has called upon all electric vehicle manufacturers in China to make the same kind of reports — potentially adding to the rich kit of surveillance tools available to the Chinese government as President Xi Jinping steps up the use of technology to track Chinese citizens. “I didn’t know this,” said Shan. “Tesla could have it, but why do they transmit it to the government? Because this is about privacy.” More than 200 manufacturers, including Tesla, Volkswagen, BMW, Daimler, Ford, General Motors, Nissan, Mitsubishi and U.S.-listed electric vehicle start-up NIO, transmit position information and dozens of other data points to government-backed monitoring centers, The Associated Press has found. Generally, it happens without car owners’ knowledge. The automakers say they are merely complying with local laws, which apply only to alternative energy vehicles. Chinese officials say the data is used for analytics to improve public safety, facilitate industrial development and infrastructure planning, and to prevent fraud in subsidy programs. China has ordered electric car makers to share real-time driving data with the government. The country says it’s to ensure safety and improve the infrastructure, but critics worry the tracking can be put to more nefarious uses. (Nov. 29) But other countries that are major markets for electronic vehicles — the United States, Japan, across Europe — do not collect this kind of real-time data. And critics say the information collected in China is beyond what is needed to meet the country’s stated goals. It could be used not only to undermine foreign carmakers’ competitive position, but also for surveillance — particularly in China, where there are few protections on personal privacy. Under the leadership of Xi Jinping, China has unleashed a war on dissent, marshalling big data and artificial intelligence to create a more perfect kind of policing, capable of predicting and eliminating perceived threats to the stability of the ruling Communist Party. There is also concern about the precedent these rules set for sharing data from next-generation connected cars, which may soon transmit even more personal information. “You’re learning a lot about people’s day-to-day activities and that becomes part of what I call ubiquitous surveillance, where pretty much everything that you do is being recorded and saved and potentially can be used in order to affect your life and your freedom,” said Michael Chertoff, who served as Secretary of the U.S. Department of Homeland Security under President George W. Bush and recently wrote a book called “Exploding Data.” Chertoff said global automakers should be asking themselves tough questions. “If what you’re doing is giving a government of a more authoritarian country the tools to have massive surveillance, I think then companies have to ask themselves, ‘Is this really something we want to do in terms of our corporate values, even if it means otherwise forgoing that market?’” ___ A BIGGER BROTHER? The Shanghai Electric Vehicle Public Data Collecting, Monitoring and Research Center sits in a grey tower in suburban Jiading district. One floor up from the cafeteria, a wall-sized screen glows with dots, each representing a single vehicle coursing along Shanghai’s roads to create a massive real-time map that could reveal where people live, shop, work, and worship. Click a dot at random, and up pops a window with a number that identifies each individual vehicle, along with its make and model, mileage and battery charge. All told, the screen exhibits data from over 222,000 vehicles in Shanghai, the vast majority of them passenger cars. “We can provide a lot of data from consumers to the government to help them improve policy and planning,” said Ding Xiaohua, deputy director of the center, a non-profit that is tightly aligned with and funded by the government. According to national specifications published in 2016, electric vehicles in China transmit data from the car’s sensors back to the manufacturer. From there, automakers send at least 61 data points, including location and details about battery and engine function to local centers like the one Ding oversees in Shanghai. Data also flows to a national monitoring center for new energy vehicles run by the Beijing Institute of Technology, which pulls information from more than 1.1 million vehicles across the country, according to the National Big Data Alliance of New Energy Vehicles. The national monitoring center declined to respond to questions. Those numbers are about to get much bigger. Though electric vehicle sales accounted for just 2.6 percent of the total last year, policymakers have said they’d like new energy vehicles to account for 20 percent of total sales by 2025. Starting next year, all automakers in China must meet production minimums for new energy vehicles, part of Beijing’s aggressive effort to reduce dependence on foreign energy sources and place itself at the forefront of a growing global industry. The Chinese government has shown its interest in tracking vehicles. “The government wants to know what people are up to at all times and react in the quickest way possible,” said Maya Wang, a senior China researcher for Human Rights Watch. “There is zero protection against state surveillance.” “Tracking vehicles is one of the main focuses of their mass surveillance,” she added. Last year, authorities in Xinjiang, a restive region in western China that has become a laboratory for China’s surveillance state, ordered residents to install GPS devices so their vehicles could be tracked, according to official media. This summer the Ministry of Public Security, a police agency, began to roll out a system to track vehicles using windshield radio frequency chips that can identify cars as they pass roadside reading devices. Ding insisted that the electric vehicle monitoring program is not designed to facilitate state surveillance, though he said data could be shared with government public security organs, if a formal request is made. The center said it has not shared information with police, prosecutors or courts, but has used the data to assist a government investigation of a vehicle fire. There is a privacy firewall built into the system. The monitoring center has each car’s unique vehicle identification number, but to link that number with the personal details of the car owner, it must go through the automaker — a step it has taken in the past. Chinese law enforcement can also independently link the vehicle identification number with the car owner’s personal information. “To speak bluntly, the government doesn’t need to surveil through a platform like ours,” Ding said. He said he believed the security forces “must have their own ways to monitor suspects,” as other governments do. ___ DATA ON WHEELS Many vehicles in the U.S., Europe and Japan transmit position information back to automakers, who feed it to car-tracking apps, maps that pinpoint nearby amenities and emergency services providers. But the data stops there. Government or law enforcement agencies would generally only be able to access personal vehicle data in the context of a specific criminal investigation and in the U.S. would typically need a court order, lawyers said. Automakers initially resisted sharing information with the Shanghai monitoring center; then the government made transmitting data a prerequisite for getting incentives. “The automakers consider the data a precious resource,” said a government consultant who helped evaluate the policy and spoke on condition of anonymity to discuss sensitive issues. “They gave you dozens of reasons why they can’t give you the data. They give you dozens of excuses. Then we offer the incentives. Then they want to give us the data because it’s part of their profit.” There was concern that data pulled from electric vehicles might reveal proprietary information about, for example, how hybrids switch between gas and battery power, and eventually set automakers up for commercial competition with a Chinese government entity. As cars become more connected, carmakers are looking to tap new revenue streams built on data — a market McKinsey estimated could be worth $750 billion by 2030. Ding said a Tesla executive came to Shanghai and grilled him about the rules. “The first question is who are you, the second question is why you collect this data, and the third question is how to protect the privacy of the users,” Ding said. Tesla declined to comment. Ding said confidentiality agreements bar the data center from sharing proprietary information. Still, he is open about his commercial ambition. He’d like to wean the center from government funding and make money from the data, without infringing on anyone’s privacy or intellectual property. “We have done some explorations,” he said. “But there is still a distance from truly monetizing it.” ___ CHINA’S EDGE The Chinese government’s ability to grab data as it flows from cars gives its academics and policymakers an edge over competing nations. China tends to view technology development as a key competitive resource. Though global automakers have received billions in incentives and subsidies from U.S., European and Japanese governments, they are contributing data to the Chinese government that ultimately serves Beijing’s strategic interests. In 2011, the U.S. Department of Energy’s Idaho National Laboratory began a nationwide study of how electric vehicle owners drive and charge their cars. Participants gave explicit written consent to allow the government laboratory to collect their data, and even then it wasn’t delivered in real time, said John Smart, who leads the center’s advanced vehicles group. Instead, the team got historical data on a weekly basis. Cars were assigned random numbers for the study, so owners remained anonymous. Nothing of its kind has been done since in the U.S., Smart said. “The cost is very high to collect data,” he explained. “The government hasn’t felt the need to provide that money and the manufacturers making their own investments are choosing to keep the findings to themselves for proprietary reasons.” When it was published, in 2015, the Idaho National Laboratory’s study was the largest ever done. All told, bundled with some additional data, the study helped Idaho researchers analyze 21,600 electric vehicles over 158 million driving miles (254 million kilometers). In the same amount of time it took Idaho researchers to publish their study, the Shanghai Electric Vehicle Public Data Collecting, Monitoring and Research Center began gathering real-time information from more than 222,000 vehicles and amassed over 4.7 billion miles (7.6 billion kilometers) of driving history. “As a researcher, I think that data set could be used to answer hundreds of questions,” Smart said. “I have a notebook a half an inch thick full of questions.” Global automakers stressed that they share data to comply with Chinese regulations. Nearly all have announced plans to aggressively expand their electric vehicle offerings in China, the world’s largest car market. “There are real-time monitoring systems in China where we have to deliver car data to a government system,” Volkswagen Group China chief executive Jochem Heizmann said in an interview. He acknowledged that he could not guarantee the data would not be used for government surveillance, but stressed that Volkswagen keeps personal data, like the driver’s identity, secure within its own systems. “It includes the location of the car, yes, but not who is sitting in it,” he said, adding that cars won’t reveal any more information than smart phones already do. “There is not a principle difference between sitting in a car and being in a shopping mall and having a smart phone with you.” Jose Munoz, the head of Nissan’s China operations, said he was unaware of the monitoring system until the AP told him, but he stressed that the automaker operated according to the law. Asked by the AP about the potential for human rights abuses and commercial conflicts posed by the data sharing, Munoz smiled and shrugged. “At Nissan, we are extremely committed to the Chinese market,” he said. “We see it as the market that has the greatest opportunity to grow.” Ford, BMW and NIO declined to comment. Mitsubishi did not respond to multiple requests for comment. General Motors and Daimler said they transmit data in compliance with industry regulations and get consent from car buyers on how their vehicle data is collected and used. Tesla declined to answer specific questions and instead pointed to a privacy policy buyers sign at the time of purchase, which stipulates that vehicle data can be shared “with other third parties when required by law,” though there was no specific mention of the government monitoring centers in the Chinese version of the policy. Interviews with car owners suggest such disclosures aren’t effective. Only one of nine electric vehicle owners was aware data from his car is fed to the government — and he said he only knew because he is an electric vehicle engineer. “It’s useless to be concerned about it,” said Min Zeren, who owns a Tesla Model S. “If you’re concerned about it, then there’s no way to live in this country.” _____ Associated Press researcher Chen Si contributed from Shanghai and Business Writer Yuri Kageyama contributed from Tokyo. Follow Kinetz on Twitter at https://twitter.com/ekinetz Source: In China, your car could be talking to the government

    Read at 10:32 am, Dec 4th

  • 7 bad excuses for not using TypeScript – LogRocket

    Why have I been blocked? This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data. Source: 7 bad excuses for not using TypeScript – LogRocket

    Read at 08:03 pm, Dec 3rd

  • In practice, what are the main uses for the new "yield from" syntax in Python 3.3? - Stack Overflow

    Let's get one thing out of the way first. The explanation that yield from g is equivalent to for v in g: yield v does not even begin to do justice to what yield from is all about. Because, let's face it, if all yield from does is expand the for loop, then it does not warrant adding yield from to the language and preclude a whole bunch of new features from being implemented in Python 2.x. What yield from does is it establishes a transparent bidirectional connection between the caller and the sub-generator: The connection is "transparent" in the sense that it will propagate everything correctly too, not just the elements being generated (e.g. exceptions are propagated). The connection is "bidirectional" in the sense that data can be both sent from and to a generator. (If we were talking about TCP, yield from g might mean "now temporarily disconnect my client's socket and reconnect it to this other server socket".) BTW, if you are not sure what sending data to a generator even means, you need to drop everything and read about coroutines first—they're very useful (contrast them with subroutines), but unfortunately lesser-known in Python. Dave Beazley's Curious Course on Couroutines is an excellent start. Read slides 24-33 for a quick primer. Reading data from a generator using yield from def reader(): """A generator that fakes a read from a file, socket, etc.""" for i in range(4): yield '&#60;&#60; %s' % i def reader_wrapper(g): # Manually iterate over data produced by reader for v in g: yield v wrap = reader_wrapper(reader()) for i in wrap: print(i) # Result &#60;&#60; 0 &#60;&#60; 1 &#60;&#60; 2 &#60;&#60; 3 Instead of manually iterating over reader(), we can just yield from it. def reader_wrapper(g): yield from g That works, and we eliminated one line of code. And probably the intent is a little bit clearer (or not). But nothing life changing. Sending data to a generator (coroutine) using yield from - Part 1 Now let's do something more interesting. Let's create a coroutine called writer that accepts data sent to it and writes to a socket, fd, etc. def writer(): """A coroutine that writes data *sent* to it to fd, socket, etc.""" while True: w = (yield) print('&#62;&#62; ', w) Now the question is, how should the wrapper function handle sending data to the writer, so that any data that is sent to the wrapper is transparently sent to the writer()? def writer_wrapper(coro): # TBD pass w = writer() wrap = writer_wrapper(w) wrap.send(None) # "prime" the coroutine for i in range(4): wrap.send(i) # Expected result &#62;&#62; 0 &#62;&#62; 1 &#62;&#62; 2 &#62;&#62; 3 The wrapper needs to accept the data that is sent to it (obviously) and should also handle the StopIteration when the for loop is exhausted. Evidently just doing for x in coro: yield x won't do. Here is a version that works. def writer_wrapper(coro): coro.send(None) # prime the coro while True: try: x = (yield) # Capture the value that's sent coro.send(x) # and pass it to the writer except StopIteration: pass Or, we could do this. def writer_wrapper(coro): yield from coro That saves 6 lines of code, make it much much more readable and it just works. Magic! Sending data to a generator yield from - Part 2 - Exception handling Let's make it more complicated. What if our writer needs to handle exceptions? Let's say the writer handles a SpamException and it prints *** if it encounters one. class SpamException(Exception): pass def writer(): while True: try: w = (yield) except SpamException: print('***') else: print('&#62;&#62; ', w) What if we don't change writer_wrapper? Does it work? Let's try # writer_wrapper same as above w = writer() wrap = writer_wrapper(w) wrap.send(None) # "prime" the coroutine for i in [0, 1, 2, 'spam', 4]: if i == 'spam': wrap.throw(SpamException) else: wrap.send(i) # Expected Result &#62;&#62; 0 &#62;&#62; 1 &#62;&#62; 2 *** &#62;&#62; 4 # Actual Result &#62;&#62; 0 &#62;&#62; 1 &#62;&#62; 2 Traceback (most recent call last): ... redacted ... File ... in writer_wrapper x = (yield) __main__.SpamException Um, it's not working because x = (yield) just raises the exception and everything comes to a crashing halt. Let's make it work, but manually handling exceptions and sending them or throwing them into the sub-generator (writer) def writer_wrapper(coro): """Works. Manually catches exceptions and throws them""" coro.send(None) # prime the coro while True: try: try: x = (yield) except Exception as e: # This catches the SpamException coro.throw(e) else: coro.send(x) except StopIteration: pass This works. # Result &#62;&#62; 0 &#62;&#62; 1 &#62;&#62; 2 *** &#62;&#62; 4 But so does this! def writer_wrapper(coro): yield from coro The yield from transparently handles sending the values or throwing values into the sub-generator. This still does not cover all the corner cases though. What happens if the outer generator is closed? What about the case when the sub-generator returns a value (yes, in Python 3.3+, generators can return values), how should the return value be propagated? That yield from transparently handles all the corner cases is really impressive. yield from just magically works and handles all those cases. I personally feel yield from is a poor keyword choice because it does not make the two-way nature apparent. There were other keywords proposed (like delegate but were rejected because adding a new keyword to the language is much more difficult than combining existing ones. In summary, it's best to think of yield from as a transparent two way channel between the caller and the sub-generator. References: PEP 380 - Syntax for delegating to a sub-generator (Ewing) [v3.3, 2009-02-13] PEP 342 - Coroutines via Enhanced Generators (GvR, Eby) [v2.5, 2005-05-10] Source: In practice, what are the main uses for the new &#8220;yield from&#8221; syntax in Python 3.3? &#8211; Stack Overflow

    Read at 05:53 pm, Dec 3rd

  • The Ultimate Guide to Data Classes in Python 3.7 – Real Python

    One new and exciting feature coming in Python 3.7 is the data class. A data class is a class typically containing mainly data, although there aren’t really any restrictions. It is created using the new @dataclass decorator, as follows: from dataclasses import dataclass @dataclass class DataClassCard: rank: str suit: str Note: This code, as well as all other examples in this tutorial, will only work in Python 3.7 and above. A data class comes with basic functionality already implemented. For instance, you can instantiate, print, and compare data class instances straight out of the box: &#62;&#62;&#62;&#62;&#62;&#62; queen_of_hearts = DataClassCard('Q', 'Hearts') &#62;&#62;&#62; queen_of_hearts.rank 'Q' &#62;&#62;&#62; queen_of_hearts DataClassCard(rank='Q', suit='Hearts') &#62;&#62;&#62; queen_of_hearts == DataClassCard('Q', 'Hearts') True Compare that to a regular class. A minimal regular class would look something like this: class RegularCard def __init__(self, rank, suit): self.rank = rank self.suit = suit While this is not much more code to write, you can already see signs of the boilerplate pain: rank and suit are both repeated three times simply to initialize an object. Furthermore, if you try to use this plain class, you’ll notice that the representation of the objects is not very descriptive, and for some reason a queen of hearts is not the same as a queen of hearts: &#62;&#62;&#62;&#62;&#62;&#62; queen_of_hearts = RegularCard('Q', 'Hearts') &#62;&#62;&#62; queen_of_hearts.rank 'Q' &#62;&#62;&#62; queen_of_hearts &#60;__main__.RegularCard object at 0x7fb6eee35d30&#62; &#62;&#62;&#62; queen_of_hearts == RegularCard('Q', 'Hearts') False Seems like data classes are helping us out behind the scenes. By default, data classes implement a .__repr__() method to provide a nice string representation and an .__eq__() method that can do basic object comparisons. For the RegularCard class to imitate the data class above, you need to add these methods as well: class RegularCard def __init__(self, rank, suit): self.rank = rank self.suit = suit def __repr__(self): return (f'{self.__class__.__name__}' f'(rank={self.rank!r}, suit={self.suit!r})') def __eq__(self, other): if other.__class__ is not self.__class__: return NotImplemented return (self.rank, self.suit) == (other.rank, other.suit) In this tutorial, you will learn exactly which conveniences data classes provide. In addition to nice representations and comparisons, you’ll see: How to add default values to data class fields How data classes allow for ordering of objects How to represent immutable data How data classes handle inheritance We will soon dive deeper into those features of data classes. However, you might be thinking that you have already seen something like this before. Alternatives to Data Classes For simple data structures, you have probably already used a tuple or a dict. You could represent the queen of hearts card in either of the following ways: &#62;&#62;&#62;&#62;&#62;&#62; queen_of_hearts_tuple = ('Q', 'Hearts') &#62;&#62;&#62; queen_of_hearts_dict = {'rank': 'Q', 'suit': 'Hearts'} It works. However, it puts a lot of responsibility on you as a programmer: You need to remember that the queen_of_hearts_... variable represents a card. For the _tuple version, you need to remember the order of the attributes. Writing ('Spades', 'A') will mess up your program but probably not give you an easily understandable error message. If you use the _dict, you must make sure the names of the attributes are consistent. For instance {'value': 'A', 'suit': 'Spades'} will not work as expected. Furthermore, using these structures is not ideal: &#62;&#62;&#62;&#62;&#62;&#62; queen_of_hearts_tuple[0] # No named access 'Q' &#62;&#62;&#62; queen_of_hearts_dict['suit'] # Would be nicer with .suit 'Hearts' A better alternative is the namedtuple. It has long been used to create readable small data structures. We can in fact recreate the data class example above using a namedtuple like this: from collections import namedtuple NamedTupleCard = namedtuple('NamedTupleCard', ['rank', 'suit']) This definition of NamedTupleCard will give the exact same output as our DataClassCard example did: &#62;&#62;&#62;&#62;&#62;&#62; queen_of_hearts = NamedTupleCard('Q', 'Hearts') &#62;&#62;&#62; queen_of_hearts.rank 'Q' &#62;&#62;&#62; queen_of_hearts NamedTupleCard(rank='Q', suit='Hearts') &#62;&#62;&#62; queen_of_hearts == NamedTupleCard('Q', 'Hearts') True So why even bother with data classes? First of all, data classes come with many more features than you have seen so far. At the same time, the namedtuple has some other features that are not necessarily desirable. By design, a namedtuple is a regular tuple. This can be seen in comparisons, for instance: &#62;&#62;&#62;&#62;&#62;&#62; queen_of_hearts == ('Q', 'Hearts') True While this might seem like a good thing, this lack of awareness about its own type can lead to subtle and hard-to-find bugs, especially since it will also happily compare two different namedtuple classes: &#62;&#62;&#62;&#62;&#62;&#62; Person = namedtuple('Person', ['first_initial', 'last_name'] &#62;&#62;&#62; ace_of_spades = NamedTupleCard('A', 'Spades') &#62;&#62;&#62; ace_of_spades == Person('A', 'Spades') True The namedtuple also comes with some restrictions. For instance, it is hard to add default values to some of the fields in a namedtuple. A namedtuple is also by nature immutable. That is, the value of a namedtuple can never change. In some applications, this is an awesome feature, but in other settings, it would be nice to have more flexibility: &#62;&#62;&#62;&#62;&#62;&#62; card = NamedTupleCard('7', 'Diamonds') &#62;&#62;&#62; card.rank = '9' AttributeError: can't set attribute Data classes will not replace all uses of namedtuple. For instance, if you need your data structure to behave like a tuple, then a named tuple is a great alternative! Another alternative, and one of the inspirations for data classes, is the attrs project. With attrs installed (pip install attrs), you can write a card class as follows: import attr @attr.s class AttrsCard: rank = attr.ib() suit = attr.ib() This can be used in exactly the same way as the DataClassCard and NamedTupleCard examples earlier. The attrs project is great and does support some features that data classes do not, including converters and validators. Furthermore, attrs has been around for a while and is supported in Python 2.7 as well as Python 3.4 and up. However, as attrs is not a part of the standard library, it does add an external dependency to your projects. Through data classes, similar functionality will be available everywhere. In addition to tuple, dict, namedtuple, and attrs, there are many other similar projects, including typing.NamedTuple, namedlist, attrdict, plumber, and fields. While data classes are a great new alternative, there are still use cases where one of the older variants fits better. For instance, if you need compatibility with a specific API expecting tuples or need functionality not supported in data classes. Basic Data Classes Let us get back to data classes. As an example, we will create a Position class that will represent geographic positions with a name as well as the latitude and longitude: from dataclasses import dataclass @dataclass class Position: name: str lon: float lat: float What makes this a data class is the @dataclass decorator just above the class definition. Beneath the class Position: line, you simply list the fields you want in your data class. The : notation used for the fields is using a new feature in Python 3.6 called variable annotations. We will soon talk more about this notation and why we specify data types like str and float. Those few lines of code are all you need. The new class is ready for use: &#62;&#62;&#62;&#62;&#62;&#62; pos = Position('Oslo', 10.8, 59.9) &#62;&#62;&#62; print(pos) Position(name='Oslo', lon=10.8, lat=59.9) &#62;&#62;&#62; pos.lat 59.9 &#62;&#62;&#62; print(f'{pos.name} is at {pos.lat}°N, {pos.lon}°E') Oslo is at 59.9°N, 10.8°E You can also create data classes similarly to how named tuples are created. The following is (almost) equivalent to the definition of Position above: from dataclasses import make_dataclass Position = make_dataclass('Position', ['name', 'lat', 'lon']) A data class is a regular Python class. The only thing that sets it apart is that it has basic data model methods like .__init__(), .__repr__(), and .__eq__() implemented for you. Default Values It is easy to add default values to the fields of your data class: from dataclasses import dataclass @dataclass class Position: name: str lon: float = 0.0 lat: float = 0.0 This works exactly as if you had specified the default values in the definition of the .__init__() method of a regular class: &#62;&#62;&#62;&#62;&#62;&#62; Position('Null Island') Position(name='Null Island', lon=0.0, lat=0.0) &#62;&#62;&#62; Position('Greenwich', lat=51.8) Position(name='Greenwich', lon=0.0, lat=51.8) &#62;&#62;&#62; Position('Vancouver', -123.1, 49.3) Position(name='Vancouver', lon=-123.1, lat=49.3) Later you will learn about default_factory, which gives a way to provide more complicated default values. Type Hints So far, we have not made a big fuss of the fact that data classes support typing out of the box. You have probably noticed that we defined the fields with a type hint: name: str says that name should be a text string (str type). In fact, adding some kind of type hint is mandatory when defining the fields in your data class. Without a type hint, the field will not be a part of the data class. However, if you do not want to add explicit types to your data class, use typing.Any: from dataclasses import dataclass from typing import Any @dataclass class WithoutExplicitTypes: name: Any value: Any = 42 While you need to add type hints in some form when using data classes, these types are not enforced at runtime. The following code runs without any problems: &#62;&#62;&#62;&#62;&#62;&#62; Position(3.14, 'pi day', 2018) Position(name=3.14, lon='pi day', lat=2018) This is how typing in Python usually works: Python is and will always be a dynamically typed language. To actually catch type errors, type checkers like Mypy can be run on your source code. Adding Methods You already know that a data class is just a regular class. That means that you can freely add your own methods to a data class. As an example, let us calculate the distance between one position and another, along the Earth’s surface. One way to do this is by using the haversine formula: You can add a .distance_to() method to your data class just like you can with normal classes: from dataclasses import dataclass from math import asin, cos, radians, sin, sqrt @dataclass class Position: name: str lon: float = 0.0 lat: float = 0.0 def distance_to(self, other): r = 6371 # Earth radius in kilometers lam_1, lam_2 = radians(self.lon), radians(other.lon) phi_1, phi_2 = radians(self.lat), radians(other.lat) h = (sin((phi_2 - phi_1) / 2)**2 + cos(phi_1) * cos(phi_2) * sin((lam_2 - lam_1) / 2)**2) return 2 * r * asin(sqrt(h)) It works as you would expect: &#62;&#62;&#62;&#62;&#62;&#62; oslo = Position('Oslo', 10.8, 59.9) &#62;&#62;&#62; vancouver = Position('Vancouver', -123.1, 49.3) &#62;&#62;&#62; oslo.distance_to(vancouver) 7181.7841229421165 More Flexible Data Classes So far, you have seen some of the basic features of the data class: it gives you some convenience methods, and you can still add default values and other methods. Now you will learn about some more advanced features like parameters to the @dataclass decorator and the field() function. Together, they give you more control when creating a data class. Let us return to the playing card example you saw at the beginning of the tutorial and add a class containing a deck of cards while we are at it: from dataclasses import dataclass from typing import List @dataclass class PlayingCard: rank: str suit: str @dataclass class Deck: cards: List[PlayingCard] A simple deck containing only two cards can be created like this: &#62;&#62;&#62;&#62;&#62;&#62; queen_of_hearts = PlayingCard('Q', 'Hearts') &#62;&#62;&#62; ace_of_spades = PlayingCard('A', 'Spades') &#62;&#62;&#62; two_cards = Deck([queen_of_hearts, ace_of_spades]) Deck(cards=[PlayingCard(rank='Q', suit='Hearts'), PlayingCard(rank='A', suit='Spades')]) Advanced Default Values Say that you want to give a default value to the Deck. It would for example be convenient if Deck() created a regular (French) deck of 52 playing cards. First, specify the different ranks and suits. Then, add a function make_french_deck() that creates a list of instances of PlayingCard: RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split() SUITS = '♣ ♢ ♡ ♠'.split() def make_french_deck(): return [PlayingCard(r, s) for s in SUITS for r in RANKS] For fun, the four different suits are specified using their Unicode symbols. Note: Above, we used Unicode glyphs like ♠ directly in the source code. We could do this because Python supports writing source code in UTF-8 by default. Refer to this page on Unicode input for how to enter these on your system. You could also enter the Unicode symbols for the suits using N named character escapes (like N{BLACK SPADE SUIT}) or u Unicode escapes (like u2660). To simplify comparisons of cards later, the ranks and suits are also listed in their usual order. &#62;&#62;&#62;&#62;&#62;&#62; make_french_deck() [PlayingCard(rank='2', suit='♣'), PlayingCard(rank='3', suit='♣'), ... PlayingCard(rank='K', suit='♠'), PlayingCard(rank='A', suit='♠')] In theory, you could now use this function to specify a default value for Deck.cards: from dataclasses import dataclass from typing import List @dataclass class Deck: # Will NOT work cards: List[PlayingCard] = make_french_deck() Don’t do this! This introduces one of the most common anti-patterns in Python: using mutable default arguments. The problem is that all instances of Deck will use the same list object as the default value of the .cards property. This means that if, say, one card is removed from one Deck, then it disappears from all other instances of Deck as well. Actually, data classes try to prevent you from doing this, and the code above will raise a ValueError. Instead, data classes use something called a default_factory to handle mutable default values. To use default_factory (and many other cool features of data classes), you need to use the field() specifier: from dataclasses import dataclass, field from typing import List @dataclass class Deck: cards: List[PlayingCard] = field(default_factory=make_french_deck) The argument to default_factory can be any zero parameter callable. Now it is easy to create a full deck of playing cards: &#62;&#62;&#62;&#62;&#62;&#62; Deck() Deck(cards=[PlayingCard(rank='2', suit='♣'), PlayingCard(rank='3', suit='♣'), ... PlayingCard(rank='K', suit='♠'), PlayingCard(rank='A', suit='♠')]) The field() specifier is used to customize each field of a data class individually. You will see some other examples later. For reference, these are the parameters field() supports: default: Default value of the field default_factory: Function that returns the initial value of the field init: Use field in .__init__() method? (Default is True.) repr: Use field in repr of the object? (Default is True.) compare: Include the field in comparisons? (Default is True.) hash: Include the field when calculating hash()? (Default is to use the same as for compare.) metadata: A mapping with information about the field In the Position example, you saw how to add simple default values by writing lat: float = 0.0. However, if you also want to customize the field, for instance to hide it in the repr, you need to use the default parameter: lat: float = field(default=0.0, repr=False). You may not specify both default and default_factory. The metadata parameter is not used by the data classes themselves but is available for you (or third party packages) to attach information to fields. In the Position example, you could for instance specify that latitude and longitude should be given in degrees: from dataclasses import dataclass, field @dataclass class Position: name: str lon: float = field(default=0.0, metadata={'unit': 'degrees'}) lat: float = field(default=0.0, metadata={'unit': 'degrees'}) The metadata (and other information about a field) can be retrieved using the fields() function (note the plural s): &#62;&#62;&#62;&#62;&#62;&#62; from dataclasses import fields &#62;&#62;&#62; fields(Position) (Field(name='name',type=&#60;class 'str'&#62;,...,metadata={}), Field(name='lon',type=&#60;class 'float'&#62;,...,metadata={'unit': 'degrees'}), Field(name='lat',type=&#60;class 'float'&#62;,...,metadata={'unit': 'degrees'})) &#62;&#62;&#62; lat_unit = fields(Position)[2].metadata['unit'] &#62;&#62;&#62; lat_unit 'degrees' You Need Representation? Recall that we can create decks of cards out of thin air: &#62;&#62;&#62;&#62;&#62;&#62; Deck() Deck(cards=[PlayingCard(rank='2', suit='♣'), PlayingCard(rank='3', suit='♣'), ... PlayingCard(rank='K', suit='♠'), PlayingCard(rank='A', suit='♠')]) While this representation of a Deck is explicit and readable, it is also very verbose. I have deleted 48 of the 52 cards in the deck in the output above. On an 80-column display, simply printing the full Deck takes up 22 lines! Let us add a more concise representation. In general, a Python object has two different string representations: repr(obj) is defined by obj.__repr__() and should return a developer-friendly representation of obj. If possible, this should be code that can recreate obj. Data classes do this. str(obj) is defined by obj.__str__() and should return a user-friendly representation of obj. Data classes do not implement a .__str__() method, so Python will fall back to the .__repr__() method. Let us implement a user-friendly representation of a PlayingCard: from dataclasses import dataclass @dataclass class PlayingCard: rank: str suit: str def __str__(self): return f'{self.suit}{self.rank}' The cards now look much nicer, but the deck is still as verbose as ever: &#62;&#62;&#62;&#62;&#62;&#62; ace_of_spades = PlayingCard('A', '♠') &#62;&#62;&#62; ace_of_spades PlayingCard(rank='A', suit='♠') &#62;&#62;&#62; print(ace_of_spades) ♠A &#62;&#62;&#62; print(Deck()) Deck(cards=[PlayingCard(rank='2', suit='♣'), PlayingCard(rank='3', suit='♣'), ... PlayingCard(rank='K', suit='♠'), PlayingCard(rank='A', suit='♠')]) To show that it is possible to add your own .__repr__() method as well, we will violate the principle that it should return code that can recreate an object. Practicality beats purity after all. The following code adds a more concise representation of the Deck: from dataclasses import dataclass, field from typing import List @dataclass class Deck: cards: List[PlayingCard] = field(default_factory=make_french_deck) def __repr__(self): cards = ', '.join(f'{c!s}' for c in self.cards) return f'{self.__class__.__name__}({cards})' Note the !s specifier in the {c!s} format string. It means that we explicitly want to use the str() representation of PlayingCards. With the new .__repr__(), the representation of Deck is easier on the eyes: &#62;&#62;&#62;&#62;&#62;&#62; Deck() Deck(♣2, ♣3, ♣4, ♣5, ♣6, ♣7, ♣8, ♣9, ♣10, ♣J, ♣Q, ♣K, ♣A, ♢2, ♢3, ♢4, ♢5, ♢6, ♢7, ♢8, ♢9, ♢10, ♢J, ♢Q, ♢K, ♢A, ♡2, ♡3, ♡4, ♡5, ♡6, ♡7, ♡8, ♡9, ♡10, ♡J, ♡Q, ♡K, ♡A, ♠2, ♠3, ♠4, ♠5, ♠6, ♠7, ♠8, ♠9, ♠10, ♠J, ♠Q, ♠K, ♠A) Comparing Cards In many card games, cards are compared to each other. For instance in a typical trick taking game, the highest card takes the trick. As it is currently implemented, the PlayingCard class does not support this kind of comparison: &#62;&#62;&#62;&#62;&#62;&#62; queen_of_hearts = PlayingCard('Q', '♡') &#62;&#62;&#62; ace_of_spades = PlayingCard('A', '♠') &#62;&#62;&#62; ace_of_spades &#62; queen_of_hearts TypeError: '&#62;' not supported between instances of 'Card' and 'Card' This is, however, (seemingly) easy to rectify: from dataclasses import dataclass @dataclass(order=True) class PlayingCard: rank: str suit: str def __str__(self): return f'{self.suit}{self.rank}' The @dataclass decorator has two forms. So far you have seen the simple form where @dataclass is specified without any parentheses and parameters. However, you can also give parameters to the @dataclass() decorator in parentheses. The following parameters are supported: init: Add .__init__() method? (Default is True.) repr: Add .__repr__() method? (Default is True.) eq: Add .__eq__() method? (Default is True.) order: Add ordering methods? (Default is False.) unsafe_hash: Force the addition of a .__hash__() method? (Default is False.) frozen: If True, assigning to fields raise an exception. (Default is False.) See the original PEP for more information about each parameter. After setting order=True, instances of PlayingCard can be compared: &#62;&#62;&#62;&#62;&#62;&#62; queen_of_hearts = PlayingCard('Q', '♡') &#62;&#62;&#62; ace_of_spades = PlayingCard('A', '♠') &#62;&#62;&#62; ace_of_spades &#62; queen_of_hearts False How are the two cards compared though? You have not specified how the ordering should be done, and for some reason Python seems to believe that a Queen is higher than an Ace… It turns out that data classes compare objects as if they were tuples of their fields. In other words, a Queen is higher than an Ace because 'Q' comes after 'A' in the alphabet: &#62;&#62;&#62;&#62;&#62;&#62; ('A', '♠') &#62; ('Q', '♡') False That does not really work for us. Instead, we need to define some kind of sort index that uses the order of RANKS and SUITS. Something like this: &#62;&#62;&#62;&#62;&#62;&#62; RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split() &#62;&#62;&#62; SUITS = '♣ ♢ ♡ ♠'.split() &#62;&#62;&#62; card = PlayingCard('Q', '♡') &#62;&#62;&#62; RANKS.index(card.rank) * len(SUITS) + SUITS.index(card.suit) 42 For PlayingCard to use this sort index for comparisons, we need to add a field .sort_index to the class. However, this field should be calculated from the other fields .rank and .suit automatically. This is exactly what the special method .__post_init__() is for. It allows for special processing after the regular .__init__() method is called: from dataclasses import dataclass, field RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split() SUITS = '♣ ♢ ♡ ♠'.split() @dataclass(order=True) class PlayingCard: sort_index: int = field(init=False, repr=False) rank: str suit: str def __post_init__(self): self.sort_index = (RANKS.index(self.rank) * len(SUITS) + SUITS.index(self.suit)) def __str__(self): return f'{self.suit}{self.rank}' Note that .sort_index is added as the first field of the class. That way, the comparison is first done using .sort_index and only if there are ties are the other fields used. Using field(), you must also specify that .sort_index should not be included as a parameter in the .__init__() method (because it is calculated from the .rank and .suit fields). To avoid confusing the user about this implementation detail, it is probably also a good idea to remove .sort_index from the repr of the class. Finally, aces are high: &#62;&#62;&#62;&#62;&#62;&#62; queen_of_hearts = PlayingCard('Q', '♡') &#62;&#62;&#62; ace_of_spades = PlayingCard('A', '♠') &#62;&#62;&#62; ace_of_spades &#62; queen_of_hearts True You can now easily create a sorted deck: &#62;&#62;&#62;&#62;&#62;&#62; Deck(sorted(make_french_deck())) Deck(♣2, ♢2, ♡2, ♠2, ♣3, ♢3, ♡3, ♠3, ♣4, ♢4, ♡4, ♠4, ♣5, ♢5, ♡5, ♠5, ♣6, ♢6, ♡6, ♠6, ♣7, ♢7, ♡7, ♠7, ♣8, ♢8, ♡8, ♠8, ♣9, ♢9, ♡9, ♠9, ♣10, ♢10, ♡10, ♠10, ♣J, ♢J, ♡J, ♠J, ♣Q, ♢Q, ♡Q, ♠Q, ♣K, ♢K, ♡K, ♠K, ♣A, ♢A, ♡A, ♠A) Or, if you don’t care about sorting, this is how you draw a random hand of 10 cards: &#62;&#62;&#62;&#62;&#62;&#62; from random import sample &#62;&#62;&#62; Deck(sample(make_french_deck(), k=10)) Deck(♢2, ♡A, ♢10, ♣2, ♢3, ♠3, ♢A, ♠8, ♠9, ♠2) Of course, you don’t need order=True for that… Immutable Data Classes One of the defining features of the namedtuple you saw earlier is that it is immutable. That is, the value of its fields may never change. For many types of data classes, this is a great idea! To make a data class immutable, set frozen=True when you create it. For example, the following is an immutable version of the Position class you saw earlier: from dataclasses import dataclass @dataclass(frozen=True) class Position: name: str lon: float = 0.0 lat: float = 0.0 In a frozen data class, you can not assign values to the fields after creation: &#62;&#62;&#62;&#62;&#62;&#62; pos = Position('Oslo', 10.8, 59.9) &#62;&#62;&#62; pos.name 'Oslo' &#62;&#62;&#62; pos.name = 'Stockholm' dataclasses.FrozenInstanceError: cannot assign to field 'name' Be aware though that if your data class contains mutable fields, those might still change. This is true for all nested data structures in Python (see this video for further info): from dataclasses import dataclass from typing import List @dataclass(frozen=True) class ImmutableCard: rank: str suit: str @dataclass(frozen=True) class ImmutableDeck: cards: List[PlayingCard] Even though both ImmutableCard and ImmutableDeck are immutable, the list holding cards is not. You can therefore still change the cards in the deck: &#62;&#62;&#62;&#62;&#62;&#62; queen_of_hearts = ImmutableCard('Q', '♡') &#62;&#62;&#62; ace_of_spades = ImmutableCard('A', '♠') &#62;&#62;&#62; deck = ImmutableDeck([queen_of_hearts, ace_of_spades]) &#62;&#62;&#62; deck ImmutableDeck(cards=[ImmutableCard(rank='Q', suit='♡'), ImmutableCard(rank='A', suit='♠')]) &#62;&#62;&#62; deck.cards[0] = ImmutableCard('7', '♢') &#62;&#62;&#62; deck ImmutableDeck(cards=[ImmutableCard(rank='7', suit='♢'), ImmutableCard(rank='A', suit='♠')]) To avoid this, make sure all fields of an immutable data class use immutable types (but remember that types are not enforced at runtime). The ImmutableDeck should be implemented using a tuple instead of a list. Inheritance You can subclass data classes quite freely. As an example, we will extend our Position example with a country field and use it to record capitals: from dataclasses import dataclass @dataclass class Position: name: str lon: float lat: float @dataclass class Capital(Position): country: str In this simple example, everything works without a hitch: &#62;&#62;&#62;&#62;&#62;&#62; Capital('Oslo', 10.8, 59.9, 'Norway') Capital(name='Oslo', lon=10.8, lat=59.9, country='Norway') The country field of Capital is added after the three original fields in Position. Things get a little more complicated if any fields in the base class have default values: from dataclasses import dataclass @dataclass class Position: name: str lon: float = 0.0 lat: float = 0.0 @dataclass class Capital(Position): country: str # Does NOT work This code will immediately crash with a TypeError complaining that “non-default argument ‘country’ follows default argument.” The problem is that our new country field has no default value, while the lon and lat fields have default values. The data class will try to write an .__init__() method with the following signature: def __init__(name: str, lon: float = 0.0, lat: float = 0.0, country: str): ... However, this is not valid Python. If a parameter has a default value, all following parameters must also have a default value. In other words, if a field in a base class has a default value, then all new fields added in a subclass must have default values as well. Another thing to be aware of is how fields are ordered in a subclass. Starting with the base class, fields are ordered in the order in which they are first defined. If a field is redefined in a subclass, its order does not change. For example, if you define Position and Capital as follows: from dataclasses import dataclass @dataclass class Position: name: str lon: float = 0.0 lat: float = 0.0 @dataclass class Capital(Position): country: str = 'Unknown' lat: float = 40.0 Then the order of the fields in Capital will still be name, lon, lat, country. However, the default value of lat will be 40.0. &#62;&#62;&#62;&#62;&#62;&#62; Capital('Madrid', country='Spain') Capital(name='Madrid', lon=0.0, lat=40.0, country='Spain') Optimizing Data Classes I’m going to end this tutorial with a few words about slots. Slots can be used to make classes faster and use less memory. Data classes have no explicit syntax for working with slots, but the normal way of creating slots works for data classes as well. (They really are just regular classes!) from dataclasses import dataclass @dataclass class SimplePosition: name: str lon: float lat: float @dataclass class SlotPosition: __slots__ = ['name', 'lon', 'lat'] name: str lon: float lat: float Essentially, slots are defined using .__slots__ to list the variables on a class. Variables or attributes not present in .__slots__ may not be defined. Furthermore, a slots class may not have default values. The benefit of adding such restrictions is that certain optimizations may be done. For instance, slots classes take up less memory, as can be measured using Pympler: &#62;&#62;&#62;&#62;&#62;&#62; from pympler import asizeof &#62;&#62;&#62; simple = SimplePosition('London', -0.1, 51.5) &#62;&#62;&#62; slot = SlotPosition('Madrid', -3.7, 40.4) &#62;&#62;&#62; asizeof.asizesof(simple, slot) (440, 248) Similarly, slots classes are typically faster to work with. The following example measures the speed of attribute access on a slots data class and a regular data class using timeit from the standard library. &#62;&#62;&#62;&#62;&#62;&#62; from timeit import timeit &#62;&#62;&#62; timeit('slot.name', setup="from position import SlotPosition; slot=SlotPosition('Oslo', 10.8, 59.9)") 0.05882283499886398 &#62;&#62;&#62; timeit('simple.name', setup="from position import SimplePosition; simple=SimplePosition('Oslo', 10.8, 59.9)") 0.09207444800267695 In this particular example, the slot class is about 35% faster. Conclusion &#38; Further Reading Data classes are one of the new features of Python 3.7. With data classes, you do not have to write boilerplate code to get proper initialization, representation, and comparisons for your objects. You have seen how to define your own data classes, as well as: How to add default values to the fields in your data class How to customize the ordering of data class objects How to work with immutable data classes How inheritance works for data classes If you want to dive into all the details of data classes, have a look at PEP 557 as well as the discussions in the original GitHub repo. In addition, Raymond Hettinger’s PyCon 2018 talk Dataclasses: The code generator to end all code generators is well worth watching. If you do not yet have Python 3.7, there is also a data classes backport for Python 3.6. And now, go forth and write less code! Source: The Ultimate Guide to Data Classes in Python 3.7 – Real Python

    Read at 05:50 pm, Dec 3rd

  • Seeding your Database with Thousands of Users using Knex.js and Faker.js

    Why have I been blocked? This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data. Source: Seeding your Database with Thousands of Users using Knex.js and Faker.js

    Read at 11:11 am, Dec 3rd

  • Millennials in China Are Using Nudes to Secure Loans - VICE

    This article originally appeared on VICE AU.Microloan systems have revolutionised the way we shop. Desperate for the latest, very slightly updated iPhone? Sign up for a month-to-month plan and break that price tag down into manageable morsels. Always wanted a jacuzzi but too cash poor to front up for it? Sign up to Afterpay and for a series of $10 monthly instalments you could have that tub paid off in 60 years. It’s the way of the future, and Chinese millennials are diving in headfirst. According to the latest research from financial technology company Ant Financial, 45 million of the 170 million people born after 1990 in China have an Ant Check Later microloan account, the ABC reports. They’re not just using them to buy big ticket items like TVs and Teslas, either—some fintech companies are also letting people pay for small daily purchases like burgers or biscuits on a long-term, monthly instalment basis. In a country where cost of living is high and the chances of getting a credit card are relatively low, this new form of e-commerce has opened up a world of possibilities for a whole lot of Chinese millennials. Because it’s 2018, though, there’s also a dark side to the system. Sure, you can get a 475 gram box of Oreos and pay it back in monthly instalments of 41 cents over three years, or go jetski-shopping with peanuts to your name. But first you might have to send some nudes. A number of dodgy lenders have realised that young shoppers are desperate for loans, and are demanding that customers hand over naked selfies as collateral. If the repayments aren’t made on time, the money lenders threaten to leak those selfies to the individual’s family and friends. Many also charge interest on the original loan, thus burying their victims further in debt and forcing them to send more pictures and videos. These kinds of transactions are known in China as “naked loan services.” In 2016 a total of 10 gigabits of nudes from 161 young women—all of who were holding their photo IDs—were leaked online by microlenders. Most of the victims were aged between 19 and 23, and typically borrowed sums of money between $1,000 and $2,000, according to state media outlet China Youth Daily. Others were reportedly given the option to do sex work in order to pay off their loan. So rampant is the problem of naked loan services in China that last year the country’s financial regulators vowed to crack down on unlicensed microlenders, Reuters reports. A multi-ministry task force said that “Amid the rapid development of cash loans—while they have played a role in meeting the normal credit needs of some groups—problems such as over-lending, repeat borrowing, improper collection, abnormally high-interest rates, and privacy violations have become prominent.” Since then, new rules have been introduced forbidding unlicensed organisations and individuals from conducting a lending business. Nonetheless, local media reports suggest that the problem is still rife on social media.Source: Millennials in China Are Using Nudes to Secure Loans &#8211; VICE

    Read at 08:06 am, Dec 3rd

  • Email from reader: His favorite and most useful poker tell

    Below is an edited email from a reader, Jeremy G of California, who wrote about the content of mine he’d found most useful. I wanted to share this because I agree with him; I think verbal tells are very important in your average low to mid-stakes cash games, where there is a good amount of loose during-hand talking from not-very-aware players. And I agree with him that this stuff is powerful, once you key into it. These are all reasons the book I’m most proud of is Verbal Poker Tells; I think it contains some of the most unique and reliable poker tell information available. I spent 8 months, full-time, working on it and learned a lot in the process of researching it and writing it. Below he talks about the concept of the weak-hand statement: in other words, statements that imply weakness about the speaker’s hands. For example: “I’m bluffing,” or “I don’t have a full house.” These can be quite obvious and surface-level (like those two previous examples) but they can also be quite indirect/subtle (and that’s something I go into detail about in my book). But for the email below, the reader is talking about how players betting strong hands are fine eliminating strong hands from their range (e.g., “I don’t have quads”) whereas that’s something bluffers hardly ever will do. The email: I play a home game once or twice a week. Amateurs but  stacks are between 1k and 10k. I am most of the way through your video series; it’s a nice review but probably a bit expensive for folks who have absorbed your books.  Anyway, I enjoy it. I wanted to tell you the piece of information that was most helpful for me from all your work.  The fact that bluffers will avoid making weak-hand statements; that players with very strong hands will be willing to make weak-hand statements. This tip has been extremely useful to me in my game. Here is how I use it: someone makes a big bet on the river into a big pot, I ask them if they have the biggest hand possible. Usually something like “I think you hit quads on the turn.  Can you tell me that at least?  Do you have quads again?  I think you either are bluffing or you hit quads.”  Then I gauge the response. Not just whether they are willing to exclude the massive very unlikely hand, but other comfort/distress behaviors.  Then I decide what to do with my bluff-catcher of a hand. Here is why it is so helpful to me:1) These are usually big situations.  Big river bet into a big pot. A huge swing for me if I can get it right.2) It helps me get information that I can use immediately in that moment not somewhere down the line on a later street.3) I can use this tip to proactively get info from my opponent . .  I am not a big talker usually in these situations but this gives me something specific to ask for.  I don’t need to have paid much attention prior to this moment. 4) Because it gives me something to ask about I can also gauge their general comfort level etc., and not just the willingness to eliminate a hand from their possible holdings.5) I have found it quite reliable with my buddies.  For me I find your work most useful for those big bet decisions.  We all have played together for years and are usually drinking and talking and getting up for drinks a lot so it is much harder to notice the small stuff like whether a guy is looking at me when I bet pre-flop or not. But if I can get just a little clarify from his behavior in those big bet moments, on the river usually, and just have a little more certainty that he is not bluffing or that is likely is, it makes a huge difference in my win rate. Last night I got to use this approach to a buddy’s big big river bet. By the time I called a really tough call I was quite sure I was making the right decision and that he was bluffing and indeed he was. And that made me 3-4k. I might have gotten there anyway, without your help, but not every time, and I have a lot more confidence and know what to look for. I liked this email because he does get into some good points about how to best make use of these patterns. For one, the approach of asking questions should be used sparingly, as you don’t want your opponents to figure out that you’ve got an approach to interpreting/analyzing their statements. Obviously these are things that good/experienced players aren’t likely to fall for. But most profit in poker comes from fairly clueless and overly confident players, and the more you can extract from those players, the better you’ll do. You might be surprised; even in quite high-stakes games you’ll see a good amount of these kinds of tells. Thanks for being on my mailing list! If you haven't already, take advantage of 25% off the complete Verbal Poker Tells package (including the complete Verbal Poker Tells book, bonus articles, auido interviews, 32-page guide on Poker Tells at the Windy City Poker Tour, and a 1.3 hour video poker tells seminar). If this is a mistake and you're not on my list, signup here&#13; Related Source: Email from reader: His favorite and most useful poker tell

    Read at 07:34 am, Dec 3rd