content
stringlengths 7
2.61M
|
---|
Presently, user equipment, such as wireless communication devices, communicate with other communication devices using wireless signals, such as within a network environment that can include one or more cells within which various communication connections with the network and other devices operating within the network can be supported. Network environments often involve one or more sets of standards, which each define various aspects of any communication connection being made when using the corresponding standard within the network environment. Examples of developing and/or existing standards include new radio access technology (NR), Long Term Evolution (LTE), Universal Mobile Telecommunications Service (UMTS), Global System for Mobile Communication (GSM), and/or Enhanced Data GSM Environment (EDGE).
While operating within a network, the standard will define the manner in which the user equipment communicates with the network including initiating a new connection or refreshing an existing connection that has somehow become stale, such as for example where synchronization between the user equipment and the network access point has been lost.
As part of a low level acquisition process, when attempting to initiate a connection to a network having a cellular structure, the user equipment can at least sometimes attempt to discover and acquire signaling from each of the nearby cells. This can involve receiving corresponding synchronization signals, which can include a respective primary and a respective secondary synchronization signal. In LTE, acquisition of a primary synchronization signal is initially attempted from which symbol timing and a partial cell identification can be determined. Various determinations of cross-correlations relative to a received signal with each of a predetermined set of synchronization signals can be used to determine the likely partial cell identification, such as the physical layer identity. Further more detailed information can then be determined through a subsequent acquisition of a secondary synchronization signal, including the frame timing, the rest of the cell identity, as well as other potential communication details, such as transmission mode and/or cyclic prefix duration.
The present inventors have recognized, that the manner in which the predetermined set of synchronization signals including the secondary synchronization signals are selected from a list of possible sequences, and are mapped for use to the various cells and the corresponding cell identities can determine the relative ease with which the synchronization signal can be received and distinguished. By limiting which sequences can be used together including defining a mapping rule between a cell identity (ID) and relative cyclic shifts of multiple maximum length sequences, the cross-correlation performance can be enhanced, so that the potential for cell ID confusion during cell detection can be reduced. |
from __future__ import division
from keras import backend as K
import numpy as np
import tensorflow as tf
from keras.losses import binary_crossentropy
def dice_coef(y_true, y_pred):
smooth = 1.
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
def dice_coef_numpy(y_true, y_pred):
smooth = 1.
y_true_f = np.ndarray.flatten(y_true)
y_pred_f = np.ndarray.flatten(y_pred)
intersection = np.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (np.sum(y_true_f) + np.sum(y_pred_f) + smooth)
def bin_crossentropy_loss(y_true, y_pred):
return binary_crossentropy(y_true, y_pred)
def iou_score(y_true, y_pred):
smooth = 1.
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
return (1. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
def dice_coef_loss(y_true, y_pred):
return -dice_coef(y_true, y_pred)
def dice_coef_log_loss(y_true, y_pred):
return -K.log(dice_coef(y_true, y_pred))
def iou_score_loss(y_true, y_pred):
return -iou_score(y_true, y_pred)
|
#[derive(Debug)]
pub struct Input {}
impl Default for Input {
fn default() -> Self {
Self {}
}
}
|
<reponame>hhoshino0421/SecurityMachineLearning<filename>ch3/SecurityMachineLearningCH3/MalwareDataFileRead.py
import pandas as pd
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import ExtraTreesClassifier
def malware_data_read():
# データの読み込み
malware_dataset = pd.read_csv('MalwareData.csv', sep='|')
# データセットから名前、MD5ハッシュ値、ラベルといった列を除外してx_objに代入
x_obj = malware_dataset.drop(['Name', 'md5', 'legitimate'], axis='columns')
# データセットのレベル列のみを抽出してyに代入
y_obj = malware_dataset['legitimate']
# ExtraTreesClassifierを使用
fast_select = ExtraTreesClassifier().fit(x_obj, y_obj)
# SelectFromModelを使用して
# ExtraTreesClassifierによる分類結果に寄与した重要度の大きい特徴量のみを抽出
model_obj = SelectFromModel(fast_select, prefit=True)
# 重要度の大きい特徴量のカラム名を取得
feature_idx = model_obj.get_support()
feature_name = x_obj.columns[feature_idx]
# Xに選択した特徴量のみを代入し直す
x_obj_2 = model_obj.transform(x_obj)
# 重要度の大きい特徴量のカラム名を設定
x_obj_2 = pd.DataFrame(x_obj_2)
x_obj_2.columns = feature_name
return x_obj_2, y_obj, malware_dataset
|
Here was a beginning: A college coach, sitting in the living room of a high school All-American who's slumped in a beanbag chair half-asleep and hardly paying attention. The first time he met Andre Johnson, Chuck Pagano remembers walking out of the house and his boss mumbling, "This guy don't want to go to Miami."
No. Not at first. That boss was Butch Davis, head coach of the Hurricanes. Pagano coached the defensive backs. It was 1999. Johnson was the recruit half the country was chasing, the prospect who'd bloomed in The U's backyard — his high school sat six miles from Miami's campus — but resisted, initially, starring for his hometown school.
Johnson had his pick of suitors. Miami would wait in line like everybody else.
So Pagano worked at it. He got to know Johnson's mom, his uncle, his younger brother. He'd drag his wife to Johnson's high school basketball games and wait patiently outside the locker room afterward. One night, Johnson strolled out decked head-to-toe in red and gold USC garb.
"Andre, this is how you're going to treat me?" Pagano said, smiling.
Johnson politely turned his hat around.
Then Pagano became part of the family. He persuaded the Miami kid to stay home and watched him become the best receiver on the best college football team of the 2000s. Watched him become the No. 3 pick in the NFL Draft, one of the premier wideouts in the game and the best player in Houston Texans history.
Watched, too, as Johnson stayed silent and remained selfless — an anomaly in this me-first receiver generation — while 11 different starting quarterbacks shuffled through town and 12 seasons in Houston produced all of two playoff wins.
The coach and the receiver stayed close. The past few years, they'd meet at midfield after games, Pagano now leading the Colts, Johnson the Texans' veteran whose career was fading fast. They'd hug. "How's your mom?" his old coach would ask. "How's your uncle? How's your brother?"
Beneath the pleasantries, Pagano saw it. Years of frustration had worn Johnson's passion thin. That half-asleep kid slumped in the beanbag chair all those years ago? He'd lost his love for the game. His divorce from the Texans in March left him without a football team for the first time since he was six years old.
Then Chuck Pagano realized something.
He had the chance to recruit Andre Johnson all over again.
Here was an end: Houston's second-year head coach, Bill O'Brien, summoning the franchise's greatest player into his office, a loyal employee with 12 years of service, 13,597 receiving yards, 64 touchdowns and seven Pro Bowls to his name. He's the only Texan who's lasted through a decade of NFL mediocrity.
Andre Johnson couldn't believe what he heard next. O'Brien told him he'd only start certain games next season. That he'd only catch about 40 passes — less than half his career average. Johnson's role, apparently, was shrinking.
The receiver shook his head. Then he laughed. It's all he could do.
"You should trade me or release me," Johnson told O'Brien. "Because if that's going to be how it is, you're going to have a player who's miserable."
He walked out of the office and called his agent.
"It's over," he told him. "I'll be playing for someone else next year."
The Texans granted his wish a few days later and cut him. For the first time in his career, Johnson, who'll turn 34 in July, was a free agent.
"I think they wanted to go in a different direction and just didn't know how to tell me," says one of the newest Indianapolis Colts. "Deciding who was going to start six months before the season? I've never heard of that in my life. And I caught 85 balls last year. It didn't add up. Don't tell me what my role is going to be when we haven't even started workouts."
It was a painful split mixed with a sigh of relief. Houston was the only NFL city Johnson had ever known. It had become home. (Construction on his retirement house is wrapping up there this summer.) But it was time. He knew it. The late-career contract squabbles, management's inability to provide him a stable quarterback, his vanishing role under the new coaching staff — each had buried him deeper in frustration. It all led to one unavoidable conclusion. Johnson would not finish his career in Houston.
He walked off the field at NRG Stadium after last season's finale — a game in which he caught 10 passes for 134 yards and a touchdown, a vintage Johnson performance — yet nonetheless knew his fate.
"The reporters asked me if it was my last time in a Texans uniform, and I told them no," he says now. "But deep down inside I knew it was."
Johnson made his way around the locker room that afternoon, pulling aside close friends — running back Arian Foster, receiver DeAndre Hopkins — to break the news. He wouldn't be back. This was goodbye.
"They looked at me like I was crazy," Johnson recalls. "They didn't believe me. They're like, 'No, man, you'll be here forever.'"
"I basically watched him those last few years lose his love and passion for the game," Melton says. "They'd been telling him for years, 'We're going to put the pieces around you, we're going to get it done.' Well it never happened. They didn't give him a quarterback for years."
They did. But those quarterbacks were named David Carr and Sage Rosenfels and Matt Schaub and Case Keenum. None stuck.
"Everyone saw the frustration the last few years," Johnson admits. "Not only in me, but in my play on the field."
"I've been watching him play football since he was six years old," his mom, Karen Johnson, adds. "I could see the unhappiness during the games and after the games."
The news of his release broke while Johnson was relaxing on the couch in Miami. The phone rang. "What you going to do?" came the caller.
The two former Miami teammates and close friends had found themselves stuck in similar predicaments: Both had seen decade-long stays in the only NFL cities they've ever known come to a close. Just as Johnson was exiting Houston, Gore, a five-time Pro Bowl running back, was leaving San Francisco. Both, too, knew their time in the league was running out. Both knew what they wanted in their next team: A chance at a world championship.
"What teams are you thinking about?" Johnson asked.
"I think we can win the Super Bowl if we go to Indy," Gore said.
"That's funny you say that," he said. "Because I was thinking the same thing."
Here was one of the NFL's premier players doing what he often did when the playoffs started: Watching from home. It was Jan. 5, 2014 and Andre Johnson was sitting on the couch, flipping through channels. The Colts were hosting the Chiefs in a Wild Card matchup. Johnson saw the score — Chiefs 38, Colts 10 in the third quarter — and quickly clicked away.
"They were getting blown out," he remembers. "I was like, 'This game's over.' "
A half hour later he flipped back. And he saw a quarterback do something he'd never seen a quarterback do in his life.
Johnson watched Colts QB Andrew Luck hand the football off to Donald Brown; watched Brown fumble; watched the ball ricochet off a lineman and into the backfield; watched Luck scoop the football up at the 5-yard line and, in a moment of utter football improvisation, barrel forward into the endzone.
Johnson couldn't believe it. He looked up at the score. Luck had pulled the Colts within three.
"That's the first time I really started to think, 'Man, this kid is special,' " Johnson recalls.
The Colts would triumph 45-44 that day, overcoming the second-largest deficit in NFL playoff history. The memory stayed with Johnson during free agency 15 months later. After he left O'Brien's office that day, knowing it was over in Houston after 12 seasons, Johnson's agent asked him to list the teams he'd want to play for.
The list starts with Indianapolis, he said.
Johnson replied with two words: "The quarterback."
There was the team that had climbed one round further in the playoffs each of Luck's three seasons. The way Johnson saw it, they were just a few pieces away. He and Gore could be those pieces.
And there was the final selling point: The glistening Lombardi Trophy that sat on the desk of Colts owner Jim Irsay when Johnson walked into his office.
"I was like, now that's what I'm talking about," Johnson says. "That's the only reason you play this game. That's it. That's what it's all about."
He and Gore made the trip together and signed with the Colts hours apart. Two old Miami guys, each with decorated careers in cities they've left behind, each chasing what has eluded them their entire career. Johnson refutes the notion he signed with the Colts — perpetual bullies in the AFC South, a thorn in the side of the Texans since their NFL inception in 2002 — so he could rub his good fortune in Houston's face.
"This decision has absolutely nothing to do with the Texans," Johnson says sternly.
"This decision has everything to do with winning a Super Bowl."
Here was a quote that told his whole story: "He's probably the best quarterback I've ever played with," Johnson said of Andrew Luck.
This came after three practices together.
Johnson's late-career change of address has reinvigorated his passion for the game. His mom hears it in his voice. His uncle sees it in his body language. Pagano senses it on the practice field.
For Andre Johnson, football is fun again.
"The last few years in Houston, his voice would just be so dry, so quiet," Karen Johnson says of her son. "Now he's so upbeat. He's always smiling. You can just feel the excitement."
"It's like when he first came into the league," Melton says. "He loves Andrew, he loves T.Y. (Hilton), he loves (offensive coordinator) Pep Hamilton."
Instead of pressing new teammate Coby Fleener for the rights to jersey No. 80, Johnson sought a fresh start. He's going with 81. It marks the year of his birth. He even changed his shoulder pads. ("I don't want anything I had in Houston," he says.) With the Texans, he stood out from the moment he arrived, the top draft choice charged with pulling an expansion team into relevance.
With the Colts all he wants to do is fit in. And do something he's never done in his career: Win in January.
"When you come from Miami, you're used to winning," says Gore, whose locker sits right next to his close friend's. "I think it was tough on him in Houston. 'Dre knows, just like I know, that all the stats don't mean nothing if you don't have a shot at that trophy."
Pagano says it feels like Johnson's been with the team for five years. And they haven't even started training camp. That kid he met all those years ago, who sat in that beanbag chair half-asleep and hardly paid attention during that recruiting visit? He's found a new home. And he likes his new home.
After Johnson's first workout with the Colts, he fired off a text to his uncle.
"I see why they win," he wrote. "I see why they win." |
In recent years, study on organic compounds of germanium (a homologue of carbon) has actively been conducted, and many study results have been presented or published. Thus, attention is being paid to organogermanium compounds in various fields, particularly medical and pharmaceutical fields.
For example, it is reported that carboxyethylgermanium sesquioxide (Japanese Patent Publication No. 2498/1971) which is an organogermanium compound formed by bonding of a propionic acid derivative of germanium and oxygen atom at a 2:3 ratio shows a hypotensive action to spontaneous hypertensive rats, an amyloidosis-alleviating action, a macrophage-augmenting action, an interferon-inducing action, an antitumor action, etc. The above sesquioxide is in trial use clinically.
The above carboxyethylgermanium sesquioxide is a compound represented by a chemical formula (Ge--CH.sub.2 --CH.sub.2 --COOH).sub.2 O.sub.3 The so far developed organogermanium compounds are not restricted to the above compound alone and include cylic compounds represented by the following general formula. ##STR3## On the above cyclic compounds, patent application was made by Japanese Patent Application Kokai (Laid-Open) No. 267591/1986.
The above cyclic compounds contain a Ge atom as a ring-forming element. Since germanium atom is tetravalent, if there is developed an organogermanium compound of different chemical structure which contains a germanium atom in the form of, for example, a spiro-atom, it is highly possible that such an organogermanium compound find novel utility.
However, there has hitherto existed no organogermanium compound which contains a germanium atom in the form of a spiro-atom. Therefore, it has been desired to develop such an organogermanium compound and its useful application. |
The effects of parathyroid hormone and alendronate alone or in combination in postmenopausal osteoporosis. BACKGROUND Parathyroid hormone increases bone strength primarily by stimulating bone formation, whereas antiresorptive drugs reduce bone resorption. We conducted a randomized, double-blind clinical study of parathyroid hormone and alendronate to test the hypothesis that the concurrent administration of the two agents would increase bone density more than the use of either one alone. METHODS A total of 238 postmenopausal women (who were not using bisphosphonates) with low bone mineral density at the hip or spine (a T score of less than -2.5, or a T score of less than -2.0 with an additional risk factor for osteoporosis) were randomly assigned to daily treatment with parathyroid hormone (100 microg; 119 women), alendronate (10 mg; 60 women), or both (59 women) and were followed for 12 months. Bone mineral density at the spine and hip was assessed by dual-energy x-ray absorptiometry and quantitative computed tomography. Markers of bone turnover were measured in fasting blood samples. RESULTS The bone mineral density at the spine increased in all the treatment groups, and there was no significant difference in the increase between the parathyroid hormone group and the combination-therapy group. The volumetric density of the trabecular bone at the spine increased substantially in all groups, but the increase in the parathyroid hormone group was about twice that found in either of the other groups. Bone formation increased markedly in the parathyroid hormone group but not in the combination-therapy group. Bone resorption decreased in the combination-therapy group and the alendronate group. CONCLUSIONS There was no evidence of synergy between parathyroid hormone and alendronate. Changes in the volumetric density of trabecular bone, the cortical volume at the hip, and levels of markers of bone turnover suggest that the concurrent use of alendronate may reduce the anabolic effects of parathyroid hormone. Longer-term studies of fractures are needed to determine whether and how antiresorptive drugs can be optimally used in conjunction with parathyroid hormone therapy. |
A unified theory of Taylor Swift’s reputation
Taylor Swift knows exactly what you think of her. And she wants you know that she doesn’t care.
To show just how much she doesn’t care, she devoted the release cycle for her latest album, Reputation, to expressing how much it doesn’t bother her when people don’t like her. (The tour for Reputation begins May 8.)
Swift announced Reputation by deleting all of her old social media posts, replacing them with a video of a snake hissing, in what appeared to be a reference to her reputation as a lying snake. The video for her first single off Reputation, “Look What You Made Me Do,” concluded with a lineup of Swifts spouting the most common critiques of Taylor Swift at each other: Her surprised face is annoying and fake; she’s constantly playing the victim.
The subtext was clear. Taylor Swift knows that some people don’t like her, and she knows why. And she wants to be very clear that she doesn’t like them either, and that for the record, none of the bad things she’s done are actually her fault. It’s all stuff that someone else made her do.
“Look What You Made Me Do” ushered in the age of the New New Taylor (as opposed to the Old New Taylor circa 1989), and the response was not welcoming. Vulture declared it “the worst music of her career.” USA Today said Swift had “never been more exhausting.”
The chilliness of the reception that greeted New Taylor was on one level surprising, given how much goodwill she had going into this latest album cycle. Just before she announced Reputation, Swift was at the center of a high-profile lawsuit involving a radio DJ who groped her during a meet-and-greet. Swift handled the case with aplomb, gave an endlessly quotable testimony, and — in a particularly classy move — sued for only $1 in damages, just to show that she was only bothering with the trial out of sheer principle. Her social capital skyrocketed. After a very rocky 2016, Swift successfully used the trial to reposition herself as someone worth rooting for.
And then she dropped “Look What You Made Me Do,” and while her fan base was ecstatic, cultural critics were less than impressed.
It wasn’t just that the song wasn’t great, critical consensus went: It was that the persona Swift was debuting with “Look What You Made Me Do” was neither interesting nor timely — especially after last summer’s #KimExposedTaylorParty seemed to leave her perfectly positioned to abandon her good-girl persona and make a heel turn.
“She squandered that chance to play the villain,” opined NPR. “She'd rather be the victim, which is a stale posture for her by now.”
But Swift’s refusal to “go dark” with her persona is consistent with the basic paradox that has defined her celebrity image for as long as she has been famous.
Since the beginning of her career, Swift’s celebrity image has been caught in a tug-of-war between intimacy and control, one characterized by two distinct identities: Taylor Swift, nerdy teen and girl next door, who just happens to naturally be able to give voice to your deepest feelings in her songs; and Taylor Swift, micromanaging CEO of a billion-dollar business whose marquee product is her own public image. Both sides are fundamental to Swift’s appeal — but they are also antithetical to each other. When the two sides of her persona clash, they cancel each other out, resulting in a Swift backlash like the one that’s formed heading into Reputation.
With “Look What You Made Me Do,” Swift appears to be addressing the moment in her career in which the calculating and controlled part of her nature was most fully on display. NPR is not alone in suggesting that it’s the perfect time for her to take advantage of this moment and embrace her calculating side, making a heel turn and developing a new identity as a pop music villain: Think piece after think piece emerged all but begging Swift to stop playing the victim and have some fun being bad.
But Swift, who has maintained a strict wall between her two personas, tried to play it both ways: be the put-upon victim in her songs, but continue to coldly calculate her public persona. She was drawing her listeners close with one hand and then showing how she did the magic trick with the other. The split between her two selves had never been more apparent. And the audience turned away.
While Swift is still a major force on Billboard, Reputation’s singles haven’t had anywhere near the staying power that 1989’s did. As USA Today points out, in 2014, Swift’s “Shake It Off” spent 12 weeks at No. 1 before being dethroned by her next single, “Blank Space”; this year, “Look What You Made Me Do” spent only three weeks at No. 1 before being dethroned by Cardi B’s “Bodak Yellow.” And Swift’s follow-up single, “Ready For It,” debuted and peaked at No. 4 before tumbling down the charts.
Reputation is set to emerge not with a bang but with a whimper — and that’s in part because, for the first time since Swift first emerged into the cultural consciousness, the two sides of her persona are not cohering into a single sympathetic identity. Here’s how that fundamental clash has played out throughout Swift’s career, and why it’s getting in her way now.
In early profiles, Swift is either a maniacal control freak or a Disney princess devoted entirely to her fans
Our song is a slamming screen door, sneaking out late tapping on your window.
Kevin Winter/Getty Images
In 2008, Jon Caramanica profiled Swift, then 18 years old, for the New York Times as she made her way through the press tour for her second album, Fearless. The resulting profile hit most of the beats of the traditional early Taylor Swift profile — her precocity, her wholesome blondness — but it lingered on one idea in particular: Swift’s persona insisted on a profound intimacy with her fans, on the idea that their feelings were her feelings and that there was no barrier between them. And to do so, Caramanica wrote, she had to give up control over her own person. She belonged to her fans.
So as she finished performing the heartbreak ballad “Should’ve Said No” at a concert, Swift “dropped to her knees and bent forward, holding her head still as fans in the front rows patted it concernedly,” in what Caramanica dubbed “a scarily intimate moment but essential to her self-presentation that there is no barrier between her and her songs, and their listeners, the consumers.”
“All in all it was a fair trade,” Caramanica concluded: “intimacy for control.”
In order to create the aching emotional core of her ballads, the narrative went, Swift had to cede ownership of her own person. In order to make her fans feel that they shared the same pain, she had to give herself up to them and their feelings.
But just a year later, as Vanessa Grigoriadis followed Swift around for her first Rolling Stone cover story, the narrative had already flipped. Suddenly, Swift wasn’t selflessly subsumed by her music, lost to herself in service to the great god of teen heartbreak. Instead, she was reimagined as a control freak, ruthlessly single-minded in her pursuit of perfection.
In what would become perhaps the most iconic passage of any Swift profile, Grigoriadis renders Swift having what appears to be a breakdown over a beverage mix-up:
Within 45 minutes, Swift produces two dozen perfect, chewy cookies, which she offers around with a glass bottle of milk. Suddenly, she squints at the jar, and shrieks a little: eggnog. She scours the fridge but comes up empty-handed, irritated by the foolishness of her mother, whom she surmises was shopping absent-mindedly. This cannot be. Snack time is ruined. Then she blinks rapidly and composes herself. "I didn't do that," she says, shaking her head firmly. "Mom did that."
This version of Swift is so determined to be great at everything she attempts that she cannot handle the idea of serving her guests eggnog when only milk will do. Accordingly, the emotional power of her music and the intimacy it engenders with her fan base recedes into the background of the profile. Instead, Swift’s rapport with her fans becomes well-rendered deception, a “game face,” Grigoriadis writes, that “must be tattooed on.”
In the context of this profile, Swift’s most admirable trait is her business acumen. Grigoriadis describes her repeatedly as “very savvy,” noting that “she's been a working songwriter since the age of 13.” The most powerful image the profile affords to Swift’s music is not about its emotional strength so much as Swift’s work ethic: Swift, we learn, used to practice her guitar until her fingers bled, and her mother had to tape them up.
Swift has never been able to fully reconcile the two poles of her persona
She wears high heels, I wear sneakers.
Roger Kisby/Getty Images
The tension established by these two profiles would continue throughout Swift’s career: Everything about her music and her image is so precisely and impeccably crafted that no one can doubt it to be entirely under her control — but on the other hand, the emotions of her music are so messily intimate.
“Her music mixes an almost impersonal professionalism — it's so rigorously crafted it sounds like it has been scientifically engineered in a hit factory — with confessions that are squirmingly intimate and true,” wrote Rolling Stone in 2008.
As the tension between the two sides of Swift’s persona continued to play out in public, one side or the other always appeared to be in doubt.
Press stunts planned by Swift herself tended to place the intimacy of her persona front and center. She sent her fans surprise Christmas gifts; she invited them into her home to play 1989 for them before its official release. In TV interviews, the press clucked: Wasn’t it dangerous?
“Not to sound like worst-case-scenario Andrea,” said British talk show host Graham Norton, “but it sounds like a terrible idea.”
“Taylor, you go above and beyond the call of duty,” said Gayle King. “You have them over to your house, and you’re baking cookies. Who does that?”
Swift, the subtext went, was giving so much of herself over to her fans that she might put herself in danger.
But in in-depth profiles and criticism, the pendulum swung the other way, favoring considerations of Swift’s more calculating side. In the New Yorker in 2011: “Swift’s aura of innocence is not an act, exactly, but it can occasionally belie the scale of her success.” In Vanity Fair in 2013: “Swift cultivates a gawky adorkability in her music videos,” but in fact, “Swift works incredibly hard.” In GQ in 2015: “So is it unfair to categorize Swift as calculating? Maybe, and particularly if you view that term as exclusively pejorative. But calling her guileless would be even crazier.”
It was as though the two sides of Swift’s persona were incapable of being reconciled into a unified whole, as though she could not be both teen heartbreak queen and workaholic millionaire — or at least as though the narrative written about her life could not manage it. Occasionally she seemed to try to bring the two together, tossing out a sound bite that would render her micromanaging Type A side into something that blended more easily with the emotional intimacy of her other side.
“Am I shooting from the hip?” she asked GQ in 2015, after hearing that an unnamed “someone” had described her as calculating. “Would any of this have happened if I was? In that sense, I do think about things before they happen. But here was someone taking a positive thing — the fact that I think about things and that I care about my work — and trying to make that into an insinuation about my personal life. Highly offensive. You can be accidentally successful for three or four years. Accidents happen. But careers take hard work.”
That’s an entirely correct statement: Attaining the level of fame that Taylor Swift has, and maintaining it for as long as she has, does take hard work. It does not happen unless you are willing to be a control freak about your career. But Swift’s business persona seems to have no place in the sweetly aw-shucks persona she’s established with her music.
That’s partly because the two sides of her persona are so closely intertwined in the work she does just out of the public’s sight: in the way she carefully and intentionally rebrands her image every few years, and in the way she works the gossip press.
The two poles of Swift’s persona have helped her successfully revamp her image with every new album cycle
You have pointed out my flaws again, as if I don’t already see them.
Kevork Djansezian/Getty Images for DCP
Every time Swift launches a new album, she tweaks her hair and her style and her talking points to suggest that there’s a new Taylor to go with the new sound. And every time, she’s careful to make sure that the new Taylor is exactly what will silence her critics and delight her fans.
The new Taylor is always carefully crafted as a response to whatever criticism has been thrown her way during the previous cycle. And Swift is able to respond to that criticism because she keeps track of everything everyone says about her, as she told GQ in 2015:
That stuff does matter. Because if enough people say the same thing about me, it becomes fact in the general public’s mind. So I monitor what people say about me, and if I see a theme, I know what that means. I’ve had it happen twice before. In 2010, it was She’s too young to get all these awards. Look how annoying she is when she wins. Is she even good? And then in 2013, it was She just writes songs about guys to get revenge. She’s boy-crazy. She’s a problematic person. It will probably be something else again this year.
Accordingly, 2012 Taylor brought us Red, her most impeccably crafted album to that date, in response to the criticism that she wasn’t even that good. In turn, the pop culture hive mind began to admit that, say what you will about that little Swift girl, but she writes a damn catchy song. And after the “problematic person” critique began to pick up steam in 2013, 2014 Taylor declared herself a feminist, debuted her girl squad, and made a point of saying that her big revenge song wasn’t about a guy but about another girl.
Most effectively, she satirized the critique against her with “Blank Space,” in which she made literal the idea that she was a revenge-happy man-eater. “If I separate myself from it, it’s actually a pretty complex character,” she said. “She’s actually kind of exciting and interesting.”
Image building is the arena in which Taylor Swift the audience’s best friend and Taylor Swift the control freak have the ability to work together most seamlessly: The control freak watches the tides of public opinion and figures out exactly what kind of person it is that the world wants her to be, and then the best friend embodies it.
Or at least, that’s how it worked up until 2016. Exactly as Swift had predicted back in 2015, “something else again” came up to become the new dominant critique of her — only this time, Swift didn’t succeed in neutralizing it when she debuted her new persona in response.
And that’s because the new critique didn’t play out in the field of songwriting or politics. It was about gossip, the other arena where Swift puts both sides of her persona to work at once. In gossip, Swift is all intimacy and all control — and the resulting image is not entirely sympathetic.
Swift works endlessly to control the gossip press, which helps boost her intimacy with fans
There is nothing I do better than revenge.
Michael Kovac/Getty Images for Clear Channel
One of the big criticisms of Taylor Swift is that she writes songs about her ex-boyfriends in what can be interpreted as petty acts of revenge. She gets the last word on the story of their relationship, and almost always, it’s a story where Swift is the heroine and her ex is the villain. John Mayer (probably) is a cold-hearted user in “Dear John.” Jake Gyllenhaal (probably) is clingy and whiny in “We Are Never Ever Getting Back Together.” Harry Styles (probably) is toxic and dangerous in “I Knew You Were Trouble.”
Swift is prone to declaring that criticism of these songs comes “from a place of such sexism.”
“No one says that about Ed Sheeran. No one says that about Bruno Mars,” she said in 2014. “They’re all writing songs about their exes, their current girlfriends, their love life, and no one raises the red flag there.”
It’s true that few male pop stars get the flak Swift gets for writing songs about their exes — but it’s also true that to the best of my knowledge, Ed Sheeran and Bruno Mars aren’t seeding hints about who their songs are about throughout their liner notes and then sending their fans off on a scavenger hunt.
Swift has no such compunctions. The reason fans are pretty sure “We Are Never Ever Getting Back Together” is about Jake Gyllenhaal is because Swift gave them ample reason to think so: “She dressed her video co-star in Gyllenhaal’s clothes and sang about a scarf that she was prominently photographed wearing on a date with Gyllenhaal. They are pretty sure “I Knew You Were Trouble” is about Harry Styles because Swift talked about performing it “when the person the song is about is standing by the side of the stage watching,” right after Styles sat in the audience and listened to her sing it. They are pretty sure “Dear John” is about John Mayer because his name is John. (Mayer, for his part, says he found the song “humiliating.”)
Swift’s official stance on the matter is that she never explicitly says who her songs are about. “I’ve never named names, so I feel like I still have a sense of power over what people say,” she told GQ in 2015. “The fact that I’ve never confirmed who those songs are about makes me feel like there is still one card I’m holding.”
But she also seems to derive just as much power from the idea that her fans will surely guess who her songs are about, and that she’s given them all the information they need to do so. “Every single one of the guys that I’ve written songs about has been tracked down on MySpace by my fans,” she told the New York Times in 2008, back when her exes were non-celebrity randoms from her high school, apparently “giddy” at the idea. When a Rolling Stone writer suggested to her in 2014 that there was little ambiguity regarding who the song “Style” was about (it’s almost definitely Harry Styles), Swift “allows herself a satisfied grin. ‘We should have just called it “I'm Not Even Sorry.”’”
This kind of subliminal storytelling, the kind that gets teased out on gossip blogs and always has “alleged” attached to it, is where the two sides of Swift’s persona work most closely in tandem. She is in total control of her narrative, firmly positioning herself as the righteous and sinned-against party who has the last word, always, and that narrative is profoundly tear-stained and intimate. And if the narrative turns against her, she can always deny it, because the story depends on her confirmation.
What gets Swift into trouble is when that narrative starts to look fake. And that’s what happened to her last year.
The #KimExposedTaylorParty was a case of control overwhelming intimacy
The rumors are terrible and cruel, but, honey, most of them are true.
Graham Denholm/Getty Images
In February 2016, Kanye West released a song called “Famous” in which he rapped, “I feel like me and Taylor might still have sex. / Why? I made that bitch famous.”
Swift denounced the lyric in a public statement. “Kanye did not call for approval, but to ask Taylor to release his single ‘Famous’ on her Twitter account,” said a spokesperson on her behalf. “She declined and cautioned him about releasing a song with such a strong misogynistic message.” The spokesperson added, “Taylor was never made aware of the actual lyric, ‘I made that [expletive] famous.’”
Later that month, Swift won the Grammy for Album of the Year. And in her acceptance speech, she warned “all the young women out there” that “there will be people along the way who will try to undercut your success. Or take credit for your accomplishments or your fame."
To those who knew about her recent dustup with West, the implication was clear: West was trying to take credit for the fame Swift had worked so hard for, and this was anti-feminist. Swift was just an ordinary woman like anyone else, getting undercut in the workplace by her male colleagues.
It was a vintage Swift gossip operation. She had successfully micromanaged the narrative, and the resulting story had a universal appeal that was simultaneously feminist and spoke to the underdog in everyone: intimate, the way a good Taylor Swift song is. She was winning the game.
And then Kim Kardashian West — Kanye West’s wife and another celebrity who knows how to work a gossip cycle — released a series of videos that appeared to show Swift signing off on West’s lyrics.
At once, the narrative spiraled out of Swift’s control. #KimExposedTaylorParty started trending on Twitter as Swift haters celebrated her fall. They flooded her social media feeds with snake emojis.
Swift tried to disavow the whole thing. “I would very much like to be excluded from this narrative, one that I have never asked to be a part of, since 2009,” she wrote on Instagram in a now-deleted post. But the lie was too blatant to work. Because it was clear that Swift had asked to be a part of the narrative of her feud with Kanye West — had, if anything, amplified it by writing songs about it and talking about it in her Grammys speech — and that her public image had benefited as a result.
The controlling side of Swift’s persona had showed its hand — and that meant the intimate side lost its power. Her attempts to connect with her fans stopped feeling authentic and started to feel like a lie.
“When did you first realize that Taylor Swift was lying to you?” asked the Ringer.
Traditionally, right now is when Taylor Swift revamps her image. But this time around, she’s been having trouble doing it.
Honey, I rose up from the dead, I do it all the time.
Mike Coppola/Getty Images for DIRECTV
As she geared up for Reputation’s release, Swift began New Taylor’s introduction to the public. Traditionally, she would take this opportunity to show us all the ways in which New Taylor renders criticism of the Old Taylor irrelevant — because the haters were right but she has grown as a person and so that doesn’t apply anymore, or because in fact, if you really think about it, the haters were incredibly sexist and unfair and it’s really brave of her to speak out against them.
But this time, that’s not what’s happening. Instead, Swift’s new songs have been about how the haters have made her do bad things and none of it was her fault, and how people have persecuted her unfairly but luckily her new boyfriend is really hot. It is, in other words, a step backward, a move away from the woke feminist persona Swift was playing with circa 1989, and back toward the aggrieved victim who finds her self-worth in boys that she embodied in “You Belong With Me.”
She’s made it clear that she knows exactly what everyone is saying about her, but rather than giving the world a new “Blank Space,” in which she takes ownership of the criticism about her and then turns it around with a self-awareness that reflects positively on her, she’s giving the world “Look What You Made Me Do,” in which she aggressively refuses to take ownership of anything, even as she acknowledges that she knows people think she plays the victim too much. “There she goes, playing the victim again,” one Taylor sneers at another in the video, immediately after singing a song about how everyone else is to blame for everything she’s done.
In part, that’s because Swift taking ownership of this particular criticism — that she’s fake, that she pretends to be an underdog when she isn’t, that she should abandon the stale innocent act and embrace her inner villain — would mean resolving the fundamental tension that has been at work throughout her entire career. If Swift were to admit that she micromanages the narratives she plays out in the press, that she manufactures feuds and then plays on them to make herself seem more vulnerable and hence more sympathetic, then she would be bringing together the intimacy and control sides of her persona in public view. She would be doing exactly the thing that she’s avoided most strenuously throughout her career.
Some of her latest videos even seem to be literalizing the tension between the two poles of her persona. In the video for “Ready For It?” two Taylors battle for dominance: one of them naked and vulnerable, the other black-clad and controlling. In the end, they synthesize together into the form of naked robot Taylor — but actual Taylor Swift doesn’t seem to be willing or able to manage such a fusion.
Swift seems to believe that if she explicitly acknowledges that she is both a Type A control freak and a person with messy, vulnerable feelings, she will lose a vital part of her appeal. And she may not be entirely wrong about that: Traditionally in pop culture, try-hards are villains or sad also-rans, not heroines.
But at this point, Swift’s ability to hold on to her appeal without uniting both halves of her persona is in serious doubt. The controlling and manipulative side of her persona has come into view to an extent that much of her audience is having trouble believing in the authenticity and intimacy of the other side. So even though Taylor Swift knows exactly what you think of her, for the first time in her career, she seems to be at a loss as to how to change your mind.
Update: This article was first published in November 2017. It has been updated to include information on the Reputation concert tour. |
Inside TV, a new magazine aimed at young women, hits newsstands Thursday with a cover interview with hot “Desperate Housewives” star Eva Longoria.
The question is: Will all the publicity be enough for a new weekly with a budget price of $1.99 a copy to start to carve its own niche in the booming but increasingly cutthroat celebrity magazine field?
With its stock down 29 percent year to date and its flagship TV Guide showing a 21 percent plunge in ad pages in the first quarter, parent Gemster TV Guide International – 41 percent owned by News Corp. which also owns The Post – desperately needs a hit.
At least at the outset, the company says it is willing to spend big.
The intent is to show a good side of celebrities in fashion and homes. |
. In a comparative study 151 human sera were tested for IgG and IgM antibodies against Toxoplasma gondii in the Fluorescent-Antibody-Test (FAT) as well as in the Enzyme-Linked Immunosorbent Assay (ELISA) using the same antigen (whole trophozoites of Toxoplasma gondii). A positive correlation was found between the results obtained in FAT and ELISA. The detection of specific IgG antibodies revealed a correlation of 100% and 97.5% in positive and negative sera, respectively. Only 8 out of 111 positive sera showed deviations of more than +/- 1 step within the titre ranges. While detecting specific IgM antibodies a highly significant correlation (99.3%) between FAT and ELISA was obtained for negative sera. 5 positive IgM sera showed titre end-points of 1:64 and 1 serum an end-point titre of 1:256 in FAT as well as in ELISA; however, a comparison was not done because of the small amount of positive IgM sera having been available. |
from discord import Embed, Colour
from discord.ext import commands
from discord import AuditLogAction
from discord.utils import get
from datetime import datetime, timezone
from sqlite3 import connect
class Logs(commands.Cog):
def __init__(self, bot):
self.bot = bot
@staticmethod
def get_data(guild_id):
with connect('data.db') as conn:
c = conn.cursor()
c.execute("SELECT State FROM logs WHERE ID=?", (guild_id,))
entry = c.fetchone()
if entry is None:
c.execute("INSERT INTO logs (ID, State) VALUES (?, ?)", (guild_id, 0))
conn.commit()
return False
return int(entry[0])
@staticmethod
def check_logs(guild, logs=False):
state = Logs.get_data(guild.id)
channel = get(guild.text_channels, name='logs')
return False if ((not state or channel is None) and not logs) else True
@commands.command(hidden=True)
@commands.has_permissions(administrator=True)
async def logs(self, ctx):
await ctx.message.delete()
state = Logs.get_data(ctx.guild.id)
with connect('data.db') as conn:
c = conn.cursor()
if state is None:
c.execute("INSERT INTO logs(ID, State) VALUES(?, ?)", (ctx.guild.id, 1))
elif state:
c.execute("UPDATE logs SET State=? WHERE ID=?", (0, ctx.guild.id))
else:
c.execute("UPDATE logs SET State=? WHERE ID=?", (1, ctx.guild.id))
conn.commit()
state = 'disabled' if state else 'enabled'
await ctx.send(f"Logs {state}", delete_after=5.0)
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
param = error.param.name if isinstance(error, commands.MissingRequiredArgument) else ''
perms = ', '.join(error.missing_perms) if isinstance(error, commands.BotMissingPermissions) else ''
invoke_errors = {
'index': "Index error!",
'is_playing': "I'm not connected to any channel!",
'unpack': "User has no warns !",
'channel': "You're not connected to any channel!",
'Missing Permissions': "I'm not allowed to do this!",
'ValueError': 'Wrong arguments!',
'KeyError': 'Wrong arguments!'
}
errors = {
"<class 'discord.ext.commands.errors.MissingRequiredArgument'>": f'You forgot an argument: {param}',
"<class 'discord.ext.commands.errors.CommandNotFound'>": 'Command not found!',
"<class 'discord.ext.commands.errors.MissingPermissions'>": "You can't use this command!",
"<class 'discord.ext.commands.errors.BotMissingPermissions'>": f'I need the following perms to do this: {perms} !',
"<class 'discord.ext.commands.errors.BadArgument'>": 'You must input an integer!' if 'int' in str(error) else "Membre introuvable !",
"<class 'discord.ext.commands.errors.CommandInvokeError'>": ''.join([value for key, value in invoke_errors.items() if key in str(error)]),
}
clean_error = errors[str(type(error))]
if not clean_error:
raise error
embed = Embed(title="❌ Something went wrong:", description=clean_error, color=0xe74c3c)
await ctx.message.delete()
await ctx.send(embed=embed, delete_after=5.0)
@commands.Cog.listener()
async def on_command_completion(self, ctx):
cmd = ctx.command.name
state = Logs.get_data(ctx.guild.id)
if not Logs.check_logs(ctx.guild, True if cmd=='logs' else False):
return
channel = get(ctx.guild.text_channels, name='logs')
state = 'enabled' if state else 'disabled'
cmd_args = ctx.message.content[len(cmd)+1:].split()
if len(cmd_args)<2:
cmd_args += ['', '']
cmd_list = {
'warn': {'title': ':warning: User warned', 'desc':f"{ctx.author.mention} warned {cmd_args[0]}\n**Reason:** {' '.join(cmd_args[1:])}", 'color': 0xe67e22},
'mute': {'title': ':mute: User muted', 'desc': f"{ctx.author.mention} muted {cmd_args[0]}\n**Duration**: {cmd_args[1]}\n**Reason:** {' '.join(cmd_args[2:])}", 'color': 0xe74c3c},
'clear': {'title': ':wastebasket: Messages deleted', 'desc': f"{ctx.author.mention} deleted {cmd_args[0]} messages.", 'color': 0x1f8b4c},
'poll': {'title': ':clipboard: Poll created', 'desc': f"Question: *{cmd_args[0]}*\nChoices: *{' / '.join(cmd_args[1:])}*\nBy {ctx.author.mention}",'color': 0x7289da},
'logs': {'title': f':printer: Logs {state}', 'desc': f'{ctx.author.mention} {state} logs', 'color': 0x11806a},
}
if not cmd in cmd_list.keys():
return
embed = Embed(title=cmd_list[cmd]['title'], description=cmd_list[cmd]['desc'], color=cmd_list[cmd]['color'], timestamp=datetime.now())
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_remove(self, member):
if not Logs.check_logs(member.guild):
return
entry = await member.guild.audit_logs(limit=1).flatten()
channel = get(member.guild.text_channels, name='logs')
if entry[0].action == AuditLogAction.ban:
embed = Embed(title=':man_judge: User banned', description=f"{entry[0].user.mention} banned {entry[0].target.mention}\n**Reason:** {entry[0].reason}", color=0xe74c3c, timestamp=datetime.now())
elif entry[0].action == AuditLogAction.kick:
embed = Embed(title=':man_judge: User kicked', description=f"{entry[0].user.mention} kicked {entry[0].target.mention}\n**Reason:** {entry[0].reason}", color=0xe74c3c, timestamp=datetime.now())
else:
embed = Embed(description=f'**:outbox_tray: {member.mention} left the server**', color=0xe74c3c, timestamp=datetime.now())
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_unban(self, guild, user):
if not Logs.check_logs(guild):
return
entry = await guild.audit_logs(limit=1).flatten()
channel = get(guild.text_channels, name='logs')
embed = Embed(title=':man_judge: User unbanned', description=f"{entry[0].user.mention} unbanned {entry[0].target}\n**Reason:** {entry[0].reason}", color=0xc27c0e, timestamp=datetime.now())
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_join(self, member):
if not Logs.check_logs(member.guild):
return
channel = get(member.guild.text_channels, name='logs')
embed = Embed(description=f'**:inbox_tray: {member.mention} joined the server**', color=0x2ecc71, timestamp=datetime.now())
await channel.send(embed=embed)
embed = Embed(title=":inbox_tray: New member !", description=f'{member.mention} joined the server', color=0x2ecc71, timestamp=datetime.now())
embed.set_image(url=member.avatar_url)
await member.guild.system_channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_update(self, before, after):
if not Logs.check_logs(before.guild):
return
entry = await after.guild.audit_logs(limit=1).flatten()
channel = get(before.guild.text_channels, name='logs')
embed = Embed(title=":notepad_spiral: Member modification", description=f'{entry[0].user.mention} changed {before.mention}', color=0x99aab5, timestamp=datetime.now())
if before.display_name != after.display_name:
embed.add_field(name="Nickname:", value=f"{before.display_name} → {after.display_name}")
elif before.roles != after.roles:
new_roles = [role.name for role in after.roles if role not in before.roles]
removed_roles = [role.name for role in before.roles if role not in after.roles]
new_roles = "New roles: "+("".join(new_roles) if new_roles else "None")
removed_roles = "Removed roles: "+("".join(removed_roles) if removed_roles else "None")
embed.add_field(name="Roles:", value=f"{new_roles}\n{removed_roles}")
else:
return
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_guild_join(self, guild):
with connect('data.db') as conn:
c = conn.cursor()
c.execute("INSERT INTO logs (ID, State) VALUES (?, ?)", (guild.id, 0))
c.execute(f'CREATE TABLE IF NOT EXISTS "{guild.id}" (User_ID INTEGER, Warns TEXT)')
conn.commit()
channel = await self.bot.fetch_channel(747480897426817095)
invite = await guild.system_channel.create_invite()
embed = (Embed(title='Click to join', url=invite.url, color=0xf1c40f)
.set_author(name=f'Joined "{guild.name}"', icon_url=guild.icon_url))
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_guild_remove(self, guild):
with connect('data.db') as conn:
c = conn.cursor()
c.execute("DELETE FROM logs WHERE ID=?", (guild.id,))
c.execute(f'DROP TABLE"{guild.id}"')
conn.commit()
channel = await self.bot.fetch_channel(747480897426817095)
embed = (Embed(color=0xe74c3c)
.set_author(name=f'Left "{guild.name}"', icon_url=guild.icon_url))
await channel.send(embed=embed)
def setup(bot):
bot.add_cog(Logs(bot)) |
/**
* PMF of the DefaultDataDistribution
* @param <KeyType>
* Type of Key in the distribution
*/
public static class PMF<KeyType>
extends DefaultDataDistribution<KeyType>
implements DataDistribution.PMF<KeyType>
{
/**
* Default constructor
*/
public PMF()
{
super();
}
/**
* Copy constructor
* @param other
* ScalarDataDistribution to copy
*/
public PMF(
final DataDistribution<KeyType> other)
{
super(other);
}
/**
* Creates a new instance of DefaultDataDistribution
* @param initialCapacity
* Initial capacity of the Map
*/
public PMF(
int initialCapacity)
{
super( initialCapacity );
}
/**
* Creates a new instance of ScalarDataDistribution
* @param data
* Data to create the distribution
*/
public PMF(
final Iterable<? extends KeyType> data )
{
super( data );
}
@Override
public double logEvaluate(
KeyType input)
{
return this.getLogFraction(input);
}
@Override
public Double evaluate(
KeyType input)
{
return this.getFraction(input);
}
@Override
public DefaultDataDistribution.PMF<KeyType> getProbabilityFunction()
{
return this;
}
} |
INTENSITY MAPPING OF THE FINE STRUCTURE LINE DURING THE EPOCH OF REIONIZATION The atomic Cii fine-structure line is one of the brightest lines in a typical star-forming galaxy spectrum with a luminosity ∼0.1%1% of the bolometric luminosity. It is potentially a reliable tracer of the dense gas distribution at high redshifts and could provide an additional probe to the era of reionization. By taking into account the spontaneous, stimulated, and collisional emission of the Cii line, we calculate the spin temperature and the mean intensity as a function of the redshift. When averaged over a cosmologically large volume, we find that the Cii emission from ionized carbon in individual galaxies is larger than the signal generated by carbon in the intergalactic medium. Assuming that the Cii luminosity is proportional to the carbon mass in dark matter halos, we also compute the power spectrum of the Cii line intensity at various redshifts. In order to avoid the contamination from CO rotational lines at low redshift when targeting a Cii survey at high redshifts, we propose the cross-correlation of Cii and 21 cm line emission from high redshifts. To explore the detectability of the Cii signal from reionization, we also evaluate the expected errors on the Cii power spectrum and Cii-21 cm cross power spectrum based on the design of the future millimeter surveys. We note that the Cii-21 cm cross power spectrum contains interesting features that capture physics during reionization, including the ionized bubble sizes and the mean ionization fraction, which are challenging to measure from 21 cm data alone. We propose an instrumental concept for the reionization Cii experiment targeting the frequency range of ∼200300 GHz with 1, 3, and 10 m apertures and a bolometric spectrometer array with 64 independent spectral pixels with about 20,000 bolometers. |
Copyright by WWLP - All rights reserved Image Courtesy: Pittsfield Police Department
Copyright by WWLP - All rights reserved Image Courtesy: Pittsfield Police Department
BOSTON (WWLP)—Some Massachusetts lawmakers have concerns after the shooting of a Republican Congressman near D.C. They told 22News this calls the nation's gun control laws into question.
Although Massachusetts requires background checks for gun owners and has strict rules on sellers, other states don't require permits to purchase handguns.
Virginia allows residents to openly carry guns without a permit and doesn't require firearms to be registered.
Lawmakers told 22News the shootings of a congressman and 4 others in Virginia are a tragedy—one that calls for stricter gun laws across the U.S.
"In Massachusetts we're sometimes criticized for having some of the most strict gun laws and background checks but yet we see that we don't often have some of those instances in Massachusetts," said State Rep. Aaron Vega, (D) Holyoke.
But others disagreed.
"Before folks go in talking about gun control and things of that nature, we should stop, pause and remember, again, that if it weren't for people who were armed there, we'd probably be talking about a lot of dead congressmen right now," said State Rep. John Velis, (D) Westfield.
Several lawmakers including Governor Baker have expressed gratefulness for the work of the U.S. Capitol police. According to local reports, the Capitol police returned fire with the gunman. |
Accessory genome of the multi-drug resistant ocular isolate of Pseudomonas aeruginosa PA34 Bacteria can acquire an accessory genome through the horizontal transfer of genetic elements from non-parental lineages. This leads to rapid genetic evolution allowing traits such as antibiotic resistance and virulence to spread through bacterial communities. The study of complete genomes of bacterial strains helps to understand the genomic traits associated with virulence and antibiotic resistance. We aimed to investigate the complete accessory genome of an ocular isolate of Pseudomonas aeruginosa strain PA34. We obtained the complete genome of PA34 utilising genome sequence reads from Illumina and Oxford Nanopore Technology followed by PCR to close any identified gaps. In-depth genomic analysis was performed using various bioinformatics tools. The susceptibility to heavy metals and cytotoxicity was determined to confirm expression of certain traits. The complete genome of PA34 includes a chromosome of 6.8 Mbp and two plasmids of 95.4 Kbp (pMKPA34-1) and 26.8 Kbp (pMKPA34-2). PA34 had a large accessory genome of 1,213 genes and had 543 unique genes not present in other strains. These exclusive genes encoded features related to metal and antibiotic resistance, phage integrase and transposons. At least 24 genomic islands (GIs) were predicated in the complete chromosome, of which two were integrated into novel sites. Eleven GIs carried virulence factors or replaced pathogenic genes. A bacteriophage carried the aminoglycoside resistance gene (AAC-IId). The two plasmids carried other six antibiotic resistance genes. The large accessory genome of this ocular isolate plays a large role in shaping its virulence and antibiotic resistance. Introduction Pseudomonas aeruginosa is associated with many opportunistic and nosocomial human infections such as pneumonia, septicaemia, corneal ulcers (microbial keratitis) and chronic infections in cystic fibrotic lungs. Antibiotic resistance in this bacterium is alarmingly on the a1111111111 a1111111111 a1111111111 a1111111111 a1111111111 rise and P. aeruginosa has been included in one of the top three priority pathogens urgently requiring new antimicrobial therapies for treatment by the World Health Organization. Resistance to different antimicrobials in P. aeruginosa is due to its inherent capacity to oppose the action of antibiotics and its capacity to acquire genetic elements that often carry antibiotic resistance genes. The study of the mechanisms used by different strains of P. aeruginosa to become resistant to antibiotics or acquire virulence have benefited from genome sequencing and these have identified a number of mobile genetic elements (MGEs). However, many of the genomes investigated are not completely closed and, in this context, accessory genes associated with resistance or virulence in addition to mutations may be missed. This may limit the understanding whether resistance and virulence genes are present on MGEs or "standard" chromosomal regions as well as their prevalence in general. For example, less than 5% of P. aeruginosa draft genomes are complete; furthermore, only 37 plasmids of the total (3003 as of 15/10/2018) in the NCBI P. aeruginosa database are complete. Additionally, many of the isolates sequenced are derived from cystic fibrosis infections, while relatively few ocular and other isolates are represented. This is an important source of genetic information for P. aeruginosa as specific subpopulations are thought to be associated with microbial keratitis. Notably, those subpopulations are predominantly characterised by possession of genes associated with type IV pili twitching motility, cytotoxicity (exoU), and certain genomic islands. Indeed, to date, the complete genome of only one P. aeruginosa keratitis isolate has been published. Very little information is available about the accessory genomes of ocular isolates. P. aeruginosa strain PA34 (referred to as PA34 hereafter) is a multi-drug resistant microbial keratitis isolate which is resistant to gentamicin, imipenem, ciprofloxacin and moxifloxacin. Analysis of its draft genome revealed that PA34 belongs to sequence type 1284 based on multilocus sequence typing and carried at least 12 acquired resistance genes and possessed the exoU gene, an important effector gene in the pathogenesis of microbial keratitis. A class I integron (In1427) that carries two antibiotic resistance genes has been shown to be integrated into a Tn3-like transposon carried by PA34. However, the genetic context of these resistance and pathogenic genes has not been completely elucidated. Hence, in this study we sought to analyse the complete genome of PA34, to examine the genetic structure of accessory genome and to compare the complete genome of PA34 with other genomes of P. aeruginosa from the public database. Bacterial strain and microbiology The strain Pseudomonas aeruginosa PA34 was isolated in 1997 from the cornea of a microbial keratitis patient in a tertiary eye care centre L.V. Prasad Eye Institute, Hyderabad, India. The cause of microbial keratitis was recorded as trauma induced by a stone in the right eye of a 21-year old male. Three complete genomes of P. aeruginosa were used for comparison: I) P. aeruginosa PAO1, which has the most complete and curated annotations, II) P. aeruginosa PA14, an exoU positive strain and III) P. aeruginosa VRFPA04, an Indian microbial keratitis isolate. The minimum inhibitory concentration (MIC) to three heavy metals (mercury, copper and cobalt) was determined by broth dilution methods as described elsewhere with minor modification. PA34 and PAO1 (as the control strain) were examined against Hg ++, Cu ++ and Co ++ by using twofold serial dilutions from 16mM-0.31mM. The metal salt solutions (HgCl 2, CuCl 2 and CoCl 2 ) were prepared in deionised water, sterilized by membrane filtration and added to Mueller-Hinton broth (Oxoid Ltd, Hampshire, UK) to obtain the required concentrations. The experiments were performed in triplicate and repeated three times. Wilcoxon matched-pairs signed rank test was used to confirm significant difference between metal tolerance and the strain. A p-value of <0.05 was taken as significant. Cytotoxicity was examined by the trypan blue dye exclusion assay. Briefly, human corneal epithelial cells (HCEC) were grown in 96 well plates in the presence of SHEM (DMEM (Gibco, Grand Island, NY, USA) supplemented with 10% fetal bovine serum (Gibco), 1.05mM CaCl 2, 0.5% DMSO, 2ng/mL epidermal growth factor (Gibco), 1% ITS-X (Gibco)). 200L of 5x10 5 CFU/mL P. aeruginosa in SHEM was used to expose confluent HCEC. Following 3 h incubation at 37C, the cells were stained with 0.4% trypan blue. The stained cells were observed by microscopy and photographs were taken for the quantitative determination of cytotoxicity. P. aeruginosa PAO1 (a non-cytotoxic strain) were used as a control. The experiment was performed in triplicate and repeated three times. MinION sequencing and complete genome assembly Genomic DNA was extracted using a Wizard Genomic DNA Purification Kit (Promega, Madison, WI, USA) as per the manufacturer's protocol. The amount of extracted DNA was determined using a Qubit fluorometer (Life Technologies, Carlsbad, CA, USA). The library was prepared using the Ligation Sequencing Kit 1D R9 Version as per the manufacturer's instructions. The sequencing library was loaded into the Flow Cell Mk 1 Spot-ON of the Min-ION system using Library Loading Bead Kit R9 Version according to the manufacturer's instructions. The raw reads were obtained using the MinKNOW v1.7.14 in a 24-h run experiment and base calling was performed using Albacore v2.0.2. A total of 50,831 reads ranging from 174bp to 58,887bp (mean = 3,292bp) were obtained. The sequence reads from Illumina (which was obtained using MiSeq (Illumina, San Diego, CA) generating 300bp paired-end reads ) and MinION data were assembled using three hybrid assembly pipe-lines; Unicycler v0.4.3, Japsa v1.8.0 and Spades v3.12.0. Spades resulted in the best assembly in terms of contig numbers ( Table 1). The genome coverage was calculated using BBmap v35.82. All contigs were reordered with reference to the three complete genomes of P. aeruginosa. (PAO1, PA14, and VRFPA04) using MUMmer v3.0. Gaps between the contigs were determined by ABACAS v1.3.1 using the "circular reference genomes" flag. Pseudogenomes of different sizes were observed after comparison with different reference strains and in all comparisons, contigs 6 and 7 were observed as unused contigs indicating they were not part of the chromosome. This was further verified by performing a BLAST of unused contigs against reference genomes. The fewest gaps between contigs in the PA34 genome (99 bp) were observed when PA14 was used as the scaffold compared to the other strains. Further, the size of the PA34 pseudogenome was slightly less than the size of the draft genome (~6.8 Mbp). Therefore, this comparison was considered as the best and was further used to complete the genome of PA34. Primers were designed for each gap (S1 and S2 Tables) using Primer3web v4.1.0 and the gap size was verified by PCR. Using this approach, we were able to close the gaps between contigs to generate a single contiguous chromosome based on contigs 1-5. Contigs 6 and 7 had a lower G+C content than rest of the contigs and showed similarity with different plasmids based BLASTn searches against NCBI database. Contigs 6 and 7 were therefore estimated to represent two different plasmids and were both circularised, referred to here as pMKPA34-1 and pMKPA34-2 (Plasmid 1 and 2 of Microbial Keratitis strain PA34). Bioinformatics analysis The complete chromosomal genome was annotated using NCBI Prokaryotic Annotation General features of P. aeruginosa PA34 genome The statistics of the complete genome of P. aeruginosa PA34 ( Table 2) were broadly matched with other published complete genomes of P. aeruginosa. A total of 6,462 coding sequences (CDS) were predicted in the 6.8 Mbp genome of PA34 using NCBI Prokaryotic Genome Annotation Pipeline (PGAP). Of the predicted CDS, 6,314 were predicted to form functional proteins and 148 were pseudogenes. In the genomic comparison with three reference genomes (PAO1, PA14 and VRFPA04) and the genome of PA34, it was estimated there were 7,643 orthologs in the pangenome. Of those orthologs, 5078 were common amongst all four strains and are suggested to represent the size of the core genome. PA34 had the largest accessory genome compared to these reference strains (having 1,213 genes ) that had 543 genes unique to PA34. These exclusive genes were determined to encode features related to metal and antibiotic resistance, phage integrase and transposons. Furthermore, in the context of individual reference genomes, PA34 has 886, 737, 946 genes with no orthologs in PAO1, PA14, and VRFPA04, respectively (Fig 1) (See S1 File for full annotations of exclusive orthologs). A high proportion of strain-specific accessory genomic elements are common in P. aeruginosa strains and this represents the diversity of its genome. However, in this study, we observed a lower range (3-10%) of exclusive orthologues than previously reported range (10-20%). The difference observed may be related to the use of the complete genome for the analysis over the use of draft genomes in previous studies. Since draft genomes are likely to be mis-assembled due to the presence of a high content of repetitive sequences in bacteria, analysis based on the complete genome is expected to be more relevant. PA34 shared 124 orthologs with VRFPA04, an eye isolate, and those genes were associated with chloramphenicol resistance, pathogenesis (type IV secretion system) and phages. The diversity of core and accessory genomes observed in this study contradicts findings on environmental species P. fluorescens, where comparative genomics of three isolates demonstrated that they shared a core of 61% genes (vs 66% in this study) and 22-27% of unique genes to each isolate. Furthermore, comparative genomics of three strains of the plant pathogen P. syringae showed a smaller core genome of 56% than that of P. aeruginosa observed in this and another study. The overall low diversity amongst P. aeruginosa strains compared to other Pseudomonas spp. may result from the selection of closely related strains (i.e. those containing exoU) in the present study. No significant CRISPR and associated Cas genes were observed in PA34 based on comparison with the CRISPRCasFinder database. CRISPR-Cas system may be negatively correlated with the size of the accessory genome and acquired antibiotic resistance genes because this system restricts the invasion and incorporation of MGEs. Thus, strains without a CRISPR-Cas system are expected to have a larger genome size. Genomic islands Genomic islands (GIs) refer to blocks of horizontally acquired DNA that integrate into certain loci in the core genome. Such loci are known as Regions of Genomic Plasticity (RGPs). GIs should have a minimum of four contiguous open reading frames, which are not present in any of the set of genomes to which they are compared. More than 80 RGPs have been identified in the genome of P. aeruginosa. The position of RGPs in the genome are indicated by homologous flanking loci in PAO1. RGPs constitute a major portion of the accessory genome and are essential for the adaption of P. aeruginosa in diverse habitats. In this study, 24 RGPs were observed in the complete genome of PA34 (Table 3 and Fig 2) when compared with genomes of P. aeruginosa strains PAO1, PA14 and VRFPA04. A study has reported 27 to 37 RGPs in individual genomes of five P. aeruginosa strains. The difference in number of observed RGPs may be due to a difference in the number of genomes used for comparison. Nevertheless, out of 24 GIs in the current study, two GIs were integrated into loci which have not been reported previously and were deemed as GIs MKPA34-GI1 and MKPA34-GI2 in this study ( Table 3). The GI MKPA34-GI1 was 68.9 Kbp, was integrated between PA2858 and PA2859 homologues of PAO1 and carried genes for mercury and chromate resistance. The GI MKPA34-GI2 had a size of 39.9 Kbp, encodes genes associated with phages and was integrated into loci flanking 4856/4857 of PAO1. In addition, three GIs (RGP23, RGP56 and RGP84) carried phage related genes; phages can be associated with virulence. Our analysis showed that at least five GIs were associated with replacement or insertion of pathogenic genes and one GI (RGP23) carried an acquired aminoglycoside resistance gene (AAC-IId). Three GIs (RGP2, RGP50, and RGP57) were associated with the type IV secretion system. Integrative conjugative elements (ICEs) are chromosomally integrated self-transmissible MGEs that can exist as circular extrachromosomal elements and are antecedents of various GIs. Our analysis revealed three ICEs in the complete genome of PA34. The ICEs observed in RGP5 and RGP29 were related to clc-like ICE elements (Genbank Accession number AJ617740). The parental clc element contains genes for chlorocatechol (clc) degradation. However, these genes were lost from both RGP5 and RGP29 of PA34. Nevertheless, genes required for integration and conjugation were identified in both of the ICEs in RGP5 and RGP29 (Fig 3A) indicating that these elements may have the capacity to transfer within and between species. This may be the reason for observing clc-like GIs in two different loci in this strain. In addition, RGP5 carried mercury resistance genes, which are not present in the parental clc elements. This finding suggests that the clc-like elements may incorporate antibiotic resistance genes during genetic recombination. The third ICE observed in RGP41 of PA34 was related to the pKLC102 family (GenBank Accession number AY257538) and was similar to P. aeruginosa pathogenicity island PAPI-1 (GenBank Accession number AY273869) first identified in P. aeruginosa clone C (Fig 3B). PAPI-1 is self-transmissible and carries virulence factors such as genes for type IV pilus biogenesis and the cupD gene clusters The cupD genes are essential for the formation of cell surface fimbriae that are involved in biofilm formation. Interestingly, the cupD gene cluster appears to have been lost from the RGP41 of PA34, although the genes for type IV pilus biogenesis are still present. In addition, various members of pKCL102 ICE family are found to be associated with the carriage of exoU/spcU genes. These GIs have frequently been referred as exoU islands such as exoU island A, exoU island B, exoU island C and PAPI-2. Possession of the exoU gene, that encodes the type III secretion system effector cytotoxin ExoU, markedly enhances the virulence of P. aeruginosa. An exoU-island of 7.5 Kbp carrying five open reading frames was observed in PA34 (RGP7). In contrast to other exoU-islands that contain genes associated with integration, transposition, conjugations and sometimes antibiotic resistance, the exoU island observed here contains only three genes that have homology to a site-specific integrase (Fig 4A). The presence of both PAPI-1 and PAPI-2 like elements that act synergistically in virulence may indicate an enhanced virulence of PA34. To determine whether the exoU gene was functional, cytotoxicity of PA34 was examined in a human corneal epithelium cell line and compared with P. aeruginosa PAO1 which is a noncytotoxic invasive strain. Microscopic examination after staining with trypan blue indicated that PA34 was highly cytotoxic (Fig 5) showing a large number of dead cells. Based on Accessory genome of ocular P. aeruginosa the percentage of dead cells, maximum cytotoxicity (of score 4) was observed in PA34. Previous studies have shown that possession of exoU is associated with in vitro and in vivo cytotoxicty, for example by using knockout mutants of P. aeruginosa strains such as PA103 and PAO1. The results in the current study suggest that exoU in RGP7 of PA34 was transcribed and translated into a functional protein that retained cytotoxicity. The finding also demonstrates that the size of the exoU island was not be associated with activity. However, direct confirmation of this result by producing exoU knockout of P. aeruginosa PA34 is required to confirm this result. A mercury resistance operon was also observed in the MKPA34-GI1 RGP that also carried chromate resistance genes and features related to transposition and conjugation. A BLASTn search against the plasmid database in NCBI did not show significant sequence similarity with MKPA34-GI1. However, 51% of the MKPA34-GI1 sequence was loosely identical (205 matches with an average identity of 97%) to a the complete genome of Pseudomonas stutzeri strain 273 (GenBank accession number CP015641.1). Pseudomonas stutzeri is an environmental organism and has the capacity to degrade pollutants such as toxic metals. These observations indicate that the MKPA34-GI1 may have been acquired by horizontal transfer from organisms in mercury polluted environments. The ability of MKPA34-GI1 to transfer between strains needs to be confirmed by further experiments that will also help to confirm the MKPA34-GI1 RGP loci is mobile. In order to compare the phenotypic susceptibility to heavy metals, MIC to Hg ++, Cu ++ and Co ++ were examined. High mercury tolerance was observed in PA34 (p<0.05) in comparison to PAO1 (Fig 6), possibly due to the presence of mercury resistance operon in two different GIs (RGP5 and MKPA34-GI1) in PA34. Copper tolerance was slightly higher in PA34 than PAO1 (p>0.05). Although bacteria require copper as a cofactor for many metabolic processes and can tolerate low concentration of Cu ++, decreasing sensitivity to copper can be associated with acquisition of copper resistance genes. The presence of a copper resistance operon in RGP23 in PA34 may be associated with higher MIC to Cu ++. On the other hand, cobalt tolerance, for which no acquired genes were observed in this study was low in both PA34 and PAO1 (p<0.05). P. aeruginosa can tolerate Cu ++ and other heavy metals including Co ++ mainly due to P-type ATPase transporter and resistance nodulation cell division efflux pump. In PAO1, the P-type ATPase encoded by PA3920 was found to be important for copper tolerance. In addition, bacterial plasmids also carry metal resistance determinants. However, plasmid associated metal resistance determinates were not detected in PA34. The Pseudomonas phage MP38 was identified in the MKPA34-GI2 (flanking loci homologous to 4856/4857 of PAO1) (Fig 4B). MP38 is D3112-like phage which is a transposable and has been isolated from many clinical isolates of P. aeruginosa. We examined the presence of MP38 in genomes of different P. aeruginosa and found that a similar phage was integrated into VRFPA04 near the PA4204 homologue of PAO1. This confirms the result of another study that has shown that transposable phages may have variable integration sites, indicating that the phage MP38 does not have any specific integration site in the genome of P. aeruginosa. Therefore, the MKPA34-GI2 integration site may not be a constant RGP for P. aeruginosa. Four RGPs (RGP31, RGP73, RGP9 and RGP60) of PA34 were associated with replacement of pathogenic genes and were related to lipo-polysaccharide O-antigen, pyoverdine (pvdE), flagella (fliC) and pilus (pilA) synthesis. Despite the replacement islands contains the same genes and being integrated into the same loci in the core genome, they highly diverse between strains. These components are important for interaction of a bacterium with external environments including other species or hosts and hence are under continuous selection pressure. The pvdE and fliC orthologs have been shown to vary greatly between different strains of P. aeruginosa. The replacement islands may contribute to higher virulence in PA34 although this needs to be tested for swimming or twitching motility and for expression of pvdE under low iron condition. The largest GI (RGP23) observed in PA34 was 125.1 Kbp and carried resistance genes for aminoglycosides (AAC-IId) and tunicamycin. An insertion sequence of the family IS1182 was observed in this GI, which may be responsible for carriage of these resistance genes. A BLASTn search revealed that the antibiotic resistance genes were best matched with those of Acinetobacter sp. WCHA45 plasmid pNDM1_010045 (GenBank accession number NZ_CP028560.1) and were similar to many from other members of the Enterobacteriaceae where IS1182 is also present. In addition, a phage tail protein gp37, which was first identified in Enterobacter phage T4 was found inserted into this island. This suggests that this resistance island may be derived from phages. Plasmid features The Illumina and ONT reads of the whole genome sequence of PA34 were assembled into seven contigs (> 500 bp) using hybrid strategies in SPAdes. Out of seven contigs, contigs 6 and 7 had a G+C content that less than that of other contigs and showed a significant match with plasmids in the NCBI database. This suggests that contigs 6 and 7 are likely to represent two different plasmids carried by PA34 and were named here as pMKPA34-1 and pMKPA34-2. pMKPA34-1 is 95.4 kbp with 57% G+C content and pMKPA34-2 is 26.8 kbp with 61% G+C content. Automatic annotation followed by manual confirmation with BLASTn revealed 98 CDS in pMKPA34-1 and 33 CDS in pMKPA34-2. Out of 98 predicted genes in pMKPA34-1, 46 were predicted to encode proteins with unknown functions whilst all 33 CDS in pMKPA34-2 were predicted to encode known proteins. General features of pMKPA34-1. The putative plasmid pMKPA34-1 contains a replication gene (repE), a chromosome partition gene (smc), a plasmid stabilization gene (parB) and a plasmid conjugal transfer mating pair stabilization protein (traN). These genes may help replication, maintenance and transfer of the plasmid (Fig 7). Based on BLASTn searches against the NCBI plasmid database, pMKPA34-1 had the best match (31% query cover with 94% identity) with plasmid pLIB119 of P. stutzeri strain 19SMN4 (GenBank accession number CP007510), followed by Citrobacter freundii strain 18-1 plasmid pBKPC18-1 (23% query cover with 99% identity) (Fig 7). The parA, smc and repE genes display high similarity to the corresponding genes of pLIB119. The presence of the traN gene, which encodes an outer membrane protein and is essential for F-mediated bacterial conjugation, indicates the potential exchangeability of pMKPA34-1. This transfer system is common amongst bacterial plasmids notably in Enterobacteriaceae and its presence in pMKPA34-1 may indicate that the plasmid could be exchanged with members of the Enterobacteriaceae. Transposase, integrase and recombinase genes formed a major portion of the mobile genetic elements in pMKPA34-1. ISsage analysis identified two putative prophage integrases, and site-specific recombinases (xerC and xerD) of the tyrosine family. The XerC-XerD system, which is found on both the chromosome and on plasmids helps separation and segregation of newly replicated bacterial dimeric chromosome by resolving it to monomers. This system is essential in the segregation of multicopy plasmids and contributes to the stable inheritance of multicopy plasmids. General features of pMKPA34-2. The plasmid pMKPA34-2 lacks identifiable replication genes. However, the genome coverage statistics (109x vs. 50x) ( Table 1) suggests it may have a higher copy number than the pMKPA34-1. pMKPA34-2 may use alternative mechanisms for replication. In the BLASTn search against the NCBI plasmid database, pMKPA34-2 was best matched (29% query cover with 88% identity) with plasmid pSSE-ATCC-43845 of Salmonella enterica subsp. enterica serovar Senftenberg strain 775WP (GenBank accession number CP016838), followed by plasmid tig00000727 of Klebsiella pneumoniae strain AR_0158 (Gen-Bank accession number CP021699) (14% query cover with 99% identity) (Fig 8). Moreover, pMKPA34-2 carried the series of genes (tnsA, tnsB, tnsC, tnsD and tnsE) that are associated with transposition and are related to Tn7 transposons, a phage integrase and a putative resolvase. Upstream of these mobile genetic elements, a multi drug export protein gene (mepA) was identified. MepA is multi drug efflux transporter of MATE (Multidrug And Toxic Compound Extrusion) family whose role in P. aeruginosa is not well understood.. However, MepA has been associated with resistance to many antibiotics and microbicidal dyes (crystal violet and ethidium bromide) in Staphylococcus aureus. Indeed, the presence of the mepA gene in this plasmid and its association with mobile genetic elements suggest that this gene may have been acquired through horizontal gene transfer. Conclusions The large accessory genome of P. aeruginosa strain PA34 indicates that this strain has a diverse genomic structure. The strain harbours twenty-four genomic islands and two plasmids that carry various metal and antibiotic resistance genes as well as several genes associated with virulence. This may be associated with the observance of higher antibiotic resistance, mercury tolerance and in-vitro cytotoxicity of PA34. The in-silico analysis showed that six antibiotic resistance genes were present in two different plasmids and one antibiotic resistance gene plus various mercury resistance genes were integrated into different GIs and these resistance genes have sequence similarities with that of either other environmental or enteric bacteria. Furthermore, the genome of the PA34 has been integrated by phage element (gp37) that has its origin in enteric bacteria and carried aminoglycoside resistance gene (AAC-IId). These findings suggest that resistance and virulence in PA34 may have evolved due to environmental selection pressure where organisms acquire traits to survive predation by other inhabitants. Thus acquired traits enhance the pathogenesis process in human. Given the eye is susceptible to being infected by environmental strains of P. aeruginosa, examination of a larger number of eye isolates may be necessary to uncover any additional acquired genetic features associated with microbial keratitis. This will help our understanding of different aspects of Pseudomonas keratitis. Supporting information S1 |
/* Function: p7_hmmwindow_init()
*
* Synopsis: initialize the object used to store a list of sequence windows
*
* Returns: eslEMEM in event of allocation failure, otherwise eslOK
*/
int
p7_hmmwindow_init (P7_HMM_WINDOWLIST *list) {
int status;
list->size = 10000;
list->count = 0;
ESL_ALLOC(list->windows, list->size * sizeof(P7_HMM_WINDOW));
return eslOK;
ERROR:
return eslEMEM;
} |
<filename>Unix/http/httpcommon.h
/*
**==============================================================================
**
** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE
** for license information.
**
**==============================================================================
*/
#ifndef _omi_http_httpcommon_h
#define _omi_http_httpcommon_h
#include <stddef.h>
#include "config.h"
#include <common.h>
#include <base/batch.h>
#include <base/interaction.h>
#include <sock/selector.h>
#include <base/paths.h>
#ifdef CONFIG_POSIX
# include <openssl/ssl.h>
# include <openssl/err.h>
#endif
#define ENGINE_TYPE 'E'
BEGIN_EXTERNC
/* NTLM error codes */
enum ntlm_err_code {
ERR_BASE = 0x4E540000, /* base error space at 'NT00' */
ERR_DECODE,
ERR_ENCODE,
ERR_CRYPTO,
ERR_NOARG,
ERR_BADARG,
ERR_NONAME,
ERR_NOSRVNAME,
ERR_NOUSRNAME,
ERR_BADLMLVL,
ERR_IMPOSSIBLE,
ERR_BADCTX,
ERR_WRONGCTX,
ERR_WRONGMSG,
ERR_REQNEGFLAG,
ERR_FAILNEGFLAGS,
ERR_BADNEGFLAGS,
ERR_NOSRVCRED,
ERR_NOUSRCRED,
ERR_BADCRED,
ERR_NOTOKEN,
ERR_NOTSUPPORTED,
ERR_NOTAVAIL,
ERR_NAMETOOLONG,
ERR_NOBINDINGS,
ERR_TIMESKEW,
ERR_EXPIRED,
ERR_KEYLEN,
ERR_NONTLMV1,
ERR_NOUSRFOUND,
ERR_LAST
};
/* HTTP Error codes */
#define HTTP_ERROR_CODE_OK 200
#define HTTP_ERROR_CODE_BAD_REQUEST 400
#define HTTP_ERROR_CODE_UNAUTHORIZED 401
#define HTTP_ERROR_CODE_INTERNAL_SERVER_ERROR 500
#define HTTP_ERROR_CODE_NOT_SUPPORTED 501
/*
**==============================================================================
**
** Authentication progress state, digested auth type
**
**==============================================================================
*/
typedef enum _AuthMethod {
AUTH_METHOD_UNSUPPORTED = -1,
AUTH_METHOD_NONE = 0,
AUTH_METHOD_BASIC,
AUTH_METHOD_NEGOTIATE,
AUTH_METHOD_NEGOTIATE_WITH_CREDS,
AUTH_METHOD_KERBEROS,
AUTH_METHOD_DIGEST,
AUTH_METHOD_NTLMDOMAIN,
AUTH_METHOD_CLIENTCERTS,
AUTH_METHOD_CREDSSP,
AUTH_METHOD_ISSUER_CERTS,
AUTH_METHOD_BYPASS
} AuthMethod;
typedef enum _AuthMechanism {
AUTH_MECH_UNSUPPORTED = -1,
AUTH_MECH_NONE = 0,
AUTH_MECH_KERBEROS,
AUTH_MECH_NTLMSSP
} AuthMechanism;
/*
**==============================================================================
**
** Define supported Authentication and other related fields.
**
**==============================================================================
*/
#define AUTHENTICATION_NEGOTIATE "Negotiate" /* Used for kerberos or ntlm authentication */
#define AUTHENTICATION_NEGOTIATE_LENGTH 9
#define AUTHENTICATION_KERBEROS "Kerberos" /* Used for kerberos only authentication, no fallback */
#define AUTHENTICATION_KERBEROS_LENGTH 8
#define AUTHENTICATION_BASIC "Basic"
#define AUTHENTICATION_BASIC_LENGTH 5 /*This is the length of "Basic"*/
#define HTTP_WWWAUTHENTICATE_BASIC "WWW-Authenticate: Basic realm=\"WSMAN\""
#define HTTP_WWWAUTHENTICATE_NEGOTIATE "WWW-Authenticate: Negotiate realm=\"WSMAN\""
#define HTTP_WWWAUTHENTICATE_KERBEROS "WWW-Authenticate: Kerberos realm=\"WSMAN\""
/* ************************************************ */
/* Datatypes */
/* ************************************************ */
typedef struct _Http Http;
/* HTTP options.
mostly used for unit-testing; default values
are hard-coded but can be overwritten by
unit-tests/config modules */
typedef struct _HttpOptions
{
/* timeout for network delays and keep-alive;
note: http does not have timeout for server/provider processing */
MI_Uint64 timeoutUsec;
/* Enable tracing of HTTP input and output */
MI_Boolean enableTracing;
}
HttpOptions;
/* SSL_Options.
Allows SSL or TLS to be individually disabled, or to disable
both protocols, based on omiserver.conf and omicli.conf */
typedef enum _SSL_Options
{
// Must be bits so these can be specified individually or together
DISABLE_SSL_V2 = 0x01,
DISABLE_SSL_V3 = 0x02,
DISABLE_TLS_V1_0 = 0x04,
DISABLE_TLS_V1_1 = 0x08,
DISABLE_TLS_V1_2 = 0x10,
DISABLE_SSL_COMPRESSION = 0x20
}
SSL_Options;
//------------------------------------------------------------------------------------------------------------------
/* 60 sec timeout */
#define DEFAULT_HTTP_OPTIONS { (60 * 1000000), MI_FALSE }
MI_Result Http_New_Server(
_Out_ Http** selfOut,
_In_ Selector* selector, /*optional, maybe NULL*/
_In_ unsigned short http_port, /* 0 to disable */
_In_ unsigned short https_port, /* 0 to disable */
_In_opt_z_ const char* sslCipherSuite, /* NULL to disable */
_In_ SSL_Options sslOptions, /* 0 for default options */
_In_ OpenCallback callbackOnNewConnection,
_In_opt_ void* callbackData,
_In_opt_ const HttpOptions* options ); /* Sets http options (mostly unit-test support) */
MI_Result Http_Delete(
Http* self);
MI_Result Http_Run(
Http* self,
MI_Uint64 timeoutUsec);
//------------------------------------------------------------------------------------------------------------------
// Auxiliary methods
MI_Boolean ParseAuthorization(
_Inout_ HttpHeaders* recvHeaders,
_In_ CharPtr value );
void ParseContentType(
_Inout_ HttpHeaders* recvHeaders,
_In_ CharPtr value );
#ifdef CONFIG_POSIX
MI_Result CreateSSLContext(SSL_CTX **sslContext, SSL_Options sslOptions);
char* GetSslErrorString(
_Out_ char* buf,
_In_ size_t bufLen);
#endif
void _WriteTraceFile(PathID id, const void* data, size_t size);
END_EXTERNC
#endif /* _omi_http_httpcommon_h */
|
Theological College of Northern Nigeria (TCNN) Research Bulletin Theological College of Northern Nigeria (TCNN) Research Bulletin Dr Gunther J. Hermann, Chairman of the Editorial Board, writes: For almost two years now TCNN has been publishing a research magazine called TCNN Research Bulletin. Up to now five issues (each of about forty pages) have been published (two-three issues per year). The aim of the Bulletin is to encourage research in Northern Nigeria related to questions of African traditional religion, Islam, Nigerian church history, mission and colonialism, modernization and problems of a social, ethical, political or philosophical nature. The first editorial principle is that all articles must have a clear relevance to the African or especially Nigerian context. Only present and former students of TCNN, as well as present and former staff members of the college, are eligible to contribute to the Bulletin. The second editorial principle is to avoid theological jargon. The Bulletin does not aim at being a forum for international scholars, but it is intended to be read and understood by a wider public. Although the Bulletin is not primarily intended for a readership outside West Africa, it has a role in supplementing existing research at the international, academic level by serving as an outlet for the original, local research done by students and graduates of TCNN. Recent issues have included papers on: |
Antitrust and Competition in Health Care Markets In this paper we review issues relating to antitrust and competition in health care markets. The paper begins with a brief review of antitrust legislation. We then discuss whether and how health care is different from other industries in ways that might affect the optimality of competition. The paper then focuses on the main areas in which antitrust has been applied to health care: hospital mergers, monopsony, and foreclosure. In each of these sections we review the relevant antitrust cases, discuss the issues that have arisen in those cases, and then review the relevant economics literature and suggest some new methods for analyzing these issues. |
Alternative Liquid Fuel from Catalytic Cracking of Candlenut Oil Biodiesel (Aleurites Moluccana) and PP/PS Plastic Waste In this research, synthesis and characterization of alternative liquid fuel obtained from candlenut oil biodiesel (Aleurites moluccana) and polypropylene (PP) combined with polystyrene (PS) plastic waste were carried out. This research aims to obtain biodiesel that is more environmentally friendly when compared to conventional diesel fuel today. The synthesis and characterization process was performed through catalytic cracking using a combination of Al-MCM-41 catalyst and ceramics, with a ratio of 7:3, respectively. This catalytic cracking method has been known to produce biodiesel because it can break long-chain carbon bonds to be shorter and simpler. The morphology and acidity of the catalysts were analyzed using XRD and FTIR-Pyridine techniques. The fuel liquid obtained from synthesis was analyzed using Gas Chromatography-Mass Spectroscopy (GC-MS) to obtain its constituent hydrocarbon components fraction. The highest yield was obtained at a feedstock of PS:COB (candlenut oil biodiesel) variation of 68.2%, with hydrocarbon fraction composition C7, C7C12, > C12 each respectively of 14.66%, 85.32%, and 13.05%. The viscosity and the calorific value of the liquid fuel were initially known. In this research, the effects of using other plastic waste towards the yield percentage and the characteristics of the synthesized fuel were also investigated. The results from the analysis show that the properties of the synthesized liquid fuel mixture variations being researched have met the Indonesian National Standard SNI 06-3506-1994, which refers to the quality standards of gasoline-type liquid fuel. |
Vegetables are packed with the vitamins and minerals your body needs to stay strong. Most of them also are low in calories, meaning they can sustain your appetite and boost your energy levels — all without the worry of adding extra weight.
Busy schedules mean limited free time for preparation and cooking. The great thing about vegetables is that many of them can be consumed raw for a delicious treat.
Even if you only have 30 minutes or less to cook each night, that is ample time for boiling a shallow pan of water and adding vegetables to a steam tray. You'll have beautifully steamed vegetables before you pay the bills or help your child finish her homework.
Also, by choosing to steam your vegetables, you retain more of their important nutrients than would have been kept through boiling.
If time isn't an issue, why not invest some money and work into building your own garden? It will require an initial investment, but you'll be rewarded with bright, vibrant vegetables that you can bring in from the garden to your plate in a matter of minutes.
A garden lets you decide the types of vegetables your family will eat. Depending on how much you decide to plant, you may not need another trip to the produce aisle of your grocery store until the cold weather months.
Salad doesn't have to be made up of lettuce, cheese and dressing. Get creative. Think of your salad as an art project, and choose the most colorful options possible.
The more color you add to your salad, the better it is for you. Start by slicing up a red or yellow pepper. Keep the red coming with some colorful cabbage, radishes or cherry tomatoes. Before you know it, you'll be digging into your rainbow of a salad, all while knowing that you're also enhancing your overall health and wellness. |
June 18, 2018 at 7:28p.m.
The Youngstown/Warren Regional Chamber, in partnership with several other chambers of commerce, is working to compile a list of companies willing to hire workers impacted by layoffs at the General Motors Lordstown Assembly Complex, Magna Seating and Comprehensive Logistics. The chamber’s partners include the Greater Cleveland Partnership, Greater Akron Chamber, and the Shenango and Lawrence county chambers.
The Youngstown/Warren Regional Chamber, in partnership with several other chambers of commerce, is working to compile a list of companies willing to hire workers impacted by layoffs at the General Motors Lordstown Assembly Complex, Magna Seating and Comprehensive Logistics.
The list will be distributed to workers who may be looking for employment opportunities.
The chamber’s partners include the Greater Cleveland Partnership, Greater Akron Chamber, and the Shenango and Lawrence county chambers.
“To take a multi-regional approach to any of the challenges in our business community means that there is a higher rate of success for the problems to actually get solved,” said Sherris Moreira, executive director of the Shenango Valley Chamber of Commerce.
The plant will go down to one shift beginning June 25.
February 7, 2019 8:26 a.m.
February 8, 2019 12:02 a.m.
April 15, 2018 12:01 a.m. |
<filename>DeepFilterNet/df/logger.py
import os
import sys
from typing import Dict, Optional
import torch
from loguru import logger
from torch.types import Number
from df.utils import get_branch_name, get_commit_hash, get_device, get_host
_logger_initialized = False
def init_logger(file: Optional[str] = None, level: str = "INFO"):
global _logger_initialized
if _logger_initialized:
logger.debug("Logger already initialized.")
return
logger.remove()
level = level.upper()
if level != "NONE":
log_format = get_log_format(debug=level == "DEBUG")
logger.add(sys.stdout, level=level, format=log_format)
if file is not None:
logger.add(file, level=level, format=log_format)
logger.info(f"Running on torch {torch.__version__}")
logger.info(f"Running on host {get_host()}")
commit = get_commit_hash()
if commit is not None:
logger.info(f"Git commit: {commit}, branch: {get_branch_name()}")
if (jobid := os.getenv("SLURM_JOB_ID")) is not None:
logger.info(f"Slurm jobid: {jobid}")
_logger_initialized = True
def get_log_format(debug=False):
if debug:
return (
"<green>{time:YYYY-MM-DD HH:mm:ss}</green>"
" | <level>{level: <8}</level>"
" | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan>"
" | <level>{message}</level>"
)
else:
return (
"<green>{time:YYYY-MM-DD HH:mm:ss}</green>"
" | <level>{level: <8}</level>"
" | <cyan>DF</cyan>"
" | <level>{message}</level>"
)
def log_metrics(prefix: str, metrics: Dict[str, Number]):
msg = prefix
for n, v in sorted(metrics.items()):
msg += f" | {n}: {v:.5g}"
logger.info(msg)
def log_model_summary(model: torch.nn.Module, verbose=False):
import ptflops
from df.model import ModelParams
# Generate input of 1 second audio
# Necessary inputs are:
# spec: [B, 1, T, F, 2], F: freq bin
# feat_erb: [B, 1, T, E], E: ERB bands
# feat_spec: [B, 2, T, C*2], C: Complex features
p = ModelParams()
b = 1
t = p.sr // p.hop_size
device = get_device()
spec = torch.randn([b, 1, t, p.fft_size // 2 + 1, 2]).to(device)
feat_erb = torch.randn([b, 1, t, p.nb_erb]).to(device)
feat_spec = torch.randn([b, 1, t, p.nb_df, 2]).to(device)
macs, params = ptflops.get_model_complexity_info(
model,
(t,),
input_constructor=lambda _: {"spec": spec, "feat_erb": feat_erb, "feat_spec": feat_spec},
as_strings=False,
print_per_layer_stat=verbose,
verbose=verbose,
)
logger.info(f"Model complexity: {params/1e6:.3f}M #Params, {macs/1e6:.1f}M MACS")
|
// prints a indexinfo to the provided output
void
CMDIndexInfo::DebugPrint
(
IOstream &os
)
const
{
os << "Index id: ";
Pmdid()->OsPrint(os);
os << std::endl;
os << "Is partial index: " << m_fPartial << std::endl;
} |
package com.allmycoins.balance.cosmosjs;
import java.math.BigDecimal;
public final class CosmosJsBalanceJson {
private String denom;
private BigDecimal amount;
public BigDecimal getAmount() {
return amount;
}
public String getDenom() {
return denom;
}
}
|
. We administered local botulinum toxin injections on the leg adductors of 12 patients with spastic paraparesis (9 patients with HAM, 2 patients with spinal spastic paraparesis, 1 patient with an identified degenerative disease). Two of them were wheelchair-bound and the other patients could walk with or without help. The patients were assessed by the time to walk 10 m and the spasticity score which was derived from the degree of muscle tone and spasm frequency of leg adductors. After the initial injection, 7 of the 12 patients improved spasticity scores and 8 of the 10 patients could walk 10 m within a shorter time. The time to walk 10 m was markedly shortened in moderate cases. However, one patient complained of leg weakness and the time to walk 10 m was prolonged. Five of the 12 patients received injections 3 to 7 times, and were followed up for a mean of 16.2 months. In 4 of the 5 patients, repeated injections could maintain the improvement of spasticity score and time to walk 10 m. However, injection was discontinued in one patient because of leg weakness. The other side effects were pain and swelling at the injected site and dysarthria. However, these side effects were slight and transient and did not require treatment. No other systemic side effects were observed. In conclusion, the beneficial effects of botulinum injections to spastic paraparesis were improvement of objective symptoms in mild cases, improvement of ADL in moderate cases, and improvement of objective symptoms and ease of nursing care in severe cases. Furthermore, we confirmed the long-term efficacy and safety of botulinum toxin. |
The Algorithm of Terminal Logistics Path Planning Based on TSP Problem In order to improve the efficiency of logistics express delivery, and address the delivery and pick up problems in the process of logistics, this paper introduces the TSP problem algorithm into the research of terminal logistics path planning for the first time. The TSP problem model and the TSP problem model are established according to the different characteristics of delivery and pick-up process. The dynamic programming equations of delivery and pick-up process are obtained by using dynamic programming algorithm and they provide theoretical basis for the next step of intelligent delivery and pick-up. |
A HOMELESS man has said he was told by housing advisors to quit his job in order to get a place at a hostel.
Anthony Rimmington, 25, has been sleeping on floors of the homes of friends and family since losing the flat in Morley he shared with his ex girlfriend.
The UK Mail warehouse sorter said he was not able to pay the rent on his own after the couple split up, and was unable to pay for another privately rented flat.
Mr Rimmington, who said he had been on the priority housing list since last year, said: “I knew I was going to become homeless so have been going to the housing office at Morley One Stop.
“They suggested a hostel, private rent or shared occupancy, asked me some questions about my work, hours and wage and then said I should quit my job so they could get me a place in a hostel.
“I think it is disgusting. Without my job I have nothing to look after my kids and there are lots of people out there struggling to get jobs.
Mr Rimmington said he looked after his three-year-old son Leon at the weekends and was worried he might lose that if he couldn’t get a place of his own.
A spokeswoman for Leeds City Council said: “It is certainly not correct that Mr Rimmington should give up his job in order to get a place in a hostel. We are very sorry if he was advised this.
“Mr Rimmington does have a ‘homeless’ priority status but there are many people who have a higher priority status because of their additional needs and vulnerability, such as disability or health issues, or those who have dependent children.
“We understand and sympathise with Mr Rimmington’s situation, however he is doing the right thing in bidding for lots of suitable properties, to maximise his chances of finding somewhere soon. |
Correlative chemical and structural nanocharacterization of a pseudo-binary 0.75Bi(Fe0.97Ti0.03)O3-0.25BaTiO3 ceramic Fast-cooling after sintering or annealing of BiFeO3-BaTiO3 mixed oxide ceramics yields core-shell structures that give excellent functional properties, but their precise phase assemblage and nanostructure remains an open question. By comparing conventional electron energy loss spectroscopy (EELS) with scanning precession electron diffraction (SPED) mapping using a direct electron detector, we correlate chemical composition with the presence or absence of octahedral tilting and with changes in lattice parameters. This reveals that some grains have a 3-phase assemblage of a BaTiO3-rich pseudocubic shell; a BiFeO3-rich outer core with octahedral tilting consistent with an R3c structure; and an inner core richer in Ba and even poorer in Ti, which seems to show a pseudocubic structure of slightly smaller lattice parameter than the shell region. This last structure has not been previously identified in these materials, but the composition and structure fit with previous studies. These inner cores are likely to be non-polar and play no part in the ferroelectric properties. Nevertheless, the combination of EELS and SPED clearly provides a novel way to examine heterogeneous microstructures with high spatial resolution, thus revealing the presence of phases that may be too subtle to detect with more conventional techniques. Introduction Mixed oxide electroceramics are of great interest due to their unique functional properties and therefore, the abundance of technological applications such as piezoelectric sensors, transducers and actuators. It is well known that tuning material properties, such as stoichiometry, elemental composition or epitaxial strain, can enhance piezoelectric properties. In particular, these properties are greatly enhanced around the morphotropic phase boundary -a region in the phase diagram in which two structurally competing phases coexist within a narrow range of stoichiometry. Currently, the most commercially used piezoceramic is the inorganic compound Pb(ZrxTi1-x)O3 (0<x<1) (PZT), due to its excellent functional properties. One drawback to this compound, however, is its environmental toxicity due to its lead content. The threat of incoming EU regulations regarding the use of lead has created a surge of research dedicated to finding a suitable, lead-free replacement material with equivalent or superior properties. One candidate is the pseudo-binary solid solution, BiFeO3-BaTiO3 (BF-BT). BiFeO3 itself is a promising candidate for many devices, due to its high remanent polarisation and high Curie temperature. However, its formation generally yields impurity phases and the high coercive field and high leakage current results in unsaturated hysteresis loops being reported. Many attempts have been made to improve the properties of BiFeO3 based ceramics by doping or using different synthesis methods, although this can result in unexpected defect formation. However, addition of BaTiO3 into the solid solution has been reported to stabilise the BiFeO3 perovskite structure and improve the electrical properties. The BF-BT solid solution exists in a rhombohedral phase for BiFeO3 contents ⪆0.70. Below this threshold, the material adopts a cubic structure, before transforming to a tetragonal phase for BiFeO3 content ⪅0.1. The use of certain types of dopants in BF-BT has been shown to cause chemical segregation resulting in core-shell microstructures, a process attributed to an electronegativity difference of the dopant species driving immiscibility during cooling from the sintering temperature. Initially seen as undesirable due to the reduction in the strength of functional properties, Murakami et al., showed that quenching after sintering or annealing could eliminate chemical heterogeneity and was accompanied by increased electrostrain and polarisation, suggesting that quenching provided potential for improved functional properties. More intriguingly, it has been shown that donor dopants promote chemical heterogeneity, while isovalent dopants promote solubility. Therefore, the consensus derived from a large number of studies on BF-BT, is that the structure and properties are highly sensitive to the doping species, doping quantity and heat treatment, suggesting that there may be more than one route to tune the desired functionality of these ceramics. In a further publication, Calisir et al. propose a new avenue of exploration of piezoelectric properties, in which they exploit deliberate chemical segregation and the creation of a core-shell microstructure. By creating both chemically and structurally inhomogeneous ceramics, they report enhanced dielectric energy storage density with slow-cooling and improved piezoelectric properties with fast-cooling in core-shell structured BiFeO3-BaTiO3. In disagreement with the findings of Murakami et al. that quenching reduces heterogeneity, it was found that the core-shell microstructure was maintained with quenching accompanied by a dramatic enhancement of the ferroelectric and piezoelectric properties with respect to furnace cooled samples. With a new vision to create chemically and structurally inhomogeneous materials in order to generate enhanced piezoelectric properties, it is necessary to have methods to characterise this inhomogeneity at the requisite length scale (tens of nanometres or less). Distinguishing these details using X-ray diffraction or scanning electron microscopy (SEM) techniques such as X-ray mapping or electron backscatter diffraction (EBSD) is not realistic due to the lack of spatial resolution and the relatively subtle differences between the phases involved. To make progress in correlating structure and chemistry, here we study thin sections using a combination of the high spatial resolution techniques of electron diffraction and EELS in the transmission electron microscope/scanning transmission electron microscope (TEM/STEM). Specifically, the study of nanostructured mixed phases is an ideal application for SPED. First demonstrated in 1994, precession electron diffraction is a technique in which a convergent electron beam is focused on the sample, tilted away from the optic axis, and precessed about the optic axis, whilst the diffraction pattern is recorded. This averages out dynamical diffraction effects and the resulting intensity distributions of the integrated diffraction patterns are considered pseudo-kinematical. More recently, this was turned into a scanning technique in which the beam is simultaneously precessed and rastered over the sample, thus making it one variant of a scanned diffraction or 4-dimensional STEM (4D STEM) technique with resolutions down to a few nanometres, making it perfect for mapping core-shell structures. It is well-known that octahedral tilting of perovskites causes the appearance of extra reflections in electron diffraction patterns which reveal the nature of the tilting pattern. Previously, Bi(Fe1-xTix)O3-BaTiO3 was found to be a mixture of a rhombohedral R3c perovskite (BiFeO3-like) containing substantial antiphase octahedral tilting and a primitive pseudocubic perovskite (maybe similar to BaTiO3) with untilted oxygen octahedra. Given that the similarity of BaTiO3 and BiFeO3 structures (~1% distortion from cubic perovskite) would make most equivalent zone axes diffraction patterns indistinguishable, the presence of superlattice reflections at the {ooo} positions (where o stands for an odd number) arising from antiphase octahedral tilting, was utilised to spatially map the crystal structure. The lowest index zone axes in which these reflections appear are the <110> and <112> zone axes of the primitive perovskite cell. Woodward and Reaney analysed the appearance of superlattice reflections in <110>primitive zone axes for perovskites with different tilting systems and showed that these only appear in 6 of the 12 possible <110>primitive directions for aaastructures like BiFeO3. Thus, using the presence or absence of such reflections in a <110>primitive direction is not reliable, as their absence could also indicate a domain with a different crystallographic orientation. In contrast, all 24 distinct <112>primitive directions contain allowed {ooo} reflections (a detailed analysis using calculated diffraction patterns is included in the Supplemental Materials Figure S1 and Table S1), making these the optimal zone axes for diffraction experiments to distinguish octahedrally-tilted and untilted perovskites. Once acquired, SPED data can be visualised using a Virtual Dark Field (VDF) approach, where an image is generated using the intensity in a single diffraction spot or multiple diffraction spots from the same phase, allowing the separation of different crystals, phases or domain orientations in a crystal. Additionally, mapping the spot positions allows the determination of strain. The first of these, however, would be difficult for weak antiphase tilting spots using the conventional SPED detector (a fast CCD camera), as the weak spots would be lost in the relatively high background noise level. In a recent advance, an electron counting pixelated detector (Merlin for EM with Medipix 3 chip) was integrated with a SPED system. This allows SPED data collection at a suitable signal to noise ratio to extract the intensity of the superlattice spots. This paper describes a study of air-quenched Bi(Fe0.97Ti0.03)O3-BaTiO3 ceramics in a TEM/STEM system using EELS chemical mapping coupled with analysis of weak superlattice spots in SPED patterns that reveal octahedral tilting. This reveals the core-shell structure in unprecedented detail, and even leads to the discovery of an additional unexpected phase in the ceramic. Experimental Procedure Samples were synthesised by the solid state reaction method based on the chemical formula of 0.75(3% Ti-doped BiFeO3)−0.25BaTiO3. More details are given by Calisir et al.. Samples for TEM/STEM analysis were prepared by a focused ion beam (FIB) liftout process using a Helios xenon plasma FIB (Thermo Fisher Inc., Hillsboro, OR). All TEM and STEM data were collected on a JEOL ARM200F (JEOL Ltd., Akishima, Japan) with a cold field emission source using an accelerating voltage of 200 kV. EELS measurements were acquired in STEM mode with a Gatan GIF Quantum ER electron energy loss spectrometer (Gatan Inc., Pleasanton, CA) using a beam convergence angle of 29 mrad and spectrometer collection angle of 36 mrad. The spectra were acquired with an energy dispersion of 0.5 eV/channel over the range of 1024 eV. This encompassed major edges of four of the constituent elements in the composition. Any discernible bismuth edge lay well outside the acquired energy range and therefore bismuth could not be mapped simultaneously, however the acquired high-angle annular dark field (HAADF) image can be taken as a measure of bismuth presence, as contrast scales with atomic number in HAADF imaging and bismuth is the heaviest constituent element. Relating to the EELS mapping, a separate EELS map of the same area was obtained over the range of 1812-3848 eV with a dispersion of 1 eV/channel to map bismuth directly using the M4,5 edge (see Supplementary Information Figure S3). EELS data were processed in Digital Micrograph (Gatan Inc., Pleasanton, CA) by firstly removing any X-rays spikes from the data due to X-ray generation from scattering. The spectra were then aligned using the zero-loss peak to account for movements of the spectrum on the detector during acquisition (either from energy drift or scanning effects). Multivariate statistical analysis was then performed on the data using a specially designed plugin in Digital Micrograph to separate the real signal from random noise. The elemental composition was then quantified using the Elemental Quantification plugin in Digital Micrograph and chemical maps of the constituent elements that lay within the acquired energy range were generated using the Ti and Fe L2,3 edges, the Ba M4,5 edge and the O K edge. The EELS spectra from the different regions were quantified to produce relative contents of Bi, Ba, Ti and Fe. The Ti and Fe contents were taken straight from the standardless quantification using the formula (Bi1-xBax)(Fe1-yTiy)O3 and assuming that the Fe and Ti amounts always sum to 1, and thereby reporting y and 1-y. It was slightly more involved for Ba and Bi as these are in separated spectrum images of the same area. To account for this, spectra from the same integrated areas were created for both scans and the integrated intensity in the edge determined for each of the shell, outer core and inner core regions, was divided by the zero loss intensity to produce: ! = for each element, where I is the intensity in the edge, I0 is the intensity in the zero loss peak, N is the number of atoms per unit area in the path of the beam, and is the interaction cross section. Whilst we do not know the cross-section values (and estimates for M edges are likely to be inaccurate), we can determine an approximate composition in a 2-component system where the two concentrations have to add up to a constant using a simple simultaneous equations approach. This was already found to give a close approximation to results found by determining absolute cross sections from standards for Si-Ge alloys. In this case, the problem is overdetermined as we have three regions to work from, not just two, as in the Si-Ge. Nevertheless, the k-factor relating the cross sections for Bi and Ba can be estimated and then adjusted until the residuals in the analysis are minimised. In our case, with a window width of 400 eV starting at 2600 eV for the Bi-M4,5 edge (to minimise noise) and a window width of 50 eV starting at 781 eV for the Ba-M4,5 edge, the k-factor was found to be about 2.1, i.e.: for the three regions. Therefore, the Ba and Bi fractions could be determined as: SPED data was collected using the JEOL ARM200F noted above with an acceleration voltage of 200kV, a NanoMEGAS Topspin software system (with a prototype system to use the MerlinEM direct electron detector for the diffraction pattern acquisition) and Digistar hardware (NanoMEGAS SPRL, Brussels, Belgium), using a beam precession angle of 0.5 and a 10m condenser aperture to obtain a low convergence angle and well-separated diffraction spots. Comparison diffraction patterns from the same region were also recorded using the standard Stingray camera (NanoMEGAS SPRL, Brussels, Belgium) focused on the small viewing screen. The SPED data was processed to generate structural maps using python scripts derived from the fpd library, which is detailed by Paterson et al.. Functions in the fpd library were used for identifying the central beam spot and then cross correlation and threshold discriminators were used to identify spots with similar characteristics, i.e. diffracted spots. These were then filtered to only include any which had a Friedel counterpart to create a synthetic lattice. This included all primitive lattice spots, excluding any superlattice spots (achieved through intensity threshold discrimination). This synthetic lattice was then used to generate a mask with an array of virtual apertures at the primitive spot positions, from which a VDF image could be generated and normalised to the total counts per real space pixel. The mask was then displaced a certain amount, such that the aperture array then encompassed the superlattice reflections, from which a second VDF image was generated. The strain mapping feature in the TopSpin software was used to map changes in lattice parameters across a grain of interest (based on work by Darbal et al. ). Changes in lattice parameter were mapped in the sample in two orthogonal directions and correlated to changes in octahedral tilting and chemistry. Results The comparison between the two detectors for the same diffraction pattern from the same crystal shows a huge improvement in the diffraction data for the direct electron counting detector, as illustrated in Figure 1. Specifically, the superlattice reflections are now clearly distinguished from the noise, allowing good prospects for mapping their appearance as a function of scan position. This detector was therefore used in the remainder of this work. Figure S3). The O signal seems to be relatively homogeneous through the grains. This is consistent with BaTiO3-rich shells and BiFeO3-rich cores, which has been attributed mainly to the Ti 4+ donor doping in place of Fe 3+ causing differences in electronegativity and hence some degree of immiscibility between BaTiO3 and BiFeO3, inhibiting them from mixing in a solid solution. Another region worth noting is the central core of the lower grain on the right-hand side. In the inner core region, there appears to be a correlation (increased intensity) between the Ba and Fe maps, which both appear to be anticorrelated with the HAADF image and Ti map (decreased intensity), causing an orangecoloured area in the centre of the core of this grain in Figure 2f. There are also orange regions in the grain to the left and the grain above, suggesting that this may be common to many if not all grains (especially as slicing a lamella from the bulk will not always cut directly through the centre of grain). This suggests that the phase formed in these regions is distinct from the surrounding core or shell regions and appears to more barium ferrite rich than other areas. It may also be noted that there are some bright regions at grain boundaries in the HAADF image Table 1 summarises quantification results from the EELS data. The first thing to note is that there are no areas of pure BiFeO3 or BaTiO3; every area is a solid solution. Nevertheless, the shell is around 50-60% BaTiO3, which puts this into the pseudocubic region of the BaTiO3-BiFeO3 phase diagram. In the outer core, the Ba content is very low and these regions are more likely to be in the rhombohedral region of the phase diagram with a structure closer to that of BiFeO3. Finally, there is a region where Ba is at an intermediate composition, but Ti is at its lowest and Fe is relatively high. This is clearly not on the BiFeO3-BaTiO3 tie line, but is maybe heading towards a BaFeO3 composition away from this tie line. It should be noted that whilst the Ba:Bi ratios are plausible for a starting composition of 25%BaTiO3:75%BiFeO3, the Ti contents seem too high as any sensible weighted average would yield something larger than 0.25, and there is probably an error in the calculation of the cross sections used in quantification resulting in a systematic overestimate of Ti content. Nevertheless, even if the absolute magnitude of these proportions could be subject to some significant systematic errors (at least 0.05 and possibly 0.1), the general trends are still clear. Grain area Ba In order to map the local crystal structure of the outer core, shell and inner core phases, SPED was used and exemplar diffraction patterns from the shell and the core are shown in some bright contrast is seen on the grain boundaries and triple points, especially on the right, corresponding to Bi2O3 segregation. There is also a bright particle in the lower right of Figure 4c that appears as black in the EELS map of Figure 4d, this is probably a piece of dust or contamination on the surface of the sample that was not present when the data shown in Figures 4a and 4b were recorded. direction. If one compares Figure 5 with Figure 4, the areas giving strong superlattice contrast tend to have small lattice parameters (green or blue), whereas the shell tends to be mostly larger lattice parameters (reddish or yellow), and the inner core is also yellow or orange suggesting that it is also a larger lattice parameter structure. It is, however, the case that not all parts of the BiFeO3-like region have the same lattice parameters and redder parts are seen where the lattice parameter in one or other direction is around or just over 4. These may be domains where the c-axis lines up along one specific direction. It is notable that two of the redder parts in Figure 5b in the outer core show very blue contrast in Figure 5a, suggesting just such a distortion in the plane of the diffraction pattern where it is most detectable. Discussion It is clear from the data presented that the core-shell structure in the quenched samples is a 3-phase one, not the two-phase structure previously posited. The three phases will be discussed in turn in the forthcoming paragraphs. The shell has a composition where about 60% of B site atoms appear to be Ti. This area is also enriched in Ba, although it does not appear that the A sites are quite as rich in Ba as the B sites are in Ti. This correlates with a reduction in intensity in HAADF images, which should be brightest in Bi rich areas because of the strong atomic-number contrast in HAADF imaging and the fact that Bi is by far the heaviest element in this ceramic. It also correlates with a reduction in the EELS signal to background intensity at the Bi M4,5 edge, even if that had to be recorded separately as it appears in a very different energy range to the other element edges (see Supplementary Information Figure S2). It is therefore evident that this is the area of the grain that is richest in BaTiO3. Moreover, whilst the detailed analysis was performed on one grain, larger area EELS maps show similar trends across many grains in the ceramic. Using precession electron diffraction, this area consistently did not show {ooo} reflections, which are a sign of antiphase tilting -even careful examination of the raw data focusing on those positions found no evidence for these. This either suggests that the structure is an untilted pseudocubic perovskite, as has been suggested in previous reports on the more BaTiO3-rich phases in this system, or a rhombohedral phase with very small tilting such that the intensity in the superlattice spots is undetectably small. Unsurprisingly, these areas are generally those with the largest lattice parameter, as was already expected from previous publications on this system. The outer core was, as expected, rich in BiFeO3, although Ti and Ba are still present at lower concentrations. Nevertheless, the precession electron diffraction clearly demonstrates strong {ooo} reflections throughout this area, giving clear evidence that this area has formed the rhombohedral BiFeO3 structure expected. This area also shows some of the smallest lattice parameters, but with different contractions in different areas, which would agree with the observation of a complex domain structure for this area using conventional TEM (see Figure S4). Supplementary Information It should be noted that the nature of the core-shell structure is crucial in determining the functional properties of the system. For instance, when this material was compared to material that was slow-cooled, the boundary of the outer-core and the shell regions seemed less well defined in the slow-cooled material. On the other hand, when the material is quenched, the clear boundary between the shell and the outer core and distinct chemistry and crystallography of the two as shown in the results above can be expected to lead to long range polarisation ordering in the BiFeO3-rich parts (as evidenced by the extensive domain structure seen in this region (see Supplementary Information Figure S4)). It is also entirely possible that some permanent polarisation can be induced in the BaTiO3-rich shells on the application of an external field, although little domain structure is currently seen in an unpoled material, in much the same way that some other Bi-containing Pb-free materials display significant piezoelectric response despite having less in the way of obvious large scale domains. It is likely that creating a clearer compositional separation that minimises the volume percentage of the ceramic in a non-polar pseudocubic phase and maximises the amount of ferroelectric material of different compositions both towards the BiFeO3 and BaTiO3 ends of the tie line between the two compositions contributes to the improved long-range ordering under an electric field that results in high remanent polarisation (see Supplementary Information Figure S5). Finally, the surprise in this work is the appearance of the inner core, which is richer in Ba but very low in Ti. In fact, there seems to be a straightforward core-shell segregation between Ti and Fe, where Ti tends towards the shells and Fe towards the cores. The complexity comes from the fact that the Ba and Bi do not always follow this Fe-Ti segregation. The composition seems to be heading in the direction of a perovskite phase of something like BaFeO3 (or more likely, BaFeO2.5), but not so far away in composition from the BiFeO3-rich ceramic (containing a little Ti) that is in the outer core. Structurally, however, it is totally distinct from the outer core and consistently has no {ooo} superlattice spots. This was not just this grain, but similar conclusions were found for another grain containing a Ba-rich inner core. Thus, we again identify a pseudocubic phase. The lattice parameter, whilst not quite as large as that for the shell region, was clearly larger than for most of the outer core. Seeing as it is structurally very similar to the shell, although with a rather different chemistry, it is no surprise that this was not identified in refinements of X-ray diffraction data. Interestingly, we have so far been unsuccessful in discerning any domain structure in this inner core region (see Figure S4) and it may be non-ferroelectric, or only polarises with field on it, but retains little domain structure at zero field. The question remains as to why this phase even exists at all and why it is pseudocubic. BaFeO3-BiFeO3 solid solutions in the middle of the tie line tend to form tetragonal structures in a centrosymmetric space group (No. 123 -P4/mmm) with a very small c/a ratio, which might explain why our inner core appears pseudocubic and shows no signs of domain structure. This still does not explain fully why it should be favoured to form under these conditions, but it maybe explains why the structure seen is formed when this composition results from the segregation frozen in by quenching. Supplemental Materials Further work, for example using thermodynamic modelling, would be needed to elucidate why the observed phase segregation is exhibited in this system. Conclusion The nanoscale structure and chemistry within the core-shell structure of a quenched Bi(Fe0.97Ti0.03)O3-BaTiO3 mixed oxide ceramic has been investigated using various STEM techniques. EELS mapping was used to map the Ba, Fe and Ti contents simultaneously, while mapping of Bi content was done separately using the Bi M4,5 edge, due to its high energy. To correlate the chemical mapping with the crystallography, SPED was performed along a <112>primitive direction in the same grain using a prototype system with a direct electron detector, and the data was analysed using open-source routines to determine the integrated intensity for superlattice reflections corresponding to antiphase octahedral tilting. The same dataset was analysed to determine the shifts of the diffraction spots and thereby map the lattice parameter with respect to a reference pattern. The work clearly shows that there are three distinct chemistries present, each having a distinct crystallographic structure associated with it. Firstly, an apparently-pseudocubic shell that is enriched in Ba and Ti (and a relatively large lattice parameter). Secondly, an octahedrally tilted outer core richest in Bi and Fe (showing variation in lattice parameters in different directions, suggesting an inherent domain structure as corroborated by dark field TEM images), fitting well with expectations of an R3c BiFeO3-like structure as a major phase in this system. And thirdly and finally, an apparently-pseudocubic inner core phase richer in Ba and very low in Ti (and a lattice parameter similar to the BaTiO3-rich shell), which may indicate a phase somewhere between BiFeO3 and BaFeO3. By comparison with previous literature and by the absence of any discernible domain structure, the inner core phase appears to be nonpolar and therefore, unlikely to be involved in the overall ferroelectric properties. This work clearly demonstrates the power of combining precession electron diffraction and EELS for correlative studies of nanoscale structure and chemistry in complex mixed oxide ceramics, especially when using new electron counting detectors for the SPED. We expect this will be of much wider applicability in a range of different ceramic materials with deliberately inhomogeneous microstructures. Supplemental Materials Exemplar diffraction patterns from <110>primitive and <112>primitive in BiFeO3 Figure S1 shows schematic calculated diffraction patterns (CrystalMaker / A full list of equivalent directions is shown in Table 1 was obtained in a separate EELS acquisition, in which the energy range of 1812-3848eV with a dispersion of 1eV/channel, so that Bi could be mapped directly. Figure S3 (a) shows the spectra for each region (averaged over 80 pixels) in the energy range containing the Bi M edge. The spectra have been normalised within the range of 2451-2551eV (just before the peak), so as variations in the Bi edge can be discerned between the three regions. (b) shows the absolute counts for each of the spectra after a background subtraction. Simultaneously acquired HAADF signal of the same region. Scale bar represents 500nm. Figure S4 shows a TEM dark field image obtained using the 011 $ reflection alongside the diffraction pattern to which the grain was orientated, the pc direction. The dark field image clearly shows the presence of a domain structure in the outer core phase (BiFeO3 rich), while the shell and inner core phase show a clear lack of domain structure, which would be expected for a pseudocubic phase. Corresponding diffraction pattern to which the grain was aligned. The dark field image was formed using the 011 $ reflection. Figure S5 shows the polarisation-electric field hysteresis loops for both slow-cooled and quenched ceramics of this composition, clearly showing a high remanent polarisation for the quenched sample with respect to the slow-cooled. |
Occupational Types and Antenatal Care Attendance Among Women in Ghana Improving antenatal care is considered a priority and has been relevant toward achieving the Millennium Development Goals (MDGs), yet antenatal care attendance remains relatively low in Ghana. Guided by the Andersen and Newman framework and employing logit models, we examine associations between occupational types and antenatal care among Ghanaian women aged 1549. Type of occupation, conceptualized as a predisposing factor, has a significant impact on the frequency and timing of antenatal care attendance at the bivariate level. The effect of occupational type was considerably mediated, however, when other socioeconomic variables such as wealth status were controlled in the multivariate models. |
ARTS AND CULTURE AS CREATIVE LEARNING OF STUDENTS THROUGH CULTURAL PRODUCT DESIGN The study explores whether a design activity could promote creative learning expression and development among students regarding arts and culture issues through cultural product design. Therefore, students engage in designing a cultural product model. The study aims to analyze their ability to develop arts and culture through sketches and an appearance model. The research project was conducted to observe students (aged 1820 years) as they negotiated and shared creative ideas during the process of cultural product design, interaction with fellow students, and the design presentation. The results indicate that design activities significantly contributed to studentsarts and culture learning by developing creative ideas through cultural product design. Moreover, students developed reasoning, communication, and collaboration skills during the development of their work. |
Last week, France’s executive duo — President François Hollande and Prime Minister Manuel Valls shuffled the French cabinet, getting rid of the economy minister, Arnaud Montebourg, after he publicly criticized the government’s fealty to German-imposed austerity measures. Emmanuel Macron, a business-friendly former Rothschild banker and 36-year-old political prodigy, has been anointed his replacement.
With this kerfuffle, the Socialist Party has been split into two factions — one supporting the bitter medicine of slashing government spending prescribed by the European Central Bank and Angela Merkel’s government in Germany, and the other joining a growing chorus warning that austerity is precisely the wrong remedy for the euro zone’s current economic malaise. Mr. Hollande has said that his government will not waver from the course he laid out in a speech on Dec. 31: a responsibility pact where business, in exchange for corporate tax cuts, promises to create jobs. But the pact won’t take effect until 2015. Meanwhile, unemployment, which Mr. Hollande promised to bring down this year, has hit a high of 11 percent.
French manufacturing has contracted for four consecutive months. Economic growth for 2014 has flatlined at nearly zero, forcing France to scrap deficit-reduction targets pledged to the European Union.
On the domestic front, a Socialist government at odds with much of the party will have a harder time pushing through legislation on clean energy, terrorism and aging. While ridding the government of Mr. Montebourg’s strident protectionism is not necessarily a bad idea, stubbornly hewing to the austerity line dictated by Berlin and the European Central Bank is likely to prove as disastrous for France as it is proving for Europe as a whole. |
The road to a Romney victory is really, really rocky. Ezra Klein sums this up in the following piece. A few excerpts:
On the presidential level, where everyone running campaigns is very, very good at their jobs, campaign infighting and incoherence tend to be the result of a candidate being behind in the polls, not the cause of it. Romney is behind and has been there for quite some time. According to the Real Clear Politics average of head-to-head polls, Romney hasn't led the race since October 2011. The closest he came to a lead in the polls this year was during the Republican National Convention, when he managed to ... tie Obama...
This year, it was the Democrats who made the biggest gains from before to after the conventions. Obama is leading by 3 percent in the Real Clear Politics average of polls, about double his lead before the Republican convention. If that doesn't fade by the end of the week or so -- that is, if it proves to be a real lead rather than a post-convention bounce -- then there's simply no example in the past 15 elections of a candidate coming back from a post-convention deficit to win the popular vote.
This is about the point where I'm supposed to write: That said, the race remains close, and the debates are coming soon. It's still anyone's game. But the most surprising of Erikson and Wlezien's results, and the most dispiriting for the Romney campaign, is that unlike the conventions, the debates don't tend to matter. There's "a fairly strong degree of continuity from before to after the debates," they write. That's true even when the trailing candidate is judged to have "won" the debates. "Voters seem to have little difficulty proclaiming one candidate the 'winner' of a debate and then voting for the opponent," Erikson and Wlezien say.
Gallup agrees. The august polling firm reviewed the surveys it did before and after every televised presidential debate and concluded they "reveal few instances in which the debates may have had a substantive impact on election outcomes. "
The Romney campaign tends to point to two elections to show how its candidate could win this thing. There's 1980, when Jimmy Carter supposedly led Ronald Reagan until the debates, and 1988, when Michael Dukakis was leading by 13 points after his convention. In fact, Reagan led going into the 1980 debates. And although Dukakis's convention bounce was indeed large, it was wiped out by Bush's convention bounce, which put him back in the lead.
I think there is something about this particular moment in liberalism wherein we attribute magical powers to the letters G and O and P. There seems to be a popular sense that Sheldon Adelson is an archlich , and the Koch brothers are the Crimson Twins. Maybe it's the 2000 election, I don't really know.
I am not making predictions, but I am going to gush here: I think Barack Obama is a gifted politician, and a ruthless campaigner. That his opponents (and even some of us) don't really get this, that we think he is merely lucky, only heightens the joy I feel watching him do work. I don't expect to ever feel like this again in my life. The good times are so rare. As a liberal, I see nothing wrong with looking at the math, and then enjoying the moment. It does not preclude voting, nor making sure friends and family vote. If I'm wrong, I'm wrong. I'll move on.
The thing is this: As a black person, there's a sort of Cinderella effect. We were not supposed to be here -- not in this time. We were supposed to inaugurate Starfleet before we inaugurated a black president. And yet here we are. And it has been so much worse in the past.
Not to go all race man, but I cut on the television and I see Barack Obama say, "I'll let the American people be the judge of that" and I get warm in a way that I know my people understand. And none of this was supposed to happen. When I was young I was convinced that I should have been black in another time. (Wouldn't it have been great to be like my Dad, rocking the black beret, and aiming guns at the cops?) Sometimes I fall victim to Civil War fantasy, but in my heart I would not have wanted to see any other time, as a black person, than this one.
It is a particular thing to be black and watch Barack Obama. I can't even explain it. There is a picture of Muhammad Ali after he beats Sonny Liston where where he, with mouth agape, points at the people sitting in the press room who insisted the Louisville Lip would be killed. The feeling conveyed in that picture is what it's like to be black and watch Obama.
I don't know if that translates. Perhaps I need some libertarian cousins. |
<gh_stars>1-10
/* Copyright (c) 2001-2019, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hsqldb.types;
import java.io.Serializable;
import org.hsqldb.error.Error;
import org.hsqldb.error.ErrorCode;
import org.hsqldb.lib.InOutUtil;
/**
* Represents of an instance of an OTHER field value for direct storage.<p>
*
* Objects need not implement Serializable to be stored in the mem: database.
* They are stored as-is and reflect any changes to the stored Objects by the
* application program.
*
* @author <NAME> (<EMAIL> dot sourceforge.net)
* @version 2.3.4
* @since 1.9.0
*/
public class JavaObjectDataInternal extends JavaObjectData {
Object object;
/**
* Constructor used inside the engine when an already serialized
* Object is read from a file.
*
* If the Object is not serializable, this method throws an exception.
*/
public JavaObjectDataInternal(byte[] data) {
try {
object = InOutUtil.deserialize(data);
} catch (Exception e) {
throw Error.error(ErrorCode.X_22521, e.toString());
}
}
/**
* Constructor used inside the engine.
*/
public JavaObjectDataInternal(Object o) {
object = o;
}
public byte[] getBytes() {
try {
if (object instanceof Serializable) {
return InOutUtil.serialize((Serializable) object);
}
} catch (Exception e) {}
return new byte[]{};
}
public int getBytesLength() {
try {
if (object instanceof Serializable) {
byte[] data = InOutUtil.serialize((Serializable) object);
return data.length;
}
} catch (Exception e) {}
return 0;
}
/**
* This method is called from classes implementing the JDBC
* interfaces. Inside the engine it is used for conversion from a value of
* type OTHER to another type. It will throw if the OTHER is an instance
* of a class that is not available.
*/
public Object getObject() {
return object;
}
/**
* Returns String representation of this object.
*
* @return a String representation of this object.
*/
public String toString() {
return super.toString();
}
}
|
Acting EPA chief Andrew Wheeler, a former coal lobbyist, just signed his first major regulatory amendment — making it easier for corporations to discard coal ash however they see fit.
The Environmental Protection Agency on Wednesday finalized a rule that rolls back standards for disposing of the toxic ash produced by burning coal, The Hill reports. The amendment was in the works for several months, but when Wheeler took over for Scott Pruitt earlier this month, he took the reins. Pruitt resigned as EPA administrator following a string of ethics scandals.
The amendment backpedals on regulations put in place by the Obama administration, which mandated strict federal standards for coal ash disposal in 2015. In a statement, the EPA said relaxing the standards would save $31.4 million a year in regulatory costs, as states are given authority to loosen or waive requirements for companies.
"These amendments provide states and utilities much-needed flexibility in the management of coal ash, while ensuring human health and the environment are protected," said Wheeler in the statement. Environmental groups disagree, reports The Hill, and immediately condemned the measure as dangerous to groundwater and air pollution. |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03
// <filesystem>
// class directory_entry
// directory_entry& operator=(directory_entry const&) = default;
// directory_entry& operator=(directory_entry&&) noexcept = default;
// void assign(path const&);
// void replace_filename(path const&);
#include "filesystem_include.h"
#include <type_traits>
#include <cassert>
#include "test_macros.h"
#include "rapid-cxx-test.h"
#include "filesystem_test_helper.h"
TEST_SUITE(directory_entry_mods_suite)
TEST_CASE(test_replace_filename_method) {
using namespace fs;
{
directory_entry e;
path replace;
static_assert(noexcept(e.replace_filename(replace)) == false,
"operation cannot be noexcept");
static_assert(
std::is_same<decltype(e.replace_filename(replace)), void>::value,
"operation must return void");
}
{
const path p("/path/to/foo.exe");
const path replace("bar.out");
const path expect("/path/to/bar.out");
directory_entry e(p);
TEST_CHECK(e.path() == p);
e.replace_filename(replace);
TEST_CHECK(e.path() == expect);
}
}
TEST_CASE(test_replace_filename_ec_method) {
using namespace fs;
static_test_env static_env;
{
directory_entry e;
path replace;
std::error_code ec;
static_assert(noexcept(e.replace_filename(replace, ec)) == false,
"operation cannot be noexcept");
static_assert(
std::is_same<decltype(e.replace_filename(replace, ec)), void>::value,
"operation must return void");
}
{
const path p("/path/to/foo.exe");
const path replace("bar.out");
const path expect("/path/to/bar.out");
directory_entry e(p);
TEST_CHECK(e.path() == p);
std::error_code ec = GetTestEC();
e.replace_filename(replace, ec);
TEST_CHECK(e.path() == expect);
TEST_CHECK(ErrorIs(ec, std::errc::no_such_file_or_directory));
}
{
const path p = static_env.EmptyFile;
const path expect = static_env.NonEmptyFile;
const path replace = static_env.NonEmptyFile.filename();
TEST_REQUIRE(expect.parent_path() == p.parent_path());
directory_entry e(p);
TEST_CHECK(e.path() == p);
std::error_code ec = GetTestEC();
e.replace_filename(replace, ec);
TEST_CHECK(e.path() == expect);
TEST_CHECK(!ec);
}
}
TEST_CASE(test_replace_filename_calls_refresh) {
using namespace fs;
scoped_test_env env;
const path dir = env.create_dir("dir");
const path file = env.create_file("dir/file", 42);
const path file_two = env.create_file("dir/file_two", 101);
const path sym = env.create_symlink("dir/file", "sym");
const path sym_two = env.create_symlink("dir/file_two", "sym_two");
{
directory_entry ent(file);
ent.replace_filename(file_two.filename());
TEST_REQUIRE(ent.path() == file_two);
// removing the file demonstrates that the values where cached previously.
LIBCPP_ONLY(remove(file_two));
TEST_CHECK(ent.file_size() == 101);
}
env.create_file("dir/file_two", 99);
{
directory_entry ent(sym);
ent.replace_filename(sym_two.filename());
TEST_REQUIRE(ent.path() == sym_two);
LIBCPP_ONLY(remove(file_two));
LIBCPP_ONLY(remove(sym_two));
TEST_CHECK(ent.is_symlink());
TEST_CHECK(ent.is_regular_file());
TEST_CHECK(ent.file_size() == 99);
}
}
#ifndef TEST_WIN_NO_FILESYSTEM_PERMS_NONE
// Windows doesn't support setting perms::none to trigger failures
// reading directories.
TEST_CASE(test_replace_filename_propagates_error) {
using namespace fs;
scoped_test_env env;
const path dir = env.create_dir("dir");
const path file = env.create_file("dir/file", 42);
const path file_two = env.create_file("dir/file_two", 99);
const path file_out_of_dir = env.create_file("file_three", 101);
const path sym_out_of_dir = env.create_symlink("dir/file", "sym");
const path sym_out_of_dir_two = env.create_symlink("dir/file", "sym_two");
const path sym_in_dir = env.create_symlink("file_two", "dir/sym_three");
const path sym_in_dir_two = env.create_symlink("file_two", "dir/sym_four");
const perms old_perms = status(dir).permissions();
{
directory_entry ent(file);
permissions(dir, perms::none);
std::error_code ec = GetTestEC();
ent.replace_filename(file_two.filename(), ec);
TEST_CHECK(ErrorIs(ec, std::errc::permission_denied));
}
permissions(dir, old_perms);
{
directory_entry ent(sym_in_dir);
permissions(dir, perms::none);
std::error_code ec = GetTestEC();
ent.replace_filename(sym_in_dir_two.filename(), ec);
TEST_CHECK(ErrorIs(ec, std::errc::permission_denied));
}
permissions(dir, old_perms);
{
directory_entry ent(sym_out_of_dir);
permissions(dir, perms::none);
std::error_code ec = GetTestEC();
ent.replace_filename(sym_out_of_dir_two.filename(), ec);
TEST_CHECK(!ec);
TEST_CHECK(ent.is_symlink());
ec = GetTestEC();
TEST_CHECK(!ent.exists(ec));
TEST_CHECK(ErrorIs(ec, std::errc::permission_denied));
}
}
#endif
TEST_SUITE_END()
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from shapely.geometry import Polygon, Point
from shapely.geometry.base import BaseGeometry
from sedona.utils.decorators import require
class Envelope(Polygon):
def __init__(self, minx=0, maxx=1, miny=0, maxy=1):
self.minx = minx
self.maxx = maxx
self.miny = miny
self.maxy = maxy
super().__init__([
[self.minx, self.miny],
[self.minx, self.maxy],
[self.maxx, self.maxy],
[self.maxx, self.miny]
])
@require(["Envelope"])
def create_jvm_instance(self, jvm):
return jvm.Envelope(
self.minx, self.maxx, self.miny, self.maxy
)
@classmethod
def from_jvm_instance(cls, java_obj):
return cls(
minx=java_obj.getMinX(),
maxx=java_obj.getMaxX(),
miny=java_obj.getMinY(),
maxy=java_obj.getMaxY(),
)
def to_bytes(self):
from sedona.core.serde.binary.buffer import BinaryBuffer
bin_buffer = BinaryBuffer()
bin_buffer.put_double(self.minx)
bin_buffer.put_double(self.maxx)
bin_buffer.put_double(self.miny)
bin_buffer.put_double(self.maxy)
return bin_buffer.byte_array
@classmethod
def from_shapely_geom(cls, geometry: BaseGeometry):
if isinstance(geometry, Point):
return cls(geometry.x, geometry.x, geometry.y, geometry.y)
else:
envelope = geometry.envelope
exteriors = envelope.exterior
coordinates = list(exteriors.coords)
x_coord = [coord[0] for coord in coordinates]
y_coord = [coord[1] for coord in coordinates]
return cls(min(x_coord), max(x_coord), min(y_coord), max(y_coord))
def __reduce__(self):
return (self.__class__, (), dict(
minx=self.minx,
maxx=self.maxx,
miny=self.miny,
maxy=self.maxy,
))
def __getstate__(self):
return dict(
minx=self.minx,
maxx=self.maxx,
miny=self.miny,
maxy=self.maxy,
)
def __setstate__(self, state):
self.minx = state.get("minx", 0)
self.minx = state.get("maxx", 1)
self.minx = state.get("miny", 0)
self.minx = state.get("maxy", 1)
@property
def __array_interface__(self):
raise NotImplementedError()
def _get_coords(self):
raise NotImplementedError()
def _set_coords(self, ob):
raise NotImplementedError()
@property
def coords(self):
raise NotImplementedError()
def __repr__(self):
return f"Envelope({self.minx}, {self.maxx}, {self.miny}, {self.maxy})"
|
Mapping of protective forest coverage of territories and assessment of its optimality Protective forest plantations are an integral part of agroforestry landscapes that serve as an ecological frame and contribute to the expanded reproduction of soil fertility. The problem of assessing the actual protective forest cover of territories is relevant. The solution of this issue allows you to identify the need, sequence and volume of forest reclamation work. The problem of mapping and assessing the protective forest cover of territories is closely related to the tasks of identifying the optimal forest cover of territories and substantiating approaches to the allocation of spatial-territorial complexes. The boundaries of the identified contours directly affect the values of specific indicators, which are the basis for the gradation of the need for forest reclamation work. The conducted studies demonstrate the possibilities of using the QGIS software package for the purpose of assessing the protective forest cover of the territory. The interpretation and creation of a cartographic model of protective forest plantations of the study area was carried out using QuickBird satellite images. The assessment was made on the basis of the calculation of specific indicators within the boundaries of landscapes for the territory of the Ilovlinsky District of the Volgograd region. As a standard for comparing the studied indicators, indicators of the protective forest cover of the Kachalino pilot farm were used. The application of the landscape-typological approach to the identification of territorial complexes made it possible to approach the issue of assessing the protective forest cover of territories in a more differentiated way than when using administrative boundaries. As a result of the study, landscape areas were identified, the protective forest cover of which is close to the normative, as well as those areas that need agroforestry measures. Cartographic work carried out in the QGIS software package confirms its effectiveness and allows us to recommend its use in agroforestry research related to the parallel application of various approaches to the allocation of territorial complexes. |
Suicide Behaviors in Adult Inpatients with Mental Disorders in Beijing, China Background: This study examined the tendency and suicidal behavior rates of Chinese adult inpatients with different types of mental disorders from 2010 to 2015. The aim was to provide some interesting clues for further studies. Methods: Adult patients with mental disorders who were hospitalized in Beijing Anding hospital from 1 January 2010 to 31 December 2015 were included. Chi-square tests were used to compare the difference among inpatients with mental disorders by gender and year. Frequency, trend and suicidal behavior rates of inpatients with mental disorders were graphed. Results: A total of 17,244 psychiatric adult inpatients were included in our study. About 53.2% of the inpatients had mood disorders, followed by schizophrenia, which accounted for 34.6%. The proportion of female inpatients with mental disorders was larger than that of males (52.6% to 47.4%). Of the total, 3296 psychiatric inpatients were recognized as having suicidal behaviors. The rate of suicidal behavior among all inpatients was 19.1%, and it varied over the years. The suicidal behavior rate of female inpatients with mood disorders was much higher than that of the corresponding male inpatients. Conclusions: The presence of suicidal behavior varied among people with different types of mental disorders. For each type of mental illness, identifying the risk of specific suicide behavior would help tailor-make preventive efforts accordingly. Introduction Suicide is among the leading causes of death and injury around the world, with over 800,000 people dying or one death every 40 s by suicide every year. In China, suicide is the fifth most important cause of death, with around 287,000 suicide deaths per year during 1995 to 1999, accounting for up to a third of suicides worldwide. It is estimated that 48~500 million people are thought to experience suicide bereavement each year, which leads to a series of social and public health issues. Thus, people who experience such a loss, the wider public and health professionals often struggle to understand this complicated behavior, although in many cultures the topic still remains a taboo. Mental health is a fundamental and inseparable component of the WHO's definition of health. Most notably, mental disorders contribute to mortality through suicide. They represent the most commonly studied risk factor for suicide, and in high-income countries the link between mental disorders and suicide is well established [1,. Although studies from western countries showed over 90% of suicides were associated with mental disorders, in China, where about 60% of suicide victims had a psychiatric diagnosis, this proportion was substantially lower. In China, it was estimated that 173 million adults had a diagnosable psychiatric disorder, however, mental health services have been a low priority. Suicide prevention as well as strategies to tackle stigma and discrimination against people with mental disorders were absent from the China's national work plan for mental health 2015-2020. At present, the degree of psychopathology underpinning suicide cannot be clearly evaluated. For suicide prevention, there is still a lot of work remaining to be done for people with mental disorders. It is still unknown whether the suicide rate and risk differed in each category of mental disorders in China. In this study, we examined the admission tendencies of inpatients with mental disorder and tendency of the suicidal behavior rates during recent years. We conducted a preliminary examination of the association between suicidal behaviors and some common mental disorders that were generally regarded with a high level of concern by using inpatient data from the Beijing Anding Hospital (Beijing, China). Data Collection Patients with mental disorders who were hospitalized in Beijing Anding hospital-one of the top five psychiatric hospitals in China-were consecutively collected from 1 January 2010 to 31 December 2015. The Beijing Anding Hospital receives psychiatric patients mainly from the Beijing area. There were 800 hospital beds in Beijing Anding Hospital, which was unchanged from 2010 to 2015. The trend of inpatient numbers in this hospital would highly reflect the trend of numbers of psychiatric patients in Beijing during the 6 years. All of the medical records of the inpatients were collected for this study. Our study was conducted in accordance with the Declaration of Helsinki, and was reviewed and approved by the Institutional Review Board of Capital Medical University (2014SY37). The inclusion criteria were: (a) it was the first time that the patients were hospitalized in Beijing Anding Hospital according to medical records; (b) the patients were at least 18 years old. The exclusion criteria included: (a) the patient was not of Chinese nationality; (b) the patient's mental disorder diagnosis was not definitive. The raw dataset consists of individual-level data for each patient, including patient's medical record number (a unique lifetime identification number), age, gender, admitting diagnosis, discharge diagnosis, the patient's chief complaint, present medical history, past medical history, family history and personal history. Diagnoses of Mental Disorders The patients were diagnosed by at least two mental health professionals (attending or senior doctors). Mental disorders are a set of mental and behavioral disorders as defined by the International Statistical Classification of Diseases and Related Health Problems (ICD-10). These disorders include organic, including symptomatic mental disorders (F00-F09), mental and behavioral disorders due to psychoactive substance use (F10-F19), schizophrenia, schizotypal and delusional disorders (F20-F29), mood (affective) disorders (F30-F39), neurotic, stress-related somatic disorders (F40-F48), behavioral syndromes associated with physiological disturbances and physical factors (F50-F59), disorders of adult personality and behavior (F60-F69), mental retardation (F70-F79), disorders of psychological development (F80-F89), behavioral and emotional disorders with onset usually occurring in childhood and adolescence (F90-F98) and unspecified mental disorder (F99). The inpatients were categorized according to their primary discharge diagnosis, which was more accurate than admitting diagnosis. Suicidal Behaviors According to the WHO report Preventing suicide: A global imperative, suicide refers to an act of deliberately killing oneself. Suicidal behaviors are defined as a range of behaviors including thinking about suicide (or suicide ideation), planning for suicide, attempted suicide (or incomplete suicide) and complete suicide. For the purpose of this study, suicidal behaviors included "suicide ideation", "planning for suicide", and "attempted suicide". Suicidal ideation concerns thoughts about or intent to suicide. Planning for suicide is defined as those with mental disorders who planned to die by suicide but had not attempted the act of suicide yet. Attempted suicide is defined as patients who have carried out suicidal behaviors but survived, saved by others or whose fatal actions were stopped. It refers to intentionally self-inflicted poisoning, injury or self-harm with a fatal intent. Suicidal behavior was one of the issues of most concern, which was routinely and mandatorily asked by professionals in Beijing Anding Hospital. Mental health specialists asked the patients and their relatives or guardians about the suicidal behaviors occurring 2 months before the patients admission to the hospital, and recorded whether or not the patients had suicidal behaviors. A new variable "suicidal behavior in past 2 months (0 = No, 1 = Yes)" was created according to these records. Data Management and Analysis We categorized the patients according to their primary discharge diagnosis, and manually divided them into groups for the convenience of our analysis. Inpatients' suicidal behaviors were identified by researchers according to the information recorded in the "patient's chief complaint", "present medical history" and "past medical history". Two professionals read all of these records independently and identified whether or not the inpatients presented suicide ideation or attempted suicide (as the important reason attend to the hospital) during the past 2 months right before being admitted in the hospital. A single identification for each inpatient would be made after combining two professionals' opinions (different opinions would be discussed and come to agreement). Data were managed and analyzed using SAS 9.4 (SAS Institute, Cary, NC, USA). We at first provided the frequency and percentage distribution of the inpatients with mental disorders by year and gender. Chi-square tests were used to compare the differences among inpatients with mental disorders by gender and year, and a linear-by-linear association was adopted to test the linear trends for each category of mental disorder. We graphed the frequency, trend and suicidal behavior rates for inpatients with mental disorders, frequency of inpatients with suicidal behaviors for each category of mental disorder, and the suicidal behavior rates of inpatients with each category of mental disorder by year. Any p-value less than or equal to 0.05 was considered statistically significant. Results A total of 17,244 inpatients who were admitted to Beijing Anding hospital between 1 January 2010 and 31 December 2015, were included in our study. These inpatients were all Chinese citizens and no less than 18 years old. There were eight categories of inpatients with mental disorders, which were "mood disorders", "schizophrenia, schizotypal and delusional disorders (psychotic disorders in short)", "mental and behavioral disorders due to psychoactive substance use (substance use disorders in short)", "organic, including symptomatic, mental disorders (organic mental disorders in short)", "neurotic, stress-related and somatoform disorders (somatoform disorders in short)", "mental retardation", "behavioral and emotional disorders with onset usually occurring in childhood and adolescence (occurring in childhood and adolescence in short)" and "others". About 53.2% of the total inpatients were mood disorders, followed by psychotic disorders, which accounted for 34.6%. Inpatients with mental disorders had increased in the 6-year period, especially in inpatients with mood disorders and schizophrenia, while the number of other mental disorders showed little change during 6 years. More details are shown in Table 1. Table 2 presents the frequency and percentage of inpatients with mental disorders in Beijing Anding hospital by gender. Overall 52.6% of the inpatients with mental disorders were female. The proportions of mental disorders significantly differed between males and females. The proportion of female inpatients with mental disorders was larger than that of males (52.6% to 47.4%). The numbers increased steadily both in males and females, especially in inpatients with mood disorders and schizophrenia. Among the included subjects, 3296 of them were recognized as having suicidal behaviors. The rate of suicidal behaviors was 19.1%, and differed each year with a peak in 2012, as shown in Figure 1. The number of inpatients with suicidal behaviors increased steadily from 2010 to 2014, and slightly decreased in 2015. Suicidal behavior rates showed a significant linear trend during the 6 years studied. Table 2 presents the frequency and percentage of inpatients with mental disorders in Beijing Anding hospital by gender. Overall 52.6% of the inpatients with mental disorders were female. The proportions of mental disorders significantly differed between males and females. The proportion of female inpatients with mental disorders was larger than that of males (52.6% to 47.4%). The numbers increased steadily both in males and females, especially in inpatients with mood disorders and schizophrenia. Among the included subjects, 3296 of them were recognized as having suicidal behaviors. The rate of suicidal behaviors was 19.1%, and differed each year with a peak in 2012, as shown in Figure 1. The number of inpatients with suicidal behaviors increased steadily from 2010 to 2014, and slightly decreased in 2015. Suicidal behavior rates showed a significant linear trend during the 6 years studied. Most of the inpatients with suicidal behaviors were those with mood disorders. The second group was inpatients with psychotic disorders, and the number increased greatly in 2012, then changed little from 2013 to 2015. The suicidal behavior rates in mood disorders were the highest among all inpatients, followed by "neurotic, stress-related and somatoform disorders", "organic, including symptomatic mental disorders", "schizophrenia, schizotypal and delusional disorders" and "mental and behavioral disorders due to psychoactive substance use". Suicidal behavior rates among inpatients with mood disorders showed significant linear trend during 6 years. More details are shown in Figure 2. Most of the inpatients with suicidal behaviors were those with mood disorders. The second group was inpatients with psychotic disorders, and the number increased greatly in 2012, then changed little from 2013 to 2015. The suicidal behavior rates in mood disorders were the highest among all inpatients, followed by "neurotic, stress-related and somatoform disorders", "organic, including symptomatic mental disorders", "schizophrenia, schizotypal and delusional disorders" and "mental and behavioral disorders due to psychoactive substance use". Suicidal behavior rates among inpatients with mood disorders showed significant linear trend during 6 years. More details are shown in Figure 2. The total suicidal behavior rate for the male inpatients was 15.3%. The suicidal behavior rates in mood disorders were the highest, followed by "neurotic, stress-related and somatoform disorders", "organic, including symptomatic mental disorders", "schizophrenia, schizotypal and delusional disorders" and "mental and behavioral disorders due to psychoactive substance use" (Figure 3a). In female inpatients, the suicidal behavior rate was 22.6%. The female suicidal behavior rates for mood disorders were much higher than those of males, and it was also the highest overall. Female inpatients with "neurotic, stress-related and somatoform disorders" ranked in second place in terms of suicidal behavior rates. The following were "organic, including symptomatic mental disorders", "schizophrenia, schizotypal and delusional disorders" (Figure 3b). More details are shown in Figure 3. The rates of suicidal ideation and attempted suicide differed in the different mental disorder categories. The inpatients with mood disorders had the highest rates of suicide ideation. The following were inpatients with somatoform disorders, psychotic disorders, organic mental disorders, psychotic disorders, substance use disorders and mental retardation. The rates of attempted suicide followed the same order. Among inpatients with mood disorders, the rate of suicidal ideation was significantly larger than the rate of attempted suicide. While among inpatients with other mental disorders, there were no significant differences. More details are shown in Table 3. The total suicidal behavior rate for the male inpatients was 15.3%. The suicidal behavior rates in mood disorders were the highest, followed by "neurotic, stress-related and somatoform disorders", "organic, including symptomatic mental disorders", "schizophrenia, schizotypal and delusional disorders" and "mental and behavioral disorders due to psychoactive substance use" (Figure 3a). In female inpatients, the suicidal behavior rate was 22.6%. The female suicidal behavior rates for mood disorders were much higher than those of males, and it was also the highest overall. Female inpatients with "neurotic, stress-related and somatoform disorders" ranked in second place in terms of suicidal behavior rates. The following were "organic, including symptomatic mental disorders", "schizophrenia, schizotypal and delusional disorders" (Figure 3b). More details are shown in Figure 3 The rates of suicidal ideation and attempted suicide differed in the different mental disorder categories. The inpatients with mood disorders had the highest rates of suicide ideation. The following were inpatients with somatoform disorders, psychotic disorders, organic mental disorders, psychotic disorders, substance use disorders and mental retardation. The rates of attempted suicide followed the same order. Among inpatients with mood disorders, the rate of suicidal ideation was significantly larger than the rate of attempted suicide. While among inpatients with other mental disorders, there were no significant differences. More details are shown in Table 3. Discussion Few studies have investigated the tendency and suicidal behaviors among Chinese adult inpatients with different types of mental disorders, especially studies with large sample sizes. In this study, we included 17244 inpatients and found that the number of inpatients with mental disorders increased from 2010 to 2015, and the number of inpatients with suicidal behaviors also increased, especially in inpatients with mood disorders and schizophrenia. The prevalence of mental disorders was 17.5% in China, one of the highest rates in the world, which makes it a serious public health issue. However, mental health had not received sufficient attention in China for various historical reasons, and the government budget for mental health care was very low compared to the extent of burden of mental disorders. According to our data, the inpatients with mental disorders increased steadily from 2010 to 2015 (except for 2012). There were a few possible interpretations of this finding. First, the number of psychiatric patients in China increased these years. A second interpretation was that the awareness from the public on the mental health improved especially after the enforcement of the Mental Health Law of the People's Republic of China since 2013, and an increasing number of people with mental illness sought help at psychiatric hospitals. In this study, inpatients with mood disorders and psychotic disorders represented the overwhelming majority among all psychiatric inpatients, accounting for 53.2% and 34.6%, respectively. This was followed by the substance use disorders (3.7%), organic mental disorders (3.1%) and somatoform disorders (2.7%). It was different for a previous study in China, which included the natural population and reported people with substance use disorders were much more than those with psychotic disorders. The different results might be attributed to the different populations adopted in the two studies. Mental disorders show a clear sex distinction across the world. Although findings from our study found that both the male and female inpatients with mood disorders took the majority among all categories of mental disorders, the proportions of male inpatients were much lower than that of females (the difference was about 10% each year). A similar situation happened among inpatients with somatoform disorders (male inpatients also represented a lower percentage). There was evidence that women reported a higher number of physical and psychological symptoms than men, and comorbidity was also more common among women than men, and it often took the form of a co-occurrence of somatoform disorders. Almost all the studies have shown that substance use disorders are much more common among men than women. Our results also indicated that there were much more male inpatients with substance use disorders than female ones. The individuals with substance use disorders in the West (North America and Europe) were much more than that in China especially for the people with alcohol abuse. The reason might be that alcohol abuse was considered to be a habit rather than a mental disorder in Chinese culture, and few people suffering from alcohol abuse went to hospital for help. Thus, the issue of substance use disorders might be far underestimated in China. In contrast to mood disorders and substance use disorders, schizophrenia and other mental disorders did not show clear differences in proportion between male and female inpatients in our study, which was consistent with former studies. However, Phillips et al. found that relative risk of suicide in rural residents with schizophrenia comparing those without was higher in men than in women, but in urban areas, the ratio was lower in men than women. Further studies are needed concerning the underlining mechanism. Mental disorders are one of the most important factors investigated in suicides. In the West, over 90% of suicides are associated with mental illness, while in China the proportion varied in different studies. In a nationally representative psychological autopsy study, Phillips et al. reported that 40% of suicide victims were diagnosed with depression, 7% with schizophrenia, and 7% with alcohol dependence. Zhang et al. found that 76% of rural suicide victims had a diagnosable mental illness in a psychological autopsy study. There were few studies concerned on suicide rate among confirmed patients with mental disorders in China. The suicide rates of each category of mental disorder and the relative risks of suicide among different mental disorders is still a mystery. Our study included ideation in suicidal behaviors. WHO report also included ideation in suicidal behavior for the purpose of simplicity since suicide ideation might more likely lead to suicide actions as the course of mental disorders last for years, though there is meaningful ongoing academic dialogue about such complex issue. We intended not to include deaths from suicide in this study, and in fact there were no such cases in this hospital during these 6 years. The overall suicide rates in China decreased sharply in the past two decades. The rates were about 23 per 100,000 people in 1990 and about 8 per 100,000 people in 2006. From 2006 to 2011, the suicide rates showed a fluctuation of around 8 per 100,000. The exact number of suicide rate in China was still controversial because different sources of data were used in previous studies, but a sharp reduction of the suicide rate from the 1990s to the 2010s is generally recognized. The reason is still unclear. According to some points of view, the reduction of pesticide toxicity might play an important role. Meanwhile, the rural labor migration from rural to urban areas might also be an important reason. Our study showed that the numbers of inpatients with suicidal behaviors increased from 2010 to 2015, yet the suicidal behavior rates showed a trend of fluctuations around 17%. The suicidal behavior rates were also fluctuating during the 6 years and showed a reduction tendency according to linear-by-linear association analysis. Previous studies suggested that a large number of individuals with schizophrenia attempt suicide during the course of their illness. Radomsky et al. reported that 30% of patients with schizophrenia had attempted suicide at least once during their lifetime, while Caldwell's study found that about 10% of persons with schizophrenia died by suicide. However, the suicide rate in Chinese people with schizophrenia was lower than that in the West. Phillips et al. found that the suicide rate in individuals with schizophrenia aged 15 years and older was 6.8 per 1000 people per year. The results of our study found that the suicidal behavior rate of schizophrenia was around 10%. The suicidal behavior rates of inpatients with schizophrenia were relatively low both in male and female inpatients compared with the West. Future studies should be carried out to find the mechanism or cause regarding this phenomenon. Alcohol dependence, one of the most important substance use disorders, might lead to more suicidal behaviors than mood disorders and schizophrenia in the West. However, the suicidal behavior rates of inpatients with substance use disorders were the lowest in male inpatients in this study (few female patients with substance use disorders). As stated above, substance use disorders, especially the alcohol dependence (over 90% among patients with substance use disorders, data was not shown) might potentially be a much more serious problem in China, which called for more studies. The suicidal behavior rate abruptly rose in 2012 and then declined, which seemed abnormal, because there was a reconstruction for one inpatient area in 2012 in Beijing Anding hospital (all together 15 inpatient areas), and a number of patients without suicidal behaviors (relatively less dangerous) in 2012 might not be admitted in the hospital. Nock et al. conducted survival models to examine the associations between individual disorders and subsequent suicidal behaviors using the National Comorbidity Survey data. Mood disorders played a major role in accounting for the onset of suicide ideation, followed by anxiety disorders, impulse-control disorder and substance use disorder. Besides, predictive effects of mood disorders to suicidal ideation were larger than that to attempted suicide. In our study, we also found that mood disorders and neurotic, stress-related somatoform disorders were the top two most important mental disorders associated with suicidal behaviors, and among inpatients with mood disorders, the rate of suicidal ideation was larger than that of attempted suicide. In this study our outcome measure represents suicidal behavior in the time recently before admission, i.e., it represent if they present at hospital with previous suicidal behavior, thus from our data we cannot comment on suicidal behavior in inpatients while admitted to hospital. We would conduct further studies to figure out which diagnostic categories displayed more suicidal behaviors during an inpatient stay, which would be better to apply for tailor made preventive efforts for an inpatient stay. Another limitation for this study was that it could only provide clues for the trend of inpatients with mental disorders in China. The data were limited by the admission rate, which might influence the results, and the Berkson's selection bias could not be eliminated. As was mentioned above, combining medical records from two or more hospitals was not possible in China. The sample size in this study was relatively small comparing to some western studies, which might lead to controversial inferences, especially for subgroups with small sample size. However, researches on mental disorders and suicidal behaviors were still in development stage in China, and there is a scarcity of studies about mental patients using large sample size survey. This study was a beneficial practice to provide ideas and a basis for further studies. Conclusions The number of inpatients increased steadily during recent years, and mood disorders and schizophrenia were the top two serious categories of mental disorders. The presence of suicidal behaviors varied in people with different types of mental disorders. Mood disorders might be the most important category of mental disorders associated with suicidal behaviors. Identification of specific suicidal behaviors risk for each type of mental illness would help tailor prevention efforts. |
#if !defined(__EMSCRIPTEN__)
#include <iostream>
#include <cstdio>
#include <numeric>
#include <SDL2/SDL.h>
#include <fstream>
#include <vector>
#include <algorithm>
#include <thread>
#include <mutex>
#include <chrono>
extern volatile bool hasQuit;
#endif
#include "types.hpp"
#include "cpu.hpp"
namespace PROF {
u32 hits[ sizeof(MMU::flash)>>1 ];
bool dumpOnExit = true;
void init( bool _hitCaller ){
}
}
|
Use of human growth hormone in a cachectic post-traumatic crush injury patient Somatropin, recombinant human growth hormone, is used for the treatment of growth hormone deficiencies and conditions with associated weight loss. A 42-year-old male was admitted to the trauma service after suffering a traumatic crush injury. Approximately five months later, the patient was readmitted due to cachexia and intractable vomiting. Somatropin (0.1mg/kg) injection therapy was initiated. This was a novel therapeutic approach to a patient that was otherwise declining. Despite complications with nutrition, somatropin appeared to augment weight gain. |
#pragma once
#include "shadow/renderer/buffer_layout.h"
namespace Shadow {
class VertexBuffer {
public:
explicit VertexBuffer(uint32_t size);
VertexBuffer(float* vertices, uint32_t size);
~VertexBuffer();
void Bind() const;
void Unbind() const;
const BufferLayout& GetLayout() const { return mLayout; }
void SetLayout(BufferLayout const& layout) { mLayout = layout; }
void SetData(const void* data, uint32_t size);
private:
uint32_t mRendererId = 0;
BufferLayout mLayout;
};
class IndexBuffer {
public:
IndexBuffer(uint32_t* indices, uint32_t count);
~IndexBuffer();
void Bind() const;
void Unbind() const;
uint32_t GetCount() const { return mIndicesCount; };
private:
uint32_t mRendererId = 0;
uint32_t mIndicesCount;
};
class ShaderStorageBuffer {
public:
ShaderStorageBuffer(float* vertices, uint32_t size);
~ShaderStorageBuffer();
void Bind() const;
void Unbind() const;
const BufferLayout& GetLayout() const { return mLayout; }
void SetLayout(BufferLayout const& lo) { mLayout = lo; }
private:
uint32_t mRendererId = 0;
BufferLayout mLayout;
};
}
|
We’ve seen all sorts of predictions for the Colts’ 2017 season so far, and most of them don’t have Indianapolis winning the AFC South.
But in ESPN’s recent predictions, based on their FPI metric, the Colts have hte best chance to win their division and are predicted to finish in first place.
Per ESPN, “a team's FPI rating combines its efficiency ratings on offense, defense and special teams -- based on each unit's expected points added per play -- with the sum of all three squad ratings yielding the overall FPI rating.” Using those FPI ratings, the season is simulated 10,000 times to develop these predictions.
Using that method, the Colts were given a 36% chance to win the AFC South, with 8.5 projected wins. The good news for Indy is that they have the best chance to win the AFC South, but the bad news is that they have the lowest chance to win their division of all eight teams picked to finish in first place in 2017.
Here’s what ESPN’s write-up had to say about the AFC South:
The AFC South might end up being the NFL's most competitive division in 2017. All four teams have at least a 10 percent chance of winning the title, and none of FPI's predicted division winners has a worse chance to win than the Colts at 36 percent. Part of the reason each team has a chance to compete is the relatively easy schedule each team faces (at least based on what we know about these teams three months before the start of the season). FPI has four of the nine easiest schedules in the league belonging to the members of the AFC South.
For comparison’s sake, the Colts’ 36% chance of winning the division was followed by the Titans (30.6%), Texans (22.5%), and Jaguars (10.9%).
It probably is encouraging to some Colts fans to see the team actually predicted to return to the top of the AFC South, since there have been varying opinions about the matter. It’s a very possible scenario, however, for a couple of reasons. First and foremost is the obvious one, and that’s quarterback Andrew Luck. Having him as the franchise player at the game’s most important position gives the Colts a big edge, and it gives them the clear best quarterback in the division.
Second, the Colts have one of the easiest schedules in the NFL, but part of that is due to the division - meaning that each of the four teams in the division have a very favorable schedule. Even still, though, the Colts couldn’t ask for a much better schedule for a hopeful return to the playoffs.
And third, the Colts should be at least somewhat improved in a number of areas, particularly on the defense (because it would be hard for them to be much worse). So with a hopefully improved defense, that should also benefit the team’s case.
All in all, though, the AFC South should indeed be a tight race in 2017, especially with the week 17 matchup between the Colts and Texans. That could be a huge game, just like the mid-December matchups between those two teams have been for the past few years. It should be a close race, but the Colts do figure to stand a very real shot at winning the AFC South and thus returning to the playoffs for the first time since 2014. |
The 13th of February 2016 is likely to go down in history as the awakening of the working class and the beginning of the class struggle in 21st century Hungary. Tens of thousands of people gathered in front of the Hungarian Parliament building demanding the abandonment of all educational “reforms” of the last 5 years. In spite of pouring rain thousands and thousands marched proudly, showing concern not just for education, but for the health service, for transport, against corruption and what is now commonly called the “mafia state”.
For the first time in a very long time, support for the teachers came from a wide variety of sectors, from local government workers, health workers, transport workers, miners, police personnel and even soldiers. Banners all over the square showed the support of official and unofficial unions and individuals with hand written slogans. The atmosphere was friendly, comradely and very, very supportive of the cause and to each other. Speakers came from all spheres and were heard with enthusiasm and applause. At the end of the rally Mária Sándor, the “nurse in black” called for a 5 minute silence, which was observed with reverence for this courageous woman, who was persecuted and lost her job last year for openly pointing out the downright dangerous state of many Hungarian hospitals. She stood alone then, but was cheered loudly on the rostrum on the 13th. This showed the government the resolve and unity of a crowd which intends to make them listen.
Mária SándorThe origins of this movement go back to last year, when the Hermann Ottó High School in Miskolc, issued an open letter to the government, enumerating their complaints over the destruction of democracy in education and the ill effects of the government’s so called “reforms”, which included falling plaster in classrooms, lack of books and even of chalk and paper. It listed 25 demands calling for the return to local democracy in schools, the abolition of the KLIK, the government’s centralised organisation overseeing education, for sensible teaching and learning hours that do not exhaust either children or teachers, reduction in the content of the National Curriculum, for teacher autonomy in the method of delivery, the return of the billions of forints which were syphoned off from education etc., etc. The KLIK, put together on a partisan basis, containing only FIDESZ party hacks, few educationalists and real experts has since become a focus of special hatred by the teaching profession. Not only has it no experts in its ranks, it has become known as a completely amateur outfit that could not organise a single lesson, never mind the whole education system from one or two offices in Budapest. Echoes of Stalinism abound through its bureaucratic inefficiency, centralised bigotry, lack of professionalism and an overuse of dictates from above. No wonder, even totally non-political as well as some FIDESZ members of the teaching profession are totally united with the rest in the call for the instant abolition of this disgraceful organisation.
Viktor Orbán’s FIDESZ government have been treating the teachers the same way as they have all government workers: with disdain, sham consultations, unwillingness to listen, with dictates from above and especially with an iron hand trying to reintroduce the old Teutonic system of learning by rote, recalling facts, against free will, free opinion or thinking by either teachers of their pupils. In other words, it seems to want nothing but an unthinking and obedient workforce that will never challenge its authority.
An unprecedented unity between teachers, their pupils and their parents had started to develop soon after the issue of the open letter. With the clever use of the internet, Twitter and Facebook, the campaign suddenly started to grow exponentially. Soon it had 30,000+ individual supporters and over 500 schools nationally joined them, some of which have very courageously put their names on the petition, including head teachers and governors.
Hungary has haemorrhaged hundreds of thousands of young people who have left the country for a hoped for better life abroad and every year more and more express their desire to leave as soon as possible. The best of the students in both schools and universities are also leaving, as they want nothing more to do with a country in the grip of a right wing government shifting relentlessly further and further to the right, thus lessening young people’s chances in the future.
We demand that the government declares the 2011 Public Education Act only temporary, and starts immediate, meaningful co-ordinating talks with the real stakeholders in education, so a new Public Education Act can be thus created.
We demand that such co-ordinating talks start from the professional basis of education! The last five years have proved that the new direction is no good, and patchwork “improvements” lead nowhere.
We demand that the government budgets a minimum of 6% of GDP for education every year, in order to provide transparent, predictable and stable normative financing for education!
We demand that those well-known problems that make the daily operation of educational establishments impossible, giving rise to untenable conditions for teaching and learning, be immediately dealt with by a change in the legal and ministerial orders!
Unless these are met at once, at least one union has started making preparations for a strike. Given the current mood, it is entirely possible that other unions will join them not only in a supporting role, but actually out on the streets. We must offer solidarity with all fighting people, organisations, unions and other bodies who are fighting for the future of Hungarian youth and call for a one day general strike, which would put on the table not only the demands of the teachers, but those from all other spheres of life. We are all at risk from this government and their system, not only the young people and their future.
No fiddling at the edges of the problem can now produce any improvement in the life of Hungarians, and they are slowly but surely recognising this fact. Standing in front of Parliament in the pouring rain I heard many comments, including those of the speakers on the rostrum, comments that had nothing to do with education. The demands were political, for the end of corruption, for democracy and for a just society. Nobody called it socialism yet, but even a small number of people putting forward the ideas of Marxism under these circumstances would get an echo.
Bernie Sanders’s US presidential campaign prompted opinion polls showing incredible figures of young people standing for socialism. It could not be any different in Hungary today! |
From carafes that chill to glasses that aerate, don't skimp out on how you can transform a "meh" bottle into a "wow" bottle.
To enjoy a bottle of wine, you mainly need three things: a corkscrew, a glass, and, well, a bottle of wine. That's it. But to truly get the most out of what you (or someone else) just spent some money on, there are some amazing gadgets out there that make wine exceptionally better.
The Coravin Model Two Elite sounds like a car name, but it is in fact a beautiful contraption that allows you to drink your wine without popping the cork. It works by piercing the cork with a pouring needle, which is then sealed with Argon gas to keep the wine fresh. It's a seamless way to never waste another bottle by not being able to reseal it.
Another option for keeping your wine from going bad is to get the Vacu Vin. This one removes the cork completely, but comes with bottle stoppers that are resealable with the Vacu Vin vacuum pump that tightly seals your bottle. Wine will keep tasting like it's just been opened for up to a week.
This wine chilling carafe from Rabbit is a white wine-drinker's dream. I love my white wine freezing cold, but hate adding ice and diluting it. This carafe features a stainless steel ice chamber that keeps your wine cold for 90+ minutes at a time, no dilution necessary.
Aerating your wine is an important step to releasing the true flavors of it. This simple-to-use handheld aerator can be used anywhere, and comes with its own carrying case. Turn any good bottle of wine into a great bottle of wine with one step.
If you're a one-glass-at-a-time drinker, check out this glass that will aerate your wine for you. Simply pour your vino into the center reservoir and allow it to trickle out the strategically placed holes and into the drinking portion of the glass. It's like your own indoor water feature, except wine.
And there's no enjoying wine if you can't get the bottle open. A classic corkscrew bottle opener will do the trick, but upgrade to something a little more impressive, like the Oster Electric Wine Opener that takes all the work (but none of the fun) out of popping a bottle. |
class TimeMap {
unordered_map<string, vector<pair<int, string>>> db;
public:
TimeMap() {
}
void set(string key, string value, int timestamp) {
db[key].push_back({timestamp, value});
}
string get(string key, int timestamp) {
auto cmp = [](const pair<int, string>& lhs, const pair<int, string>& rhs) {
return lhs.first < rhs.first;
};
auto it = upper_bound(db[key].begin(), db[key].end(), make_pair(timestamp, ""), cmp);
if (it == db[key].begin()) {
return "";
} else {
it--;
return it->second;
}
}
};
/**
* Your TimeMap object will be instantiated and called as such:
* TimeMap* obj = new TimeMap();
* obj->set(key,value,timestamp);
* string param_2 = obj->get(key,timestamp);
*/
|
High prevalence of subclinical thyroid dysfunction and the relationship between thyrotropin levels and cardiovascular risk factors in residents of the coastal area of China. OBJECTIVES To investigate the prevalence of subclinical thyroid dysfunction and the relationship between thyrotropin levels and cardiovascular risk factors in residents of the coastal area of China. METHODS Atotalof4256individuals(meanage50.51±14.24years; 2079 males, 2177 females,) were enrolled in the present study. Sex, blood pressure, body mass index, waist-to-hip ratio, serum levels of fasting glucose, total cholesterol, high-density lipoprotein cholesterol, low-density lipoprotein cholesterol, triglycerides, uric acid and smoking status were measured. The relationship between thyrotropin levels and cardiovascular risk factors was analyzed. RESULTS The overall prevalence of thyroid dysfunction was 11.07%. The prevalence of subclinical hypothyroidism (6.32%) was higher than that of hyperthyroidism (1.53%). The prevalence of thyroid dysfunction among female subjects was higher than that among male subjects (16.54% versus 5.34%, respectively; P<0.001). Significant differences were detected with respect to body mass index (P=0.026), waist-to-hip ratio (P<0.001), fasting glucose levels (P=0.001), total cholesterol levels (P=0.013), triglyceride levels (P=0.003) and smoking status according to different thyrotropin levels. CONCLUSION The prevalence of thyroid dysfunction was high in residents of China's coastal area. Significant differences were detected with regard to body mass index, waist-to-hip ratio, fasting glucose levels, total cholesterol levels, triglyceride levels and smoking status according to different thyrotropin levels. |
WASHINGTON – Republicans on the House Natural Resources Committee have released a report critical of the process used in determining protections afforded under the Endangered Species Act, asserting that peer reviewers are often motivated by bias and conflicts of interest.
The report, titled “Under the Microscope: An examination of the questionable science and lack of independent peer review in Endangered Species Act listings,” did not include input from committee Democrats or a response from the Obama administration. The GOP study researched the federal government’s peer review process for 13 different endangered species listings made by the U.S. Fish & Wildlife Service (FWS) since July 2013 and found examples of a lack of transparency and consistency.
The agency, according to the report, sometimes employs peer reviewers who authored studies on the species they are reviewing. The GOP staff determined that the peer review process as currently employed by the FWS “relies on a network of scientists who, if nothing else, have a professional and academic interest in the outcome of the ESA listing decisions they are being asked to review.”
“In recruiting peer reviewers, the FWS appears to favor scientists whose views on a species are already well known rather than more independent scientists in other academic or professional fields who would be able to bring a fresh perspective to the science the FWS is citing to support its ESA listing decisions,” it said.
The FWS does not have clear or consistent procedures in place across all regional offices to ensure that potential peer reviewers undergo a screening to identify possible conflicts of interest or impartiality, the report said. The agency furthermore doesn’t consistently disclose information regarding who serves as peer reviewers, the instructions they are given or the substance of their comments.
“The decision of whether or not to list a species under the Endangered Species Act has significant implications for the economy and livelihoods of impacted communities and private landowners,” said Rep. Doc Hastings (R-Wash.), chairman of the House Natural Resources Committee. “As such, these important decisions must be based on sound science that has undergone an independent peer review.”
The report, Hastings said, “raises troubling concerns about the lack of independence of the peer review process and whether many current, upcoming or recently finalized listing decisions...are scientifically sound.”
Hastings expressed particular dismay over inclusion of the White Bluffs bladderpod, which is found in his congressional district. It is a small plant with bright yellow flowers and tiny inflated pods that isn’t edible and doesn't provide any sort of herbal usage. It is, however, rare, apparently growing only along a 17-mile strip in the Columbia River Basin. FWS lists the bladderpod as threatened but wants to change that designation to endangered. Regional farmers would have to deal with the laws and regulations protecting the endangered species.
The committee majority’s report found that of the four peer reviewers who provided comments about the listing, “three had invested significant time to the study of the White Bluffs bladderpod.” One, Dr. Kathryn Beck, identified herself in her comments as “one of the original discoverers of these amazing plants” and expressed her desire to “weigh in if possible.”
The FWS eventually delayed implementation of the endangered designation in face of a lawsuit requiring extra time for comments. A DNA test on the bladderpod submitted during that period showed that the plant was not a unique subspecies and that the DNA was a 100 percent match with several other samples of bladderpods found in two other states, setting the stage for additional peer review.
One of the five individuals chosen for that review of the DNA evidence was Dr. Steven O’Kane who, according to the report, was a co-plaintiff in a lawsuit regarding protections for the White Bluffs bladderpod.
“With hundreds of ESA listings driven by this administration’s closed-door settlements with litigious groups, discovery of any potential bias about how ESA data and science are reviewed casts serious doubt on the credibility of these decisions and provides more evidence that the ESA needs continued oversight and updating,” Hastings said.
The Endangered Species Act of 1973 was designed to protect critically imperiled species from extinction as a "consequence of economic growth and development untempered by adequate concern and conservation.” It is particularly unpopular with farmers and developers who often have to deal with regulations protecting various species. But the U.S. Supreme Court has held that the intent of the law "was to halt and reverse the trend toward species extinction, whatever the cost.”
In 2011, the Obama administration reached a settlement with various conservation groups to study whether more than 250 species need protection under the Endangered Species Act, drawing additional opposition from opponents charging that the law is harming economic development.
Gavin Shire, a spokesman for the Fish and Wildlife Service, defended the agency’s actions, insisting that peer review “is an important part of any scientific endeavor” and that the agency is following a policy developed in 1994 to solicit independent peer review of proposed listing determinations.
“Our peer review process is fully compliant with the information quality guidelines established by OMB (Office of Management and Budget),” he said.
The report is part of an effort by House Republicans to rein in the Endangered Species Act, shifting more of the protection responsibilities to the states. The lower chamber in July adopted legislation requiring the Fish and Wildlife Service to publish its collected information on new endangered species listing and submit annual reports to Congress. The Senate has not yet reciprocated.
Earlier this month Congress approved, and President Obama signed, a $1.1 trillion spending package that included language barring the Department of the Interior from funding efforts to protect either the Gunnison sage-grouse or the greater sage-grouse, which were found to be threatened under the act – meaning the agency believes unless steps are taken the species faces the possibility of extinction. Colorado has notified the agency of its intention to stop the designation from being implemented.
About 5,000 Gunnison sage-grouse breeding birds live in southwestern Colorado and southeastern Utah.
Interior Secretary Sally Jewell said the rider on the spending bill will not affect efforts to develop and implement federal and state plans that conserve sagebrush habitat or to complete the requisite analysis for potential rulemaking.
“It’s disappointing that some members of Congress are more interested in political posturing than finding solutions to conserve the sagebrush landscape and the Western way of life,” Jewell said. “Rather than helping the communities they profess to benefit, these members will only create uncertainty, encourage conflict and undermine the unprecedented progress that is happening throughout the West.” |
1. Field of the Invention
This invention relates to hydromassage apparatus, and, more particularly, to a hydromassage apparatus having an air injector system for introducing air into a flow of water.
2. Description of the Prior Art
The field of hydromassage therapy is not a new field. Rather, the value of combining air and water is well known and accepted. For combining the air and water, there are several different types of air injector systems. The term "air injector" refers to the injecting or combining of the air and water. The following group of patents relate to one type of system in which the air supply pipe is disposed within the water supply pipe. The flow of water over or around the end of the air supply pipe, and outwardly into a pool, bath, or the like, results in the combining of the air and the water.
U.S. Pat. No. 3,496,933 discloses an oral cleaning apparatus using air and water. The water is mixed with a cleaning solution and the water and cleaning solution mixture is in turn subject to air pressure prior to discharge through a nozzle. The air injection tube is disposed in the middle of a water supply conduit and the air injector tubing terminates slightly before, or upstream of, the end of the water discharge nozzle.
U.S. Pat. No. 3,672,359 discloses a pair of substantially coaxial conduits, with the center conduit comprising an air conduit, and the outer conduit comprising a water delivery conduit or tube. The air conduit terminates upstream from the end of the outer conduit. The outer conduit includes a restriction extending upstream from the end of the outer conduit. The outer conduit includes a restriction extending upstream from the discharge end of the conduit and terminating slightly upstream of the end of the air conduit.
U.S. Pat. No. 3,905,358 discloses a nozzle apparatus in which a water conduit includes an air injector conduit disposed within the water conduit. The water conduit includes a nozzle, and the air conduit terminates upstream from the throat of the nozzle. The throat of the nozzle is the narrowest portion of the nozzle, or the portion of the nozzle with the least diameter, and the air conduit terminates upstream from the throat. The nozzle comprises a venturi, with the overall cross-sectional of the nozzle at its greatest diameter substantially less than the overall diameter of the water supply pipe.
U.S. Pat. No. 4,082,091, in general terms, discloses a nozzle apparatus similar to that of the '358 patent. The same general venturi type nozzle, with a water supply pipe leading directly into the nozzle, and an air injector pipe terminating upstream from the throat of the nozzle is disposed in the '091 patent, and the overall systems are substantially identical to each other. The '359 apparatus uses household water pressure, which is normally 50-60 psi. The '358 and '091 apparatus typically require high head pumps, with output pressures of 25-35 psi.
There are numerous patents in which the water supply pipe is disposed within the air supply pipe. Rather than having the air supply pipe disposed within a flow of water, the flow of water is disposed within an outer, air supply pipe. Examples of such an air injector system are illustrated in U.S. Pat. Nos. 2,738,787, 3,288,134, and 3,745,994.
Another type of injector apparatus for combining air and water is disclosed in U.S. Pat. No. 3,587,976, in which the air is injected into a water stream forward of the throat of a nozzle. A similar way of injecting air into a stream of water is shown in U.S. Pat. No. 3,628,529. U.S. Pat. No. 3,810,464 also discloses the air supply conduit downstream from the throat of a water supply nozzle.
The air injector systems discussed above generally result in a bubble bath or effervescent effect of the combination of air and water. The ratio of water to air by volume is restricted to about a 50--50 ratio, or in some cases an even lower ratio of water to air. In the latter case, there will be more air than water in the combination and accordingly an increase in the bubble bath type effect. The design of the particular air injector system, or head, as it may be referred to, is therefore determinative as to the net, or overall, effect of the stream of air and water which flows from the hydrotherapy massage system.
In the apparatus of the present invention, air is generally not entrained in the flow of water. Rather, the air effects a breaking up of the continuous or solid flow of the water to provide a pulsating or rhythmic flow of the water against the user of the apparatus. This is different from the apparatus of the prior art, as exemplified by the patents discussed above. The air injector system or head of the present invention results in a flow of air with the flow of water, as contrasted with the bubbly or effervescent effect of the air bubble and water type air injections of the hydrotherapy massage units of the prior art. The apparatus of the present invention results in a stream of water and a stream of air, as opposed to the prior art apparatus which produce a flow of air and water bubbles.
Generally speaking, the effectiveness of a hydrotherapy massage unit varies with the ratio of the stream of air and water emanating from the unit. However, in addition to the effectiveness of a particular nozzle in an air/water unit, another factor is also of importance, and that is the ability to direct the air/water flow from an air injector head to the desired part of the body. This may involve the ability of moving the head of the unit from one location to another location. A detriment to such arrangement is, of course, having the hydromassage units fixed at a particular location. On the other hand, there are substantial advantages to being able to move the head from one location to another. For the use or placement of such hydromassage units or air injector heads in conjunction with a pool, the ability to move the unit from one location on a pool to another location allows substantial flexibility in the end use of the apparatus. The results to be derived from such portability means that a unit may be moved from one part of a pool, where it may be used to massage a portion of a user's body at a particular location or depth of a pool, to another location at the pool where it will be most advantageously used to provide hydromassage therapy to another part of the body. For example, a person standing in a relatively shallow portion of a pool may direct the air/water stream at a lower part of the user's back. By moving the unit to a deeper portion of the pool, the user may remain in a standing position, but the air/water stream may be directed to the user's back or shoulder area. By moving the unit to the extreme shallow portion of the pool, the user may sit on the steps of the pool and have the flow of air and water directed at a foot, leg, or the like. Obviously, such advantages are not possible with a unit disposed at a fixed location.
U.S. Pat. No. 3,674,020 discloses a portable hydromassage unit usable with a swimming pool. The apparatus is self-contained, except that it requires an electrical connection for its operation. A substantial disadvantage of such unit is the requirement of an electrical conductor between the unit and a source of electrical current adjacent the water. The self-contained unit itself includes an electrical motor for providing power for its own water pump. The unit also includes a water intake to provide the required water supply for the pump. The water intake at the unit comprises a potential hazard due to the suction or intake force of the pump. The present apparatus utilizes a high volume, low head pump, as opposed to the prior art high head, low volume pumps. U.S. Pat. Nos. 3,292,615, 3,961,382, and 4,127,117 disclose portable systems adapted to be disposed on the sides of bathtubs. U.S. Pat. Nos. 3,286,712 and 3,534,730 disclose systems placed adjacent a bathtub with a flexible connection between the unit and a nozzle within the tub. U.S. Pat. No. 3,336,921 discloses a self-contained, water-proofed unit disposed within a tub, with an electric cord extending to a source of electrical current. U.S. Pat. No. 4,149,281 discloses a floating system for a swimming pool. |
<reponame>pfent/Android-MISL-Control<filename>app/src/main/java/de/tum/in/mislcontrol/communication/ASEPConnector.java
package de.tum.in.mislcontrol.communication;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.Pair;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import de.tum.in.mislcontrol.ASEPAdapter;
import de.tum.in.mislcontrol.R;
import de.tum.in.mislcontrol.communication.data.CommandPacket;
import de.tum.in.mislcontrol.communication.data.TelemetryPacket;
import de.tum.in.mislcontrol.controls.IInputController;
import de.tum.in.mislcontrol.math.Vector2D;
/**
* The ASEP connector implementations to send commands and receive status information.
*/
public class ASEPConnector implements IConnector {
private static final String LOG_TAG = "ASEPConnector";
/**
* Defalut connection settings.
*/
private static final String FALLBACK_PORT = "30190",
FALLBACK_SSID = "MISL_ROBOT_WPA",
FALLBACK_IP = "192.168.16.254";
/**
* The WiFi SSID.
*/
public static String WIFI_SSID = FALLBACK_SSID;
/**
* The IP address.
*/
private static InetAddress inetAddress;
/**
* The sending command packet.
*/
private final CommandPacket sending = new CommandPacket();
/**
* The android context.
*/
private final Context context;
/**
* The socket sync-monitor object.
*/
private final Object sockLock = new Object();
/**
* The socket port.
*/
private int port = Integer.parseInt(FALLBACK_PORT);
/**
* The telemetry received callback.
*/
private OnTelemetryReceivedListener receiver;
/**
* The input controller implementation.
*/
private IInputController inputController;
/**
* The UDP socket to send packets to ASEP.
*/
private DatagramSocket sock;
/**
* The thread pool for async request to ASEP.
*/
private ScheduledExecutorService schedulerService;
/**
* Indicates whether we are currently listening to ASEP or not.
*/
private boolean listening = false;
/**
* The recent channel commands.
*/
private short ch1, ch2;
/**
* Creates a ASEP connector instance to send commands and receive status information.
*
* @param context the current context
*/
public ASEPConnector(Context context) {
this.context = context;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
port = Integer.parseInt(prefs.getString(context.getString(R.string.preferenceKey_port),
FALLBACK_PORT));
WIFI_SSID = prefs.getString(context.getString(R.string.preferenceKey_ssid), FALLBACK_SSID);
try {
String address = prefs.getString(context.getString(R.string.preferenceKey_ipaddr),
FALLBACK_IP);
inetAddress = InetAddress.getByName(address);
//explicitly set SO_REUSEADDR, so we don't get EADDRINUSE
sock = new DatagramSocket(null);
sock.setReuseAddress(true);
sock.bind(new InetSocketAddress(port));
sock.setSoTimeout(DEFAULT_TIMEOUT);
} catch (UnknownHostException | SocketException e) {
Log.e(LOG_TAG, "Unexpected Exception while initializing", e);
}
}
@Override
public synchronized void setCommand(short ch1, short ch2) {
this.ch1 = ch1;
this.ch2 = ch2;
}
/**
* Send the movement command to ASEP
*
* @param ch1 Channel 1 command, (left?) wheel speed. Ranges -6 to 6
* @param ch2 Channel 2 command, (right?) wheel speed. Ranges -6 to 6
* @throws IOException When the connection failes
*/
private synchronized void sendCommand(short ch1, short ch2) throws IOException {
sending.setCH1Cmd(ch1);
sending.setCH2Cmd(ch2);
//don't increase sequence count, since the windows GUI also doesn't
//sending.increaseSeqCnt();
sending.calculateChecksum();
DatagramPacket command =
new DatagramPacket(sending.getData(), sending.getLength(), inetAddress, port);
sock.send(command);
}
@Override
public synchronized void start() {
if (listening || sock == null || receiver == null) {
return;
}
listening = true;
// Since ASEP does not reliably respond to our packets, we need asynchronous send/receive
// Send packets in 25ms intervals, so we properly trigger responses, even when ASEP looses
// some of our commands
schedulerService = Executors.newScheduledThreadPool(1);
schedulerService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
if (inputController != null) {
Vector2D direction = inputController.getValue();
Pair<Short, Short> channels = ASEPAdapter.drive(direction.getX(), direction.getY());
setCommand(channels.first, channels.second);
}
sendCommand(ch1, ch2);
} catch (IOException e) {
Log.e(LOG_TAG, "Unexpected Exception while sending", e);
}
}
}, 0, DEFAULT_INTERVAL, TimeUnit.MILLISECONDS);
//Continuously listen for telemetry
new Thread(new Runnable() {
@Override
public void run() {
boolean timedOut = false;
while (listening) {
try {
//Wait for the response packet
TelemetryPacket nextTelemetry = new TelemetryPacket();
DatagramPacket packet =
new DatagramPacket(nextTelemetry.getData(), nextTelemetry.getLength());
synchronized (sockLock) {
if (sock.isClosed())
break;
sock.receive(packet);
}
//ignore sequence count, since ASEP does not update them
timedOut = false;
receiver.onTelemetryReceived(nextTelemetry);
} catch (InterruptedIOException e) {
//this means the DEFAULT_TIMEOUT expired, connection has been lost
if (!timedOut && listening) {
timedOut = true;
receiver.onTelemetryTimedOut();
}
} catch (IOException e) {
Log.e(LOG_TAG, "Unexpected Exception while recieving", e);
}
}
}
}).start();
}
@Override
public synchronized void stop() {
listening = false;
if (schedulerService != null) {
schedulerService.shutdown();
try {
schedulerService.awaitTermination(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Log.w(LOG_TAG, "Stopping the scheduler service timed out.");
}
}
}
@Override
public boolean checkConnection() {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return wifiInfo != null && wifiInfo.getSSID() != null &&
wifiInfo.getSSID().contains(WIFI_SSID);
}
@Override
public void setOnTelemetryReceivedListener(OnTelemetryReceivedListener receiver) {
this.receiver = receiver;
}
@Override
public void setInputController(IInputController controller) {
this.inputController = controller;
}
@Override
public void close() {
stop();
if (sock != null) {
synchronized (sockLock) {
sock.close();
}
}
}
}
|
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.gnu.org/licenses/lgpl-3.0.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.fastjson.parser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.util.ASMUtils;
import com.alibaba.fastjson.util.IOUtils;
import java.math.BigDecimal;
import java.util.*;
//这个类,为了性能优化做了很多特别处理,一切都是为了性能!!!
/**
* @author wenshao[<EMAIL>]
*/
public final class JSONScanner extends JSONLexerBase {
private final String text;
private final int len;
public JSONScanner(String input) {
this(input, JSON.DEFAULT_PARSER_FEATURE);
}
public JSONScanner(String input, int features) {
super(features);
text = input;
len = text.length();
bp = -1;
next();
if (ch == 65279) { // utf-8 bom
next();
}
}
public final char charAt(int index) {
if (index >= len) {
return EOI;
}
return text.charAt(index);
}
public final char next() {
int index = ++bp;
return ch = (index >= this.len ? //
EOI //
: text.charAt(index));
}
public JSONScanner(char[] input, int inputLength) {
this(input, inputLength, JSON.DEFAULT_PARSER_FEATURE);
}
public JSONScanner(char[] input, int inputLength, int features) {
this(new String(input, 0, inputLength), features);
}
protected final void copyTo(int offset, int count, char[] dest) {
text.getChars(offset, offset + count, dest, 0);
}
static boolean charArrayCompare(String src, int offset, char[] dest) {
final int destLen = dest.length;
if (destLen + offset > src.length()) {
return false;
}
for (int i = 0; i < destLen; ++i) {
if (dest[i] != src.charAt(offset + i)) {
return false;
}
}
return true;
}
public final boolean charArrayCompare(char[] chars) {
return charArrayCompare(text, bp, chars);
}
public final int indexOf(char ch, int startIndex) {
return text.indexOf(ch, startIndex);
}
public final String addSymbol(int offset, int len, int hash, final SymbolTable symbolTable) {
return symbolTable.addSymbol(text, offset, len, hash);
}
public byte[] bytesValue() {
if (token == JSONToken.HEX) {
int start = np + 1, len = sp;
if (len % 2 != 0) {
throw new JSONException("illegal state. " + len);
}
byte[] bytes = new byte[len / 2];
for (int i = 0; i < bytes.length; ++i) {
char c0 = text.charAt(start + i * 2);
char c1 = text.charAt(start + i * 2 + 1);
int b0 = c0 - (c0 <= 57 ? 48 : 55);
int b1 = c1 - (c1 <= 57 ? 48 : 55);
bytes[i] = (byte) ((b0 << 4) | b1);
}
return bytes;
}
return IOUtils.decodeBase64(text, np + 1, sp);
}
/**
* The value of a literal token, recorded as a string. For integers, leading 0x and 'l' suffixes are suppressed.
*/
public final String stringVal() {
if (!hasSpecial) {
return this.subString(np + 1, sp);
} else {
return new String(sbuf, 0, sp);
}
}
public final String subString(int offset, int count) {
if (ASMUtils.IS_ANDROID) {
if (count < sbuf.length) {
text.getChars(offset, offset + count, sbuf, 0);
return new String(sbuf, 0, count);
} else {
char[] chars = new char[count];
text.getChars(offset, offset + count, chars, 0);
return new String(chars);
}
} else {
return text.substring(offset, offset + count);
}
}
public final char[] sub_chars(int offset, int count) {
if (ASMUtils.IS_ANDROID && count < sbuf.length) {
text.getChars(offset, offset + count, sbuf, 0);
return sbuf;
} else {
char[] chars = new char[count];
text.getChars(offset, offset + count, chars, 0);
return chars;
}
}
public final String numberString() {
char chLocal = charAt(np + sp - 1);
int sp = this.sp;
if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') {
sp--;
}
return this.subString(np, sp);
}
public final BigDecimal decimalValue() {
char chLocal = charAt(np + sp - 1);
int sp = this.sp;
if (chLocal == 'L' || chLocal == 'S' || chLocal == 'B' || chLocal == 'F' || chLocal == 'D') {
sp--;
}
int offset = np, count = sp;
if (count < sbuf.length) {
text.getChars(offset, offset + count, sbuf, 0);
return new BigDecimal(sbuf, 0, count);
} else {
char[] chars = new char[count];
text.getChars(offset, offset + count, chars, 0);
return new BigDecimal(chars);
}
}
public boolean scanISO8601DateIfMatch() {
return scanISO8601DateIfMatch(true);
}
public boolean scanISO8601DateIfMatch(boolean strict) {
int rest = len - bp;
return scanISO8601DateIfMatch(strict, rest);
}
private boolean scanISO8601DateIfMatch(boolean strict, int rest) {
if (rest < 8) {
return false;
}
char c0 = charAt(bp);
char c1 = charAt(bp + 1);
char c2 = charAt(bp + 2);
char c3 = charAt(bp + 3);
char c4 = charAt(bp + 4);
char c5 = charAt(bp + 5);
char c6 = charAt(bp + 6);
char c7 = charAt(bp + 7);
if ((!strict) && rest > 13) {
char c_r0 = charAt(bp + rest - 1);
char c_r1 = charAt(bp + rest - 2);
if (c0 == '/' && c1 == 'D' && c2 == 'a' && c3 == 't' && c4 == 'e' && c5 == '(' && c_r0 == '/'
&& c_r1 == ')') {
int plusIndex = -1;
for (int i = 6; i < rest; ++i) {
char c = charAt(bp + i);
if (c == '+') {
plusIndex = i;
} else if (c < '0' || c > '9') {
break;
}
}
if (plusIndex == -1) {
return false;
}
int offset = bp + 6;
String numberText = this.subString(offset, bp + plusIndex - offset);
long millis = Long.parseLong(numberText);
calendar = Calendar.getInstance(timeZone, locale);
calendar.setTimeInMillis(millis);
token = JSONToken.LITERAL_ISO8601_DATE;
return true;
}
}
char c10;
if (rest == 8
|| rest == 14
|| (rest == 16 && ((c10 = charAt(bp + 10)) == 'T' || c10 == ' '))
|| (rest == 17 && charAt(bp + 6) != '-')) {
if (strict) {
return false;
}
char y0, y1, y2, y3, M0, M1, d0, d1;
char c8 = charAt(bp + 8);
final boolean c_47 = c4 == '-' && c7 == '-';
final boolean sperate16 = c_47 && rest == 16;
final boolean sperate17 = c_47 && rest == 17;
if (sperate17 || sperate16) {
y0 = c0;
y1 = c1;
y2 = c2;
y3 = c3;
M0 = c5;
M1 = c6;
d0 = c8;
d1 = charAt(bp + 9);
} else if (c4 == '-' && c6 == '-') {
y0 = c0;
y1 = c1;
y2 = c2;
y3 = c3;
M0 = '0';
M1 = c5;
d0 = '0';
d1 = c7;
} else {
y0 = c0;
y1 = c1;
y2 = c2;
y3 = c3;
M0 = c4;
M1 = c5;
d0 = c6;
d1 = c7;
}
if (!checkDate(y0, y1, y2, y3, M0, M1, d0, d1)) {
return false;
}
setCalendar(y0, y1, y2, y3, M0, M1, d0, d1);
int hour, minute, seconds, millis;
if (rest != 8) {
char c9 = charAt(bp + 9);
c10 = charAt(bp + 10);
char c11 = charAt(bp + 11);
char c12 = charAt(bp + 12);
char c13 = charAt(bp + 13);
char h0, h1, m0, m1, s0, s1;
if ((sperate17 && c10 == 'T' && c13 == ':' && charAt(bp + 16) == 'Z')
|| (sperate16 && (c10 == ' ' || c10 == 'T') && c13 == ':')) {
h0 = c11;
h1 = c12;
m0 = charAt(bp + 14);
m1 = charAt(bp + 15);
s0 = '0';
s1 = '0';
} else {
h0 = c8;
h1 = c9;
m0 = c10;
m1 = c11;
s0 = c12;
s1 = c13;
}
if (!checkTime(h0, h1, m0, m1, s0, s1)) {
return false;
}
if (rest == 17 && !sperate17) {
char S0 = charAt(bp + 14);
char S1 = charAt(bp + 15);
char S2 = charAt(bp + 16);
if (S0 < '0' || S0 > '9') {
return false;
}
if (S1 < '0' || S1 > '9') {
return false;
}
if (S2 < '0' || S2 > '9') {
return false;
}
millis = (S0 - '0') * 100 + (S1 - '0') * 10 + (S2 - '0');
} else {
millis = 0;
}
hour = (h0 - '0') * 10 + (h1 - '0');
minute = (m0 - '0') * 10 + (m1 - '0');
seconds = (s0 - '0') * 10 + (s1 - '0');
} else {
hour = 0;
minute = 0;
seconds = 0;
millis = 0;
}
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, seconds);
calendar.set(Calendar.MILLISECOND, millis);
token = JSONToken.LITERAL_ISO8601_DATE;
return true;
}
if (rest < 9) {
return false;
}
char c8 = charAt(bp + 8);
char c9 = charAt(bp + 9);
int date_len = 10;
char y0, y1, y2, y3, M0, M1, d0, d1;
if ((c4 == '-' && c7 == '-') // cn
|| (c4 == '/' && c7 == '/') // tw yyyy/mm/dd
) {
y0 = c0;
y1 = c1;
y2 = c2;
y3 = c3;
M0 = c5;
M1 = c6;
d0 = c8;
d1 = c9;
} else if ((c4 == '-' && c6 == '-') // cn yyyy-m-dd
) {
y0 = c0;
y1 = c1;
y2 = c2;
y3 = c3;
M0 = '0';
M1 = c5;
if (c8 == ' ') {
d0 = '0';
d1 = c7;
date_len = 8;
} else {
d0 = c7;
d1 = c8;
date_len = 9;
}
} else if ((c2 == '.' && c5 == '.') // de dd.mm.yyyy
|| (c2 == '-' && c5 == '-') // in dd-mm-yyyy
) {
d0 = c0;
d1 = c1;
M0 = c3;
M1 = c4;
y0 = c6;
y1 = c7;
y2 = c8;
y3 = c9;
} else if (c8 == 'T') {
y0 = c0;
y1 = c1;
y2 = c2;
y3 = c3;
M0 = c4;
M1 = c5;
d0 = c6;
d1 = c7;
date_len = 8;
} else {
if (c4 == '年' || c4 == '년') {
y0 = c0;
y1 = c1;
y2 = c2;
y3 = c3;
if (c7 == '月' || c7 == '월') {
M0 = c5;
M1 = c6;
if (c9 == '日' || c9 == '일') {
d0 = '0';
d1 = c8;
} else if (charAt(bp + 10) == '日' || charAt(bp + 10) == '일') {
d0 = c8;
d1 = c9;
date_len = 11;
} else {
return false;
}
} else if (c6 == '月' || c6 == '월') {
M0 = '0';
M1 = c5;
if (c8 == '日' || c8 == '일') {
d0 = '0';
d1 = c7;
} else if (c9 == '日' || c9 == '일') {
d0 = c7;
d1 = c8;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
if (!checkDate(y0, y1, y2, y3, M0, M1, d0, d1)) {
return false;
}
setCalendar(y0, y1, y2, y3, M0, M1, d0, d1);
char t = charAt(bp + date_len);
if (t == 'T' && rest == 16 && date_len == 8 && charAt(bp + 15) == 'Z') {
char h0 = charAt(bp + date_len + 1);
char h1 = charAt(bp + date_len + 2);
char m0 = charAt(bp + date_len + 3);
char m1 = charAt(bp + date_len + 4);
char s0 = charAt(bp + date_len + 5);
char s1 = charAt(bp + date_len + 6);
if (!checkTime(h0, h1, m0, m1, s0, s1)) {
return false;
}
setTime(h0, h1, m0, m1, s0, s1);
calendar.set(Calendar.MILLISECOND, 0);
if (calendar.getTimeZone().getRawOffset() != 0) {
String[] timeZoneIDs = TimeZone.getAvailableIDs(0);
if (timeZoneIDs.length > 0) {
TimeZone timeZone = TimeZone.getTimeZone(timeZoneIDs[0]);
calendar.setTimeZone(timeZone);
}
}
token = JSONToken.LITERAL_ISO8601_DATE;
return true;
} else if (t == 'T' || (t == ' ' && !strict)) {
if (rest < date_len + 9) { // "0000-00-00T00:00:00".length()
return false;
}
} else if (t == '"' || t == EOI || t == '日' || t == '일') {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
ch = charAt(bp += date_len);
token = JSONToken.LITERAL_ISO8601_DATE;
return true;
} else if (t == '+' || t == '-') {
if (len == date_len + 6) {
if (charAt(bp + date_len + 3) != ':' //
|| charAt(bp + date_len + 4) != '0' //
|| charAt(bp + date_len + 5) != '0') {
return false;
}
setTime('0', '0', '0', '0', '0', '0');
calendar.set(Calendar.MILLISECOND, 0);
setTimeZone(t, charAt(bp + date_len + 1), charAt(bp + date_len + 2));
return true;
}
return false;
} else {
return false;
}
if (charAt(bp + date_len + 3) != ':') {
return false;
}
if (charAt(bp + date_len + 6) != ':') {
return false;
}
char h0 = charAt(bp + date_len + 1);
char h1 = charAt(bp + date_len + 2);
char m0 = charAt(bp + date_len + 4);
char m1 = charAt(bp + date_len + 5);
char s0 = charAt(bp + date_len + 7);
char s1 = charAt(bp + date_len + 8);
if (!checkTime(h0, h1, m0, m1, s0, s1)) {
return false;
}
setTime(h0, h1, m0, m1, s0, s1);
char dot = charAt(bp + date_len + 9);
int millisLen = -1; // 有可能没有毫秒区域,没有毫秒区域的时候下一个字符位置有可能是'Z'、'+'、'-'
int millis = 0;
if (dot == '.') { // 0000-00-00T00:00:00.000
if (rest < date_len + 11) {
return false;
}
char S0 = charAt(bp + date_len + 10);
if (S0 < '0' || S0 > '9') {
return false;
}
millis = S0 - '0';
millisLen = 1;
if (rest > date_len + 11) {
char S1 = charAt(bp + date_len + 11);
if (S1 >= '0' && S1 <= '9') {
millis = millis * 10 + (S1 - '0');
millisLen = 2;
}
}
if (millisLen == 2) {
char S2 = charAt(bp + date_len + 12);
if (S2 >= '0' && S2 <= '9') {
millis = millis * 10 + (S2 - '0');
millisLen = 3;
}
}
}
calendar.set(Calendar.MILLISECOND, millis);
int timzeZoneLength = 0;
char timeZoneFlag = charAt(bp + date_len + 10 + millisLen);
if (timeZoneFlag == ' ') {
millisLen++;
timeZoneFlag = charAt(bp + date_len + 10 + millisLen);
}
if (timeZoneFlag == '+' || timeZoneFlag == '-') {
char t0 = charAt(bp + date_len + 10 + millisLen + 1);
if (t0 < '0' || t0 > '1') {
return false;
}
char t1 = charAt(bp + date_len + 10 + millisLen + 2);
if (t1 < '0' || t1 > '9') {
return false;
}
char t2 = charAt(bp + date_len + 10 + millisLen + 3);
char t3 = '0', t4 = '0';
if (t2 == ':') { // ThreeLetterISO8601TimeZone
t3 = charAt(bp + date_len + 10 + millisLen + 4);
if (t3 != '0' && t3 != '3') {
return false;
}
t4 = charAt(bp + date_len + 10 + millisLen + 5);
if (t4 != '0') {
return false;
}
timzeZoneLength = 6;
} else if (t2 == '0') { // TwoLetterISO8601TimeZone
t3 = charAt(bp + date_len + 10 + millisLen + 4);
if (t3 != '0' && t3 != '3') {
return false;
}
timzeZoneLength = 5;
} else if (t2 == '3' && charAt(bp + date_len + 10 + millisLen + 4) == '0') {
t3 = '3';
t4 = '0';
timzeZoneLength = 5;
} else if (t2 == '4' && charAt(bp + date_len + 10 + millisLen + 4) == '5') {
t3 = '4';
t4 = '5';
timzeZoneLength = 5;
} else {
timzeZoneLength = 3;
}
setTimeZone(timeZoneFlag, t0, t1, t3, t4);
} else if (timeZoneFlag == 'Z') {// UTC
timzeZoneLength = 1;
if (calendar.getTimeZone().getRawOffset() != 0) {
String[] timeZoneIDs = TimeZone.getAvailableIDs(0);
if (timeZoneIDs.length > 0) {
TimeZone timeZone = TimeZone.getTimeZone(timeZoneIDs[0]);
calendar.setTimeZone(timeZone);
}
}
}
char end = charAt(bp + (date_len + 10 + millisLen + timzeZoneLength));
if (end != EOI && end != '"') {
return false;
}
ch = charAt(bp += (date_len + 10 + millisLen + timzeZoneLength));
token = JSONToken.LITERAL_ISO8601_DATE;
return true;
}
protected void setTime(char h0, char h1, char m0, char m1, char s0, char s1) {
int hour = (h0 - '0') * 10 + (h1 - '0');
int minute = (m0 - '0') * 10 + (m1 - '0');
int seconds = (s0 - '0') * 10 + (s1 - '0');
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, seconds);
}
protected void setTimeZone(char timeZoneFlag, char t0, char t1) {
setTimeZone(timeZoneFlag, t0, t1, '0', '0');
}
protected void setTimeZone(char timeZoneFlag, char t0, char t1, char t3, char t4) {
int timeZoneOffset = ((t0 - '0') * 10 + (t1 - '0')) * 3600 * 1000;
timeZoneOffset += ((t3 - '0') * 10 + (t4 - '0')) * 60 * 1000;
if (timeZoneFlag == '-') {
timeZoneOffset = -timeZoneOffset;
}
if (calendar.getTimeZone().getRawOffset() != timeZoneOffset) {
String[] timeZoneIDs = TimeZone.getAvailableIDs(timeZoneOffset);
if (timeZoneIDs.length > 0) {
TimeZone timeZone = TimeZone.getTimeZone(timeZoneIDs[0]);
calendar.setTimeZone(timeZone);
}
}
}
private boolean checkTime(char h0, char h1, char m0, char m1, char s0, char s1) {
if (h0 == '0') {
if (h1 < '0' || h1 > '9') {
return false;
}
} else if (h0 == '1') {
if (h1 < '0' || h1 > '9') {
return false;
}
} else if (h0 == '2') {
if (h1 < '0' || h1 > '4') {
return false;
}
} else {
return false;
}
if (m0 >= '0' && m0 <= '5') {
if (m1 < '0' || m1 > '9') {
return false;
}
} else if (m0 == '6') {
if (m1 != '0') {
return false;
}
} else {
return false;
}
if (s0 >= '0' && s0 <= '5') {
if (s1 < '0' || s1 > '9') {
return false;
}
} else if (s0 == '6') {
if (s1 != '0') {
return false;
}
} else {
return false;
}
return true;
}
private void setCalendar(char y0, char y1, char y2, char y3, char M0, char M1, char d0, char d1) {
calendar = Calendar.getInstance(timeZone, locale);
int year = (y0 - '0') * 1000 + (y1 - '0') * 100 + (y2 - '0') * 10 + (y3 - '0');
int month = (M0 - '0') * 10 + (M1 - '0') - 1;
int day = (d0 - '0') * 10 + (d1 - '0');
// calendar.set(year, month, day);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
}
static boolean checkDate(char y0, char y1, char y2, char y3, char M0, char M1, int d0, int d1) {
if (y0 < '0' || y0 > '9') {
return false;
}
if (y1 < '0' || y1 > '9') {
return false;
}
if (y2 < '0' || y2 > '9') {
return false;
}
if (y3 < '0' || y3 > '9') {
return false;
}
if (M0 == '0') {
if (M1 < '1' || M1 > '9') {
return false;
}
} else if (M0 == '1') {
if (M1 != '0' && M1 != '1' && M1 != '2') {
return false;
}
} else {
return false;
}
if (d0 == '0') {
if (d1 < '1' || d1 > '9') {
return false;
}
} else if (d0 == '1' || d0 == '2') {
if (d1 < '0' || d1 > '9') {
return false;
}
} else if (d0 == '3') {
if (d1 != '0' && d1 != '1') {
return false;
}
} else {
return false;
}
return true;
}
@Override
public boolean isEOF() {
return bp == len || ch == EOI && bp + 1 == len;
}
public int scanFieldInt(char[] fieldName) {
matchStat = UNKNOWN;
int startPos = this.bp;
char startChar = this.ch;
if (!charArrayCompare(text, bp, fieldName)) {
matchStat = NOT_MATCH_NAME;
return 0;
}
int index = bp + fieldName.length;
char ch = charAt(index++);
final boolean quote = ch == '"';
if (quote) {
ch = charAt(index++);
}
final boolean negative = ch == '-';
if (negative) {
ch = charAt(index++);
}
int value;
if (ch >= '0' && ch <= '9') {
value = ch - '0';
for (; ; ) {
ch = charAt(index++);
if (ch >= '0' && ch <= '9') {
int value_10 = value * 10;
if (value_10 < value) {
matchStat = NOT_MATCH;
return 0;
}
value = value_10 + (ch - '0');
} else if (ch == '.') {
matchStat = NOT_MATCH;
return 0;
} else {
break;
}
}
if (value < 0) {
matchStat = NOT_MATCH;
return 0;
}
if (quote) {
if (ch != '"') {
matchStat = NOT_MATCH;
return 0;
} else {
ch = charAt(index++);
}
}
for (; ; ) {
if (ch == ',' || ch == '}') {
bp = index - 1;
break;
} else if (isWhitespace(ch)) {
ch = charAt(index++);
continue;
} else {
matchStat = NOT_MATCH;
return 0;
}
}
} else {
matchStat = NOT_MATCH;
return 0;
}
if (ch == ',') {
this.ch = charAt(++bp);
matchStat = VALUE;
token = JSONToken.COMMA;
return negative ? -value : value;
}
if (ch == '}') {
bp = index - 1;
ch = charAt(++bp);
for (; ; ) {
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = charAt(++bp);
break;
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = charAt(++bp);
break;
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = charAt(++bp);
break;
} else if (ch == EOI) {
token = JSONToken.EOF;
break;
} else if (isWhitespace(ch)) {
ch = charAt(++bp);
continue;
} else {
this.bp = startPos;
this.ch = startChar;
matchStat = NOT_MATCH;
return 0;
}
}
matchStat = END;
}
return negative ? -value : value;
}
public String scanFieldString(char[] fieldName) {
matchStat = UNKNOWN;
int startPos = this.bp;
char startChar = this.ch;
for (; ; ) {
if (!charArrayCompare(text, bp, fieldName)) {
if (isWhitespace(ch)) {
next();
continue;
}
matchStat = NOT_MATCH_NAME;
return stringDefaultValue();
} else {
break;
}
}
int index = bp + fieldName.length;
char ch = charAt(index++);
if (ch != '"') {
matchStat = NOT_MATCH;
return stringDefaultValue();
}
final String strVal;
{
int startIndex = index;
int endIndex = indexOf('"', startIndex);
if (endIndex == -1) {
throw new JSONException("unclosed str");
}
String stringVal = subString(startIndex, endIndex - startIndex);
if (stringVal.indexOf('\\') != -1) {
for (; ; ) {
int slashCount = 0;
for (int i = endIndex - 1; i >= 0; --i) {
if (charAt(i) == '\\') {
slashCount++;
} else {
break;
}
}
if (slashCount % 2 == 0) {
break;
}
endIndex = indexOf('"', endIndex + 1);
}
int chars_len = endIndex - (bp + fieldName.length + 1);
char[] chars = sub_chars(bp + fieldName.length + 1, chars_len);
stringVal = readString(chars, chars_len);
}
ch = charAt(endIndex + 1);
for (; ; ) {
if (ch == ',' || ch == '}') {
bp = endIndex + 1;
this.ch = ch;
strVal = stringVal;
break;
} else if (isWhitespace(ch)) {
endIndex++;
ch = charAt(endIndex + 1);
} else {
matchStat = NOT_MATCH;
return stringDefaultValue();
}
}
}
if (ch == ',') {
this.ch = charAt(++bp);
matchStat = VALUE;
return strVal;
} else {
//condition ch == '}' is always 'true'
ch = charAt(++bp);
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = charAt(++bp);
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = charAt(++bp);
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = charAt(++bp);
} else if (ch == EOI) {
token = JSONToken.EOF;
} else {
this.bp = startPos;
this.ch = startChar;
matchStat = NOT_MATCH;
return stringDefaultValue();
}
matchStat = END;
}
return strVal;
}
public Date scanFieldDate(char[] fieldName) {
matchStat = UNKNOWN;
int startPos = this.bp;
char startChar = this.ch;
if (!charArrayCompare(text, bp, fieldName)) {
matchStat = NOT_MATCH_NAME;
return null;
}
int index = bp + fieldName.length;
char ch = charAt(index++);
final Date dateVal;
if (ch == '"') {
int startIndex = index;
int endIndex = indexOf('"', startIndex);
if (endIndex == -1) {
throw new JSONException("unclosed str");
}
int rest = endIndex - startIndex;
bp = index;
if (scanISO8601DateIfMatch(false, rest)) {
dateVal = calendar.getTime();
} else {
bp = startPos;
matchStat = NOT_MATCH;
return null;
}
ch = charAt(endIndex + 1);
bp = startPos;
for (; ; ) {
if (ch == ',' || ch == '}') {
bp = endIndex + 1;
this.ch = ch;
break;
} else if (isWhitespace(ch)) {
endIndex++;
ch = charAt(endIndex + 1);
} else {
matchStat = NOT_MATCH;
return null;
}
}
} else if (ch == '-' || (ch >= '0' && ch <= '9')) {
long millis = 0;
boolean negative = false;
if (ch == '-') {
ch = charAt(index++);
negative = true;
}
if (ch >= '0' && ch <= '9') {
millis = ch - '0';
for (; ; ) {
ch = charAt(index++);
if (ch >= '0' && ch <= '9') {
millis = millis * 10 + (ch - '0');
} else {
if (ch == ',' || ch == '}') {
bp = index - 1;
}
break;
}
}
}
if (millis < 0) {
matchStat = NOT_MATCH;
return null;
}
if (negative) {
millis = -millis;
}
dateVal = new Date(millis);
} else {
matchStat = NOT_MATCH;
return null;
}
if (ch == ',') {
this.ch = charAt(++bp);
matchStat = VALUE;
token = JSONToken.COMMA;
return dateVal;
} else {
//condition ch == '}' is always 'true'
ch = charAt(++bp);
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = charAt(++bp);
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = charAt(++bp);
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = charAt(++bp);
} else if (ch == EOI) {
token = JSONToken.EOF;
} else {
this.bp = startPos;
this.ch = startChar;
matchStat = NOT_MATCH;
return null;
}
matchStat = END;
}
return dateVal;
}
public long scanFieldSymbol(char[] fieldName) {
matchStat = UNKNOWN;
if (!charArrayCompare(text, bp, fieldName)) {
matchStat = NOT_MATCH_NAME;
return 0;
}
int index = bp + fieldName.length;
char ch = charAt(index++);
if (ch != '"') {
matchStat = NOT_MATCH;
return 0;
}
long hash = 0xcbf29ce484222325L;
for (; ; ) {
ch = charAt(index++);
if (ch == '\"') {
bp = index;
this.ch = ch = charAt(bp);
break;
} else if (index > len) {
matchStat = NOT_MATCH;
return 0;
}
hash ^= ch;
hash *= 0x100000001b3L;
}
for (; ; ) {
if (ch == ',') {
this.ch = charAt(++bp);
matchStat = VALUE;
return hash;
} else if (ch == '}') {
next();
skipWhitespace();
ch = getCurrent();
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = charAt(++bp);
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = charAt(++bp);
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = charAt(++bp);
} else if (ch == EOI) {
token = JSONToken.EOF;
} else {
matchStat = NOT_MATCH;
return 0;
}
matchStat = END;
break;
} else if (isWhitespace(ch)) {
ch = charAt(++bp);
continue;
} else {
matchStat = NOT_MATCH;
return 0;
}
}
return hash;
}
public Collection<String> newCollectionByType(Class<?> type) {
if (type.isAssignableFrom(HashSet.class)) {
HashSet<String> list = new HashSet<String>();
return list;
} else if (type.isAssignableFrom(ArrayList.class)) {
ArrayList<String> list2 = new ArrayList<String>();
return list2;
} else {
try {
Collection<String> list = (Collection<String>) type.newInstance();
return list;
} catch (Exception e) {
throw new JSONException(e.getMessage(), e);
}
}
}
@SuppressWarnings("unchecked")
public Collection<String> scanFieldStringArray(char[] fieldName, Class<?> type) {
matchStat = UNKNOWN;
while (ch == '\n' || ch == ' ') {
int index = ++bp;
ch = (index >= this.len ? //
EOI //
: text.charAt(index));
}
if (!charArrayCompare(text, bp, fieldName)) {
matchStat = NOT_MATCH_NAME;
return null;
}
Collection<String> list = newCollectionByType(type);
// if (type.isAssignableFrom(HashSet.class)) {
// list = new HashSet<String>();
// } else if (type.isAssignableFrom(ArrayList.class)) {
// list = new ArrayList<String>();
// } else {
// try {
// list = (Collection<String>) type.newInstance();
// } catch (Exception e) {
// throw new JSONException(e.getMessage(), e);
// }
// }
int startPos = this.bp;
char startChar = this.ch;
int index = bp + fieldName.length;
char ch = charAt(index++);
if (ch == '[') {
ch = charAt(index++);
for (; ; ) {
if (ch == '"') {
int startIndex = index;
int endIndex = indexOf('"', startIndex);
if (endIndex == -1) {
throw new JSONException("unclosed str");
}
String stringVal = subString(startIndex, endIndex - startIndex);
if (stringVal.indexOf('\\') != -1) {
for (; ; ) {
int slashCount = 0;
for (int i = endIndex - 1; i >= 0; --i) {
if (charAt(i) == '\\') {
slashCount++;
} else {
break;
}
}
if (slashCount % 2 == 0) {
break;
}
endIndex = indexOf('"', endIndex + 1);
}
int chars_len = endIndex - startIndex;
char[] chars = sub_chars(startIndex, chars_len);
stringVal = readString(chars, chars_len);
}
index = endIndex + 1;
ch = charAt(index++);
list.add(stringVal);
} else if (ch == 'n' && text.startsWith("ull", index)) {
index += 3;
ch = charAt(index++);
list.add(null);
} else if (ch == ']' && list.size() == 0) {
ch = charAt(index++);
break;
} else {
matchStat = NOT_MATCH;
return null;
}
if (ch == ',') {
ch = charAt(index++);
continue;
}
if (ch == ']') {
ch = charAt(index++);
while (isWhitespace(ch)) {
ch = charAt(index++);
}
break;
}
matchStat = NOT_MATCH;
return null;
}
} else if (text.startsWith("ull", index)) {
index += 3;
ch = charAt(index++);
list = null;
} else {
matchStat = NOT_MATCH;
return null;
}
bp = index;
if (ch == ',') {
this.ch = charAt(bp);
matchStat = VALUE;
return list;
} else if (ch == '}') {
ch = charAt(bp);
for (; ; ) {
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = charAt(++bp);
break;
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = charAt(++bp);
break;
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = charAt(++bp);
break;
} else if (ch == EOI) {
token = JSONToken.EOF;
this.ch = ch;
break;
} else {
boolean space = false;
while (isWhitespace(ch)) {
ch = charAt(index++);
bp = index;
space = true;
}
if (space) {
continue;
}
matchStat = NOT_MATCH;
return null;
}
}
matchStat = END;
} else {
this.ch = startChar;
bp = startPos;
matchStat = NOT_MATCH;
return null;
}
return list;
}
public long scanFieldLong(char[] fieldName) {
matchStat = UNKNOWN;
int startPos = this.bp;
char startChar = this.ch;
if (!charArrayCompare(text, bp, fieldName)) {
matchStat = NOT_MATCH_NAME;
return 0;
}
int index = bp + fieldName.length;
char ch = charAt(index++);
final boolean quote = ch == '"';
if (quote) {
ch = charAt(index++);
}
boolean negative = false;
if (ch == '-') {
ch = charAt(index++);
negative = true;
}
long value;
if (ch >= '0' && ch <= '9') {
value = ch - '0';
for (; ; ) {
ch = charAt(index++);
if (ch >= '0' && ch <= '9') {
value = value * 10 + (ch - '0');
} else if (ch == '.') {
matchStat = NOT_MATCH;
return 0;
} else {
if (quote) {
if (ch != '"') {
matchStat = NOT_MATCH;
return 0;
} else {
ch = charAt(index++);
}
}
if (ch == ',' || ch == '}') {
bp = index - 1;
}
break;
}
}
boolean valid = value >= 0 || (value == -9223372036854775808L && negative);
if (!valid) {
this.bp = startPos;
this.ch = startChar;
matchStat = NOT_MATCH;
return 0;
}
} else {
this.bp = startPos;
this.ch = startChar;
matchStat = NOT_MATCH;
return 0;
}
for (; ; ) {
if (ch == ',') {
this.ch = charAt(++bp);
matchStat = VALUE;
token = JSONToken.COMMA;
return negative ? -value : value;
} else if (ch == '}') {
ch = charAt(++bp);
for (; ; ) {
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = charAt(++bp);
break;
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = charAt(++bp);
break;
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = charAt(++bp);
break;
} else if (ch == EOI) {
token = JSONToken.EOF;
break;
} else if (isWhitespace(ch)) {
ch = charAt(++bp);
} else {
this.bp = startPos;
this.ch = startChar;
matchStat = NOT_MATCH;
return 0;
}
}
matchStat = END;
break;
} else if (isWhitespace(ch)) {
bp = index;
ch = charAt(index++);
continue;
} else {
matchStat = NOT_MATCH;
return 0;
}
}
return negative ? -value : value;
}
public boolean scanFieldBoolean(char[] fieldName) {
matchStat = UNKNOWN;
if (!charArrayCompare(text, bp, fieldName)) {
matchStat = NOT_MATCH_NAME;
return false;
}
int startPos = bp;
int index = bp + fieldName.length;
char ch = charAt(index++);
final boolean quote = ch == '"';
if (quote) {
ch = charAt(index++);
}
boolean value;
if (ch == 't') {
if (charAt(index++) != 'r') {
matchStat = NOT_MATCH;
return false;
}
if (charAt(index++) != 'u') {
matchStat = NOT_MATCH;
return false;
}
if (charAt(index++) != 'e') {
matchStat = NOT_MATCH;
return false;
}
if (quote && charAt(index++) != '"') {
matchStat = NOT_MATCH;
return false;
}
bp = index;
ch = charAt(bp);
value = true;
} else if (ch == 'f') {
if (charAt(index++) != 'a') {
matchStat = NOT_MATCH;
return false;
}
if (charAt(index++) != 'l') {
matchStat = NOT_MATCH;
return false;
}
if (charAt(index++) != 's') {
matchStat = NOT_MATCH;
return false;
}
if (charAt(index++) != 'e') {
matchStat = NOT_MATCH;
return false;
}
if (quote && charAt(index++) != '"') {
matchStat = NOT_MATCH;
return false;
}
bp = index;
ch = charAt(bp);
value = false;
} else if (ch == '1') {
if (quote && charAt(index++) != '"') {
matchStat = NOT_MATCH;
return false;
}
bp = index;
ch = charAt(bp);
value = true;
} else if (ch == '0') {
if (quote && charAt(index++) != '"') {
matchStat = NOT_MATCH;
return false;
}
bp = index;
ch = charAt(bp);
value = false;
} else {
matchStat = NOT_MATCH;
return false;
}
for (; ; ) {
if (ch == ',') {
this.ch = charAt(++bp);
matchStat = VALUE;
token = JSONToken.COMMA;
break;
} else if (ch == '}') {
ch = charAt(++bp);
for (; ; ) {
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = charAt(++bp);
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = charAt(++bp);
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = charAt(++bp);
} else if (ch == EOI) {
token = JSONToken.EOF;
} else if (isWhitespace(ch)) {
ch = charAt(++bp);
continue;
} else {
matchStat = NOT_MATCH;
return false;
}
break;
}
matchStat = END;
break;
} else if (isWhitespace(ch)) {
ch = charAt(++bp);
} else {
bp = startPos;
ch = charAt(bp);
matchStat = NOT_MATCH;
return false;
}
}
return value;
}
public final int scanInt(char expectNext) {
matchStat = UNKNOWN;
final int mark = bp;
int offset = bp;
char chLocal = charAt(offset++);
while (isWhitespace(chLocal)) {
chLocal = charAt(offset++);
}
final boolean quote = chLocal == '"';
if (quote) {
chLocal = charAt(offset++);
}
final boolean negative = chLocal == '-';
if (negative) {
chLocal = charAt(offset++);
}
int value;
if (chLocal >= '0' && chLocal <= '9') {
value = chLocal - '0';
for (; ; ) {
chLocal = charAt(offset++);
if (chLocal >= '0' && chLocal <= '9') {
int value_10 = value * 10;
if (value_10 < value) {
throw new JSONException("parseInt error : "
+ subString(mark, offset - 1));
}
value = value_10 + (chLocal - '0');
} else if (chLocal == '.') {
matchStat = NOT_MATCH;
return 0;
} else {
if (quote) {
if (chLocal != '"') {
matchStat = NOT_MATCH;
return 0;
} else {
chLocal = charAt(offset++);
}
}
break;
}
}
if (value < 0) {
matchStat = NOT_MATCH;
return 0;
}
} else if (chLocal == 'n'
&& charAt(offset++) == 'u'
&& charAt(offset++) == 'l'
&& charAt(offset++) == 'l') {
matchStat = VALUE_NULL;
value = 0;
chLocal = charAt(offset++);
if (quote && chLocal == '"') {
chLocal = charAt(offset++);
}
for (; ; ) {
if (chLocal == ',') {
bp = offset;
this.ch = charAt(bp);
matchStat = VALUE_NULL;
token = JSONToken.COMMA;
return value;
} else if (chLocal == ']') {
bp = offset;
this.ch = charAt(bp);
matchStat = VALUE_NULL;
token = JSONToken.RBRACKET;
return value;
} else if (isWhitespace(chLocal)) {
chLocal = charAt(offset++);
continue;
}
break;
}
matchStat = NOT_MATCH;
return 0;
} else {
matchStat = NOT_MATCH;
return 0;
}
for (; ; ) {
if (chLocal == expectNext) {
bp = offset;
this.ch = charAt(bp);
matchStat = VALUE;
token = JSONToken.COMMA;
return negative ? -value : value;
} else {
if (isWhitespace(chLocal)) {
chLocal = charAt(offset++);
continue;
}
matchStat = NOT_MATCH;
return negative ? -value : value;
}
}
}
public double scanDouble(char seperator) {
matchStat = UNKNOWN;
int offset = bp;
char chLocal = charAt(offset++);
final boolean quote = chLocal == '"';
if (quote) {
chLocal = charAt(offset++);
}
boolean negative = chLocal == '-';
if (negative) {
chLocal = charAt(offset++);
}
double value;
if (chLocal >= '0' && chLocal <= '9') {
long intVal = chLocal - '0';
for (; ; ) {
chLocal = charAt(offset++);
if (chLocal >= '0' && chLocal <= '9') {
intVal = intVal * 10 + (chLocal - '0');
continue;
} else {
break;
}
}
long power = 1;
boolean small = (chLocal == '.');
if (small) {
chLocal = charAt(offset++);
if (chLocal >= '0' && chLocal <= '9') {
intVal = intVal * 10 + (chLocal - '0');
power = 10;
for (; ; ) {
chLocal = charAt(offset++);
if (chLocal >= '0' && chLocal <= '9') {
intVal = intVal * 10 + (chLocal - '0');
power *= 10;
continue;
} else {
break;
}
}
} else {
matchStat = NOT_MATCH;
return 0;
}
}
boolean exp = chLocal == 'e' || chLocal == 'E';
if (exp) {
chLocal = charAt(offset++);
if (chLocal == '+' || chLocal == '-') {
chLocal = charAt(offset++);
}
for (; ; ) {
if (chLocal >= '0' && chLocal <= '9') {
chLocal = charAt(offset++);
} else {
break;
}
}
}
int start, count;
if (quote) {
if (chLocal != '"') {
matchStat = NOT_MATCH;
return 0;
} else {
chLocal = charAt(offset++);
}
start = bp + 1;
count = offset - start - 2;
} else {
start = bp;
count = offset - start - 1;
}
if (!exp && count < 18) {
value = ((double) intVal) / power;
if (negative) {
value = -value;
}
} else {
String text = this.subString(start, count);
value = Double.parseDouble(text);
}
} else if (chLocal == 'n'
&& charAt(offset++) == 'u'
&& charAt(offset++) == 'l'
&& charAt(offset++) == 'l') {
matchStat = VALUE_NULL;
value = 0;
chLocal = charAt(offset++);
if (quote && chLocal == '"') {
chLocal = charAt(offset++);
}
for (; ; ) {
if (chLocal == ',') {
bp = offset;
this.ch = charAt(bp);
matchStat = VALUE_NULL;
token = JSONToken.COMMA;
return value;
} else if (chLocal == ']') {
bp = offset;
this.ch = charAt(bp);
matchStat = VALUE_NULL;
token = JSONToken.RBRACKET;
return value;
} else if (isWhitespace(chLocal)) {
chLocal = charAt(offset++);
continue;
}
break;
}
matchStat = NOT_MATCH;
return 0;
} else {
matchStat = NOT_MATCH;
return 0;
}
if (chLocal == seperator) {
bp = offset;
this.ch = this.charAt(bp);
matchStat = VALUE;
token = JSONToken.COMMA;
return value;
} else {
matchStat = NOT_MATCH;
return value;
}
}
public long scanLong(char seperator) {
matchStat = UNKNOWN;
int offset = bp;
char chLocal = charAt(offset++);
final boolean quote = chLocal == '"';
if (quote) {
chLocal = charAt(offset++);
}
final boolean negative = chLocal == '-';
if (negative) {
chLocal = charAt(offset++);
}
long value;
if (chLocal >= '0' && chLocal <= '9') {
value = chLocal - '0';
for (; ; ) {
chLocal = charAt(offset++);
if (chLocal >= '0' && chLocal <= '9') {
value = value * 10 + (chLocal - '0');
} else if (chLocal == '.') {
matchStat = NOT_MATCH;
return 0;
} else {
if (quote) {
if (chLocal != '"') {
matchStat = NOT_MATCH;
return 0;
} else {
chLocal = charAt(offset++);
}
}
break;
}
}
boolean valid = value >= 0 || (value == -9223372036854775808L && negative);
if (!valid) {
matchStat = NOT_MATCH;
return 0;
}
} else if (chLocal == 'n'
&& charAt(offset++) == 'u'
&& charAt(offset++) == 'l'
&& charAt(offset++) == 'l') {
matchStat = VALUE_NULL;
value = 0;
chLocal = charAt(offset++);
if (quote && chLocal == '"') {
chLocal = charAt(offset++);
}
for (; ; ) {
if (chLocal == ',') {
bp = offset;
this.ch = charAt(bp);
matchStat = VALUE_NULL;
token = JSONToken.COMMA;
return value;
} else if (chLocal == ']') {
bp = offset;
this.ch = charAt(bp);
matchStat = VALUE_NULL;
token = JSONToken.RBRACKET;
return value;
} else if (isWhitespace(chLocal)) {
chLocal = charAt(offset++);
continue;
}
break;
}
matchStat = NOT_MATCH;
return 0;
} else {
matchStat = NOT_MATCH;
return 0;
}
for (; ; ) {
if (chLocal == seperator) {
bp = offset;
this.ch = charAt(bp);
matchStat = VALUE;
token = JSONToken.COMMA;
return negative ? -value : value;
} else {
if (isWhitespace(chLocal)) {
chLocal = charAt(offset++);
continue;
}
matchStat = NOT_MATCH;
return value;
}
}
}
public Date scanDate(char seperator) {
matchStat = UNKNOWN;
int startPos = this.bp;
char startChar = this.ch;
int index = bp;
char ch = charAt(index++);
final Date dateVal;
if (ch == '"') {
int startIndex = index;
int endIndex = indexOf('"', startIndex);
if (endIndex == -1) {
throw new JSONException("unclosed str");
}
int rest = endIndex - startIndex;
bp = index;
if (scanISO8601DateIfMatch(false, rest)) {
dateVal = calendar.getTime();
} else {
bp = startPos;
this.ch = startChar;
matchStat = NOT_MATCH;
return null;
}
ch = charAt(endIndex + 1);
bp = startPos;
for (; ; ) {
if (ch == ',' || ch == ']') {
bp = endIndex + 1;
this.ch = ch;
break;
} else if (isWhitespace(ch)) {
endIndex++;
ch = charAt(endIndex + 1);
} else {
this.bp = startPos;
this.ch = startChar;
matchStat = NOT_MATCH;
return null;
}
}
} else if (ch == '-' || (ch >= '0' && ch <= '9')) {
long millis = 0;
boolean negative = false;
if (ch == '-') {
ch = charAt(index++);
negative = true;
}
if (ch >= '0' && ch <= '9') {
millis = ch - '0';
for (; ; ) {
ch = charAt(index++);
if (ch >= '0' && ch <= '9') {
millis = millis * 10 + (ch - '0');
} else {
if (ch == ',' || ch == ']') {
bp = index - 1;
}
break;
}
}
}
if (millis < 0) {
this.bp = startPos;
this.ch = startChar;
matchStat = NOT_MATCH;
return null;
}
if (negative) {
millis = -millis;
}
dateVal = new Date(millis);
} else if (ch == 'n'
&& charAt(index++) == 'u'
&& charAt(index++) == 'l'
&& charAt(index++) == 'l') {
dateVal = null;
ch = charAt(index);
bp = index;
} else {
this.bp = startPos;
this.ch = startChar;
matchStat = NOT_MATCH;
return null;
}
if (ch == ',') {
this.ch = charAt(++bp);
matchStat = VALUE;
return dateVal;
} else {
//condition ch == '}' is always 'true'
ch = charAt(++bp);
if (ch == ',') {
token = JSONToken.COMMA;
this.ch = charAt(++bp);
} else if (ch == ']') {
token = JSONToken.RBRACKET;
this.ch = charAt(++bp);
} else if (ch == '}') {
token = JSONToken.RBRACE;
this.ch = charAt(++bp);
} else if (ch == EOI) {
this.ch = EOI;
token = JSONToken.EOF;
} else {
this.bp = startPos;
this.ch = startChar;
matchStat = NOT_MATCH;
return null;
}
matchStat = END;
}
return dateVal;
}
protected final void arrayCopy(int srcPos, char[] dest, int destPos, int length) {
text.getChars(srcPos, srcPos + length, dest, destPos);
}
public String info() {
StringBuilder buf = new StringBuilder();
// buf.append("pos ").append(bp);
// return "pos " + bp //
// + ", json : " //
// + (text.length() < 65536 //
// ? text //
// : text.substring(0, 65536));
int line = 1;
int column = 1;
for (int i = 0; i < bp; ++i, column++) {
char ch = text.charAt(i);
if (ch == '\n') {
column = 1;
line++;
}
}
buf.append("pos ").append(bp)
.append(", line ").append(line)
.append(", column ").append(column);
if (text.length() < 65535) {
buf.append(text);
} else {
buf.append(text.substring(0, 65535));
}
return buf.toString();
}
// for hsf support
public String[] scanFieldStringArray(char[] fieldName, int argTypesCount, SymbolTable typeSymbolTable) {
int startPos = bp;
char starChar = ch;
while (isWhitespace(ch)) {
next();
}
int offset;
char ch;
if (fieldName != null) {
matchStat = UNKNOWN;
if (!charArrayCompare(fieldName)) {
matchStat = NOT_MATCH_NAME;
return null;
}
offset = bp + fieldName.length;
ch = text.charAt(offset++);
while (isWhitespace(ch)) {
ch = text.charAt(offset++);
}
if (ch == ':') {
ch = text.charAt(offset++);
} else {
matchStat = NOT_MATCH;
return null;
}
while (isWhitespace(ch)) {
ch = text.charAt(offset++);
}
} else {
offset = bp + 1;
ch = this.ch;
}
if (ch == '[') {
bp = offset;
this.ch = text.charAt(bp);
} else if (ch == 'n' && text.startsWith("ull", bp + 1)) {
bp += 4;
this.ch = text.charAt(bp);
return null;
} else {
matchStat = NOT_MATCH;
return null;
}
String[] types = argTypesCount >= 0 ? new String[argTypesCount] : new String[4];
int typeIndex = 0;
for (; ; ) {
while (isWhitespace(this.ch)) {
next();
}
if (this.ch != '\"') {
this.bp = startPos;
this.ch = starChar;
matchStat = NOT_MATCH;
return null;
}
String type = scanSymbol(typeSymbolTable, '"');
if (typeIndex == types.length) {
int newCapacity = types.length + (types.length >> 1) + 1;
String[] array = new String[newCapacity];
System.arraycopy(types, 0, array, 0, types.length);
types = array;
}
types[typeIndex++] = type;
while (isWhitespace(this.ch)) {
next();
}
if (this.ch == ',') {
next();
continue;
}
break;
}
if (types.length != typeIndex) {
String[] array = new String[typeIndex];
System.arraycopy(types, 0, array, 0, typeIndex);
types = array;
}
while (isWhitespace(this.ch)) {
next();
}
if (this.ch == ']') {
next();
} else {
this.bp = startPos;
this.ch = starChar;
matchStat = NOT_MATCH;
return null;
}
return types;
}
public boolean matchField2(char[] fieldName) {
while (isWhitespace(ch)) {
next();
}
if (!charArrayCompare(fieldName)) {
matchStat = NOT_MATCH_NAME;
return false;
}
int offset = bp + fieldName.length;
char ch = text.charAt(offset++);
while (isWhitespace(ch)) {
ch = text.charAt(offset++);
}
if (ch == ':') {
this.bp = offset;
this.ch = charAt(bp);
return true;
} else {
matchStat = NOT_MATCH_NAME;
return false;
}
}
public final void skipObject() {
skipObject(false);
}
public final void skipObject(boolean valid) {
boolean quote = false;
int braceCnt = 0;
int i = bp;
for (; i < text.length(); ++i) {
final char ch = text.charAt(i);
if (ch == '\\') {
if (i < len - 1) {
++i;
continue;
} else {
this.ch = ch;
this.bp = i;
throw new JSONException("illegal str, " + info());
}
} else if (ch == '"') {
quote = !quote;
} else if (ch == '{') {
if (quote) {
continue;
}
braceCnt++;
} else if (ch == '}') {
if (quote) {
continue;
} else {
braceCnt--;
}
if (braceCnt == -1) {
this.bp = i + 1;
if (this.bp == text.length()) {
this.ch = EOI;
this.token = JSONToken.EOF;
return;
}
this.ch = text.charAt(this.bp);
if (this.ch == ',') {
token = JSONToken.COMMA;
int index = ++bp;
this.ch = (index >= text.length() //
? EOI //
: text.charAt(index));
return;
} else if (this.ch == '}') {
token = JSONToken.RBRACE;
next();
return;
} else if (this.ch == ']') {
token = JSONToken.RBRACKET;
next();
return;
} else {
nextToken(JSONToken.COMMA);
}
return;
}
}
}
if (i == text.length()) {
throw new JSONException("illegal str, " + info());
}
}
public final void skipArray() {
skipArray(false);
}
public final void skipArray(boolean valid) {
boolean quote = false;
int bracketCnt = 0;
int i = bp;
for (; i < text.length(); ++i) {
char ch = text.charAt(i);
if (ch == '\\') {
if (i < len - 1) {
++i;
continue;
} else {
this.ch = ch;
this.bp = i;
throw new JSONException("illegal str, " + info());
}
} else if (ch == '"') {
quote = !quote;
} else if (ch == '[') {
if (quote) {
continue;
}
bracketCnt++;
} else if (ch == '{' && valid) {
{
int index = ++bp;
this.ch = (index >= text.length() //
? EOI //
: text.charAt(index));
}
skipObject(valid);
} else if (ch == ']') {
if (quote) {
continue;
} else {
bracketCnt--;
}
if (bracketCnt == -1) {
this.bp = i + 1;
if (this.bp == text.length()) {
this.ch = EOI;
token = JSONToken.EOF;
return;
}
this.ch = text.charAt(this.bp);
nextToken(JSONToken.COMMA);
return;
}
}
}
if (i == text.length()) {
throw new JSONException("illegal str, " + info());
}
}
public final void skipString() {
if (ch == '"') {
for (int i = bp + 1; i < text.length(); ++i) {
char c = text.charAt(i);
if (c == '\\') {
if (i < len - 1) {
++i;
continue;
}
} else if (c == '"') {
this.ch = text.charAt(bp = i + 1);
return;
}
}
throw new JSONException("unclosed str");
} else {
throw new UnsupportedOperationException();
}
}
public boolean seekArrayToItem(int index) {
if (index < 0) {
throw new IllegalArgumentException("index must > 0, but " + index);
}
if (token == JSONToken.EOF) {
return false;
}
if (token != JSONToken.LBRACKET) {
throw new UnsupportedOperationException();
}
// nextToken();
for (int i = 0; i < index; ++i) {
skipWhitespace();
if (ch == '"' || ch == '\'') {
skipString();
if (ch == ',') {
next();
continue;
} else if (ch == ']') {
next();
nextToken(JSONToken.COMMA);
return false;
} else {
throw new JSONException("illegal json.");
}
} else if (ch == '{') {
next();
token = JSONToken.LBRACE;
skipObject(false);
} else if (ch == '[') {
next();
token = JSONToken.LBRACKET;
skipArray(false);
} else {
boolean match = false;
for (int j = bp + 1; j < text.length(); ++j) {
char c = text.charAt(j);
if (c == ',') {
match = true;
bp = j + 1;
ch = charAt(bp);
break;
} else if (c == ']') {
bp = j + 1;
ch = charAt(bp);
nextToken();
return false;
}
}
if (!match) {
throw new JSONException("illegal json.");
}
continue;
}
if (token == JSONToken.COMMA) {
continue;
} else if (token == JSONToken.RBRACKET) {
return false;
} else {
throw new UnsupportedOperationException();
}
}
nextToken();
return true;
}
public int seekObjectToField(long fieldNameHash, boolean deepScan) {
if (token == JSONToken.EOF) {
return JSONLexer.NOT_MATCH;
}
if (token == JSONToken.RBRACE || token == JSONToken.RBRACKET) {
nextToken();
return JSONLexer.NOT_MATCH;
}
if (token != JSONToken.LBRACE && token != JSONToken.COMMA) {
throw new UnsupportedOperationException(JSONToken.name(token));
}
for (; ; ) {
if (ch == '}') {
next();
nextToken();
return JSONLexer.NOT_MATCH;
}
if (ch == EOI) {
return JSONLexer.NOT_MATCH;
}
if (ch != '"') {
skipWhitespace();
}
long hash;
if (ch == '"') {
hash = 0xcbf29ce484222325L;
for (int i = bp + 1; i < text.length(); ++i) {
char c = text.charAt(i);
if (c == '\\') {
++i;
if (i == text.length()) {
throw new JSONException("unclosed str, " + info());
}
c = text.charAt(i);
}
if (c == '"') {
bp = i + 1;
ch = (bp >= text.length() //
? EOI //
: text.charAt(bp));
break;
}
hash ^= c;
hash *= 0x100000001b3L;
}
} else {
throw new UnsupportedOperationException();
}
if (hash == fieldNameHash) {
if (ch != ':') {
skipWhitespace();
}
if (ch == ':') {
{
int index = ++bp;
ch = (index >= text.length() //
? EOI //
: text.charAt(index));
}
if (ch == ',') {
{
int index = ++bp;
ch = (index >= text.length() //
? EOI //
: text.charAt(index));
}
token = JSONToken.COMMA;
} else if (ch == ']') {
{
int index = ++bp;
ch = (index >= text.length() //
? EOI //
: text.charAt(index));
}
token = JSONToken.RBRACKET;
} else if (ch == '}') {
{
int index = ++bp;
ch = (index >= text.length() //
? EOI //
: text.charAt(index));
}
token = JSONToken.RBRACE;
} else if (ch >= '0' && ch <= '9') {
sp = 0;
pos = bp;
scanNumber();
} else {
nextToken(JSONToken.LITERAL_INT);
}
}
return VALUE;
}
if (ch != ':') {
skipWhitespace();
}
if (ch == ':') {
int index = ++bp;
ch = (index >= text.length() //
? EOI //
: text.charAt(index));
} else {
throw new JSONException("illegal json, " + info());
}
if (ch != '"'
&& ch != '\''
&& ch != '{'
&& ch != '['
&& ch != '0'
&& ch != '1'
&& ch != '2'
&& ch != '3'
&& ch != '4'
&& ch != '5'
&& ch != '6'
&& ch != '7'
&& ch != '8'
&& ch != '9'
&& ch != '+'
&& ch != '-') {
skipWhitespace();
}
// skip fieldValues
if (ch == '-' || ch == '+' || (ch >= '0' && ch <= '9')) {
next();
while (ch >= '0' && ch <= '9') {
next();
}
// scale
if (ch == '.') {
next();
while (ch >= '0' && ch <= '9') {
next();
}
}
// exp
if (ch == 'E' || ch == 'e') {
next();
if (ch == '-' || ch == '+') {
next();
}
while (ch >= '0' && ch <= '9') {
next();
}
}
if (ch != ',') {
skipWhitespace();
}
if (ch == ',') {
next();
}
} else if (ch == '"') {
skipString();
if (ch != ',' && ch != '}') {
skipWhitespace();
}
if (ch == ',') {
next();
}
} else if (ch == 't') {
next();
if (ch == 'r') {
next();
if (ch == 'u') {
next();
if (ch == 'e') {
next();
}
}
}
if (ch != ',' && ch != '}') {
skipWhitespace();
}
if (ch == ',') {
next();
}
} else if (ch == 'n') {
next();
if (ch == 'u') {
next();
if (ch == 'l') {
next();
if (ch == 'l') {
next();
}
}
}
if (ch != ',' && ch != '}') {
skipWhitespace();
}
if (ch == ',') {
next();
}
} else if (ch == 'f') {
next();
if (ch == 'a') {
next();
if (ch == 'l') {
next();
if (ch == 's') {
next();
if (ch == 'e') {
next();
}
}
}
}
if (ch != ',' && ch != '}') {
skipWhitespace();
}
if (ch == ',') {
next();
}
} else if (ch == '{') {
{
int index = ++bp;
ch = (index >= text.length() //
? EOI //
: text.charAt(index));
}
if (deepScan) {
token = JSONToken.LBRACE;
return OBJECT;
}
skipObject(false);
if (token == JSONToken.RBRACE) {
return JSONLexer.NOT_MATCH;
}
} else if (ch == '[') {
next();
if (deepScan) {
token = JSONToken.LBRACKET;
return ARRAY;
}
skipArray(false);
if (token == JSONToken.RBRACE) {
return JSONLexer.NOT_MATCH;
}
} else {
throw new UnsupportedOperationException();
}
}
}
public int seekObjectToField(long[] fieldNameHash) {
if (token != JSONToken.LBRACE && token != JSONToken.COMMA) {
throw new UnsupportedOperationException();
}
for (; ; ) {
if (ch == '}') {
next();
nextToken();
this.matchStat = JSONLexer.NOT_MATCH;
return -1;
}
if (ch == EOI) {
this.matchStat = JSONLexer.NOT_MATCH;
return -1;
}
if (ch != '"') {
skipWhitespace();
}
long hash;
if (ch == '"') {
hash = 0xcbf29ce484222325L;
for (int i = bp + 1; i < text.length(); ++i) {
char c = text.charAt(i);
if (c == '\\') {
++i;
if (i == text.length()) {
throw new JSONException("unclosed str, " + info());
}
c = text.charAt(i);
}
if (c == '"') {
bp = i + 1;
ch = (bp >= text.length() //
? EOI //
: text.charAt(bp));
break;
}
hash ^= c;
hash *= 0x100000001b3L;
}
} else {
throw new UnsupportedOperationException();
}
int matchIndex = -1;
for (int i = 0; i < fieldNameHash.length; i++) {
if (hash == fieldNameHash[i]) {
matchIndex = i;
break;
}
}
if (matchIndex != -1) {
if (ch != ':') {
skipWhitespace();
}
if (ch == ':') {
{
int index = ++bp;
ch = (index >= text.length() //
? EOI //
: text.charAt(index));
}
if (ch == ',') {
{
int index = ++bp;
ch = (index >= text.length() //
? EOI //
: text.charAt(index));
}
token = JSONToken.COMMA;
} else if (ch == ']') {
{
int index = ++bp;
ch = (index >= text.length() //
? EOI //
: text.charAt(index));
}
token = JSONToken.RBRACKET;
} else if (ch == '}') {
{
int index = ++bp;
ch = (index >= text.length() //
? EOI //
: text.charAt(index));
}
token = JSONToken.RBRACE;
} else if (ch >= '0' && ch <= '9') {
sp = 0;
pos = bp;
scanNumber();
} else {
nextToken(JSONToken.LITERAL_INT);
}
}
matchStat = VALUE;
return matchIndex;
}
if (ch != ':') {
skipWhitespace();
}
if (ch == ':') {
int index = ++bp;
ch = (index >= text.length() //
? EOI //
: text.charAt(index));
} else {
throw new JSONException("illegal json, " + info());
}
if (ch != '"'
&& ch != '\''
&& ch != '{'
&& ch != '['
&& ch != '0'
&& ch != '1'
&& ch != '2'
&& ch != '3'
&& ch != '4'
&& ch != '5'
&& ch != '6'
&& ch != '7'
&& ch != '8'
&& ch != '9'
&& ch != '+'
&& ch != '-') {
skipWhitespace();
}
// skip fieldValues
if (ch == '-' || ch == '+' || (ch >= '0' && ch <= '9')) {
next();
while (ch >= '0' && ch <= '9') {
next();
}
// scale
if (ch == '.') {
next();
while (ch >= '0' && ch <= '9') {
next();
}
}
// exp
if (ch == 'E' || ch == 'e') {
next();
if (ch == '-' || ch == '+') {
next();
}
while (ch >= '0' && ch <= '9') {
next();
}
}
if (ch != ',') {
skipWhitespace();
}
if (ch == ',') {
next();
}
} else if (ch == '"') {
skipString();
if (ch != ',' && ch != '}') {
skipWhitespace();
}
if (ch == ',') {
next();
}
} else if (ch == '{') {
{
int index = ++bp;
ch = (index >= text.length() //
? EOI //
: text.charAt(index));
}
skipObject(false);
} else if (ch == '[') {
next();
skipArray(false);
} else {
throw new UnsupportedOperationException();
}
}
}
}
|
When Amanda Balestrieri says “see you in court,” it’s an offer, not a threat.
As director of Seicento Baroque Ensemble, she knows just how much music originated in the royal courts of the 17th and 18th centuries. And for the group’s final concert of the 2018–19 season, she is pulling music from the courts of England, France and other European countries into a single program. “In Your Court: A Royal Tour” will be performed March 22-24 in Boulder, Denver and Longmont.
In addition to the singers of Seicento, the concert features guest vocal soloists and local freelance instrumentalists who make up a small orchestra. The vocalists are students or recent graduates who wanted more experience with the Baroque style.
Portions of the program directly reflect this. The first set is titled “Pomp and Circumstance” and features a triumphal march from the French court by Marc-Antoine Charpentier, as well as pieces by Henry Purcell and William Byrd written for the English court of their times. There is also a piece by Dom Jão (King John) IV of Portugal, and a piece written in praise of Poland’s Prince Władislaw on the occasion of a visit to the Medici court in Florence, Italy.
There are other musical topics in the program, including sets of pieces titled “Sacred Music for the French Court,” “A Royal View of Rural Life” and “Reflections on Death.” The last is followed by the one Russian piece on the program, an Easter Canon by Nikolay Diletsky, representing resurrection.
Almost every piece, in some way, reflects on the relationship between the composer and his patrons, or life at court more generally. Part of the opening set is a piece by Purcell, “Welcome Vicegerent of the Mighty King,” which, Balestrieri says, “was written for the return of Charles II to London — to lick his boots, basically.” In an extreme way, that symbolizes the relationship between royal patrons and musicians in the Baroque era.
Another example of over-the-top praise is the prologue to an opera by Francesca Caccini, one of the few active women composers of the era. The opera was written for Prince Władislaw’s visit to the Medici Court. Seicento will only perform the prologue, which features extravagant compliments for the visitor.
A different kind of relationship between patron and musician is suggested in “O Lord, Make Thy Servant Elizabeth our Queen” by William Byrd, written for Elizabeth I of England. The music is filled with dissonances and harsh clashes between voices, particularly in the words “her” in the phrase “give her her heart’s desire.” Those dissonances, Balestrieri says, may refer to the fact that Byrd, a devout Catholic, was not comfortable in Elizabeth’s Protestant court.
With so much music composed to send a message to monarchs and courtiers, Balestrieri treasurers a movement from Johann Kaspar Kerll’s Mass for the Dead. “One of the things I love about the Kerll [piece] is that he remarked that he wrote this for the peace of his own soul, which I thought was touching because it shows you this wasn’t just written to welcome the king back,” she says.
Similar layers of meaning — directed at the monarch or the courtiers, who were the only people who would have heard most of the music on the concert, since it was not performed publicly — can be found in every piece. All of that information is covered in Balestrieri’s extensive notes that will be printed in the program — information she is happy to share with Seicento’s audience.
In other words, she extends an invitation, not a summons: Come see us in court!
ON THE BILL: In Your Court: A Royal Tour — Seicento Baroque Ensemble, Amanda Balestrieri, conductor; with guest soloists and instrumentalists. 7:30 p.m. Friday, March 22, First United Methodist Church, Boulder. 7:30 p.m. Saturday, March 23, Julian Pavilion, Highland Center, 2945 Julian St., Denver. 2:30 p.m. Sunday, March 24, Stewart Auditorium,400 Quail Road, Longmont. |
A little over three months into President Trump’s tenure, outside of the nomination of Neil Gorsuch to the Supreme Court, Trump has little success.
People will point to Trump’s many executive orders, and while I agree with many of them, they are only good for as long as he’s in office. His tenure so far makes for a great reality show, but Trump’s approval ratings are in the gutter, and he spends more time insulting people on Twitter than making the deals he said will make America great again.
When Trump supporters are reminded his presidency thus far is akin to a slow moving train wreck, their defense of Trump boils down to several replies, all of which are pedestrian and don’t do much to rebut the accusations against him.
One of the more oft-repeated defenses of Trump is that he is, for all of his faults, “better than Hillary.” Jonah Goldberg recently wrote, “Better than Hillary” strikes me as the minimum requirement for a conservative president, not an omnibus justification for anything he does.” I’d go so far as to say it is the minimum requirement for any Republican president, even somebody such as John Kasich. Trump won, not because he’d be better than Hillary, but because he convinced so many people he’d be better than Marco Rubio, Scott Walker, Jeb Bush, Ted Cruz and the rest of the GOP field. The argument Trump is better than Hillary is like bragging your car is better than a Yugo. A pair of roller skates with clay wheels is better than a Yugo.
Pinning the blame on Speaker Paul Ryan, the House Freedom Caucus, and Mitch McConnell is another tactic Trump supporters employ when reminded of the lack of legislation crossing President Trump’s desk. “Trump can’t help it if Ryan and the rest of the GOP losers can’t do their job!” Au contraire, mon ami, it is not Ryan who promised to be the greatest dealmaker ever elected President of the United States. Donald Trump routinely stated America is not great because of incompetent Presidents who didn’t know the “art of the deal.” Trump maintained he’d change all that. He’d use his deal-making ninja skills to work miracles while in office. Here’s a video of Trump saying it:
He said during a debate:
“With Congress, you have to get everybody in a room. You have to get them to agree with what you want,” he said. “You have to get people in. Grab em, hug em, kiss em, and get the deal done. But it’s got to be the deal that you want.”
The other defense is pure deflection. It usually comes in the form of how he “takes it to Democrats” and “attacks the media.” I suppose some people enjoy watching him talk about “fake news” and using his cute nicknames like “Crying Chuck Schumer” as they did “Lyin Ted” and “Little Marco” during the primary campaign. But is that seriously the best his defenders can do? Are they going to measure the success of a presidency based on his ability to lob schoolyard insults?
They put forward such defenses and use it as a yardstick to measure Trump’s “success.” But when Trump’s job approval ratings are in the 30’s, it’s a hell of a price to pay for what could be huge Democratic gains down the road. At some point, Trump will have to do more than sign executive orders and show them off to the media.
If not, his supporters are going to run out of excuses. |
<filename>graph-inventory/aai-client/src/main/java/org/onap/aaiclient/client/graphinventory/entities/DSLQueryBuilder.java
/*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.aaiclient.client.graphinventory.entities;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.onap.aaiclient.client.aai.entities.QueryStep;
import org.onap.aaiclient.client.graphinventory.GraphInventoryObjectName;
import com.google.common.base.Joiner;
public class DSLQueryBuilder<S, E> {
private List<QueryStep> steps = new ArrayList<>();
private String suffix = "";
protected DSLQueryBuilder() {
}
protected DSLQueryBuilder(QueryStep node) {
steps.add(node);
}
public <T> DSLQueryBuilder<S, DSLNodeBase<?>> node(DSLNodeBase<?> node) {
steps.add(node);
return (DSLQueryBuilder<S, DSLNodeBase<?>>) this;
}
public DSLQueryBuilder<S, Node> output() {
Object obj = steps.get(steps.size() - 1);
if (obj instanceof DSLNodeBase) {
((DSLNodeBase) steps.get(steps.size() - 1)).output();
} else if (obj.getClass().getName().contains("$$Lambda$")) {
// process lambda expressions
for (Field f : obj.getClass().getDeclaredFields()) {
f.setAccessible(true);
Object o;
try {
o = f.get(obj);
if (o instanceof DSLQueryBuilder && ((DSLQueryBuilder) o).steps.get(0) instanceof DSLNodeBase) {
((DSLNodeBase) ((DSLQueryBuilder) o).steps.get(0)).output();
}
} catch (IllegalArgumentException | IllegalAccessException e) {
}
f.setAccessible(false);
break;
}
}
return (DSLQueryBuilder<S, Node>) this;
}
@SafeVarargs
public final <E2> DSLQueryBuilder<S, E2> union(final DSLQueryBuilder<?, E2>... union) {
List<DSLQueryBuilder<?, ?>> unions = Arrays.asList(union);
steps.add(() -> {
StringBuilder query = new StringBuilder();
query.append("> [ ")
.append(Joiner.on(", ")
.join(unions.stream().map(item -> item.compile()).collect(Collectors.toList())))
.append(" ]");
return query.toString();
});
return (DSLQueryBuilder<S, E2>) this;
}
public DSLQueryBuilder<S, E> where(DSLQueryBuilder<?, ?> where) {
steps.add(() -> {
StringBuilder query = new StringBuilder();
query.append(where.compile()).append(")");
String result = query.toString();
if (!result.startsWith(">")) {
result = "> " + result;
}
return "(" + result;
});
return this;
}
public <E2> DSLQueryBuilder<S, E2> to(DSLQueryBuilder<?, E2> to) {
steps.add(() -> {
StringBuilder query = new StringBuilder();
query.append("> ").append(to.compile());
return query.toString();
});
return (DSLQueryBuilder<S, E2>) this;
}
public DSLQueryBuilder<S, E> to(GraphInventoryObjectName name) {
return (DSLQueryBuilder<S, E>) to(__.node(name));
}
public DSLQueryBuilder<S, E> to(GraphInventoryObjectName name, DSLNodeKey... key) {
return (DSLQueryBuilder<S, E>) to(__.node(name, key));
}
public DSLQueryBuilder<S, E> limit(int limit) {
suffix = " LIMIT " + limit;
return this;
}
public DSLTraversal<E> build() {
return new DSLTraversal<>(compile());
}
@Override
public String toString() {
return build().get();
}
@Override
public boolean equals(Object o) {
if (o != null) {
return o.toString().equals(toString());
}
return false;
}
@Override
public int hashCode() {
return compile().hashCode();
}
private String compile() {
return String.join(" ", steps.stream().map(item -> item.build()).collect(Collectors.toList())) + suffix;
}
protected QueryStep getFirst() {
return steps.get(0);
}
}
|
<reponame>bakharevpavel/node-rf1996
enum ECardType : UINT {
ect_none = 0,
ect_clean_temic = 0x10,
ect_temic = 0x20,
ect_bad_password = 0x30,
esi_em_marine = 0x40,
ect_EEPROM_error = 0x80,
ect_data_error = 0x81,
ect_unknow = 0xF0,
};
enum ELicenseStatus : UINT {
els_no_info = 0,
els_ok = 0xAA,
els_none = 0xFE,
els_conclude = 0xFD,
els_hard_error = 0xFC,
};
struct SDeviceInfoA {
char Port[16];
char DeviceName[128];
DWORD SerialNumber;
DWORD ModelNumber;
DWORD FirmwareVersion;
ELicenseStatus LicenseStatus;
DWORD LicenseYear;
DWORD LicenseMonth;
DWORD LicenseDay;
DWORD CountCard;
};
struct SCardInfo {
DWORD Flags;
ECardType CardType;
BYTE TemicCode[8];
BYTE EmMarineCode[8];
DWORD LimitLocks;
DWORD CountBorrow;
DWORD NumLastLocks;
BOOL BatteryCondition;
};
typedef DWORD (*pfnInit)();
typedef DWORD (*pfnOpenDeviceA)(char *port);
typedef DWORD (*pfnCloseDevice)();
typedef BOOL (*pfnIsDeviceOpen)();
typedef DWORD (*pfnGetDeviceInfoA)(SDeviceInfoA *DevInfo);
typedef DWORD (*pfnReadCard)(SCardInfo* CardInfo);
typedef DWORD (*pfnWriteCard)(DWORD LimitLocks);
typedef DWORD (*pfnInitCard)(BYTE *EmMarineCode);
typedef DWORD (*pfnClearCard)();
HMODULE lib;
SCardInfo CardInfo;
SDeviceInfoA DeviceInfo;
pfnInit InitLib;
pfnOpenDeviceA OpenDeviceA;
pfnIsDeviceOpen IsDeviceOpen;
pfnReadCard ReadCard;
pfnCloseDevice CloseDevice;
pfnGetDeviceInfoA GetDeviceInfoA;
pfnWriteCard WriteCard;
pfnInitCard InitCard;
pfnClearCard ClearCard;
|
1. Field of the Invention
The present invention provides a coupling for a fluid line arrangement.
2. Description of the Related Art
One known coupling for a fluid line arrangement is known from U.S. Pat. No. 4,147,368. The prior coupling comprises a coupling part provided with a sealing unit that is in the form of a sealing ring and by means of which the coupling part and an insert part that can be fitted into the coupling part can be sealed against each other. The sealing ring is disposed in a circumferential, recessed receiving groove provided in the inner wall of the coupling part, has a radially outwardly disposed, planar outer side that contacts a planar support surface of the receiving groove, and is configured with a radially inwardly oriented, arcuate inner side, edge faces oriented at right angles to the outer side being configured between the outer side and the inner side.
U.S. Pat. No. 3,584,889 and U.S. Pat. No. 3,368,830 each disclose a coupling for a fluid line arrangement, in which a coupling part in the form of a sleeve extending between two line ends of the fluid line arrangement is configured endwise with rectangular sealing-ring receptacles formed by radially broadening the sleeve. In U.S. Pat. No. 3,584,889, a sealing ring having a radially outwardly disposed, planar outer side and an inwardly oriented, arcuate inner side is fitted into each of the sealing-ring receptacles, edge faces oriented at right angles to the outer side and comprising axially projecting elevations being configured between the outer side and the inner side. In U.S. Pat. No. 3,368,830, a sealing ring having a radially outwardly disposed, planar outer side and an inwardly oriented inner side is fitted into each of the sealing-ring receptacles, the inner side being provided with a number of flexible ribs that are deformable and fit themselves to the line ends of the fluid line arrangement.
Known from DE 200 16 118 U1 is a fluid line arrangement with a complexly configured seal exhibiting various curvatures, grooves and flat sides.
Known from DE 299 03 469 U1 is a fluid line arrangement with annular seals configured with hooks.
Known from U.S. Pat. No. 3,891,224 is a D-shaped seal for a manhole composed of ring segments, which seal has a radially outwardly disposed, planar outer side and a radially inwardly oriented, arcuate inner side, with edge faces oriented at right angles to the outer side extending between the outer side and the inner side. The seal is configured with an inner cavity and contacts, by an edge face, an abutment step configured in a ring segment.
Known from U.S. Pat. No. 3,081,102 is a fluid line arrangement comprising a seal having dome-like and finger-like elevations.
Known from DE 101 15 399 C1 is a coupling that is to be integrated into a fluid line arrangement and comprises a coupling part provided with a sealing unit having at least one sealing ring. The sealing unit of the prior coupling comprises two sealing rings of round cross section and an intermediate ring disposed between the sealing rings, and is intended to seal against each other the coupling part and an insert part that can be fitted into the coupling part. |
The effect of coronavirus infection (SARS-CoV-2, MERS-CoV, and SARS-CoV) during pregnancy and the possibility of vertical maternalfetal transmission: a systematic review and meta-analysis Background Coronavirus is challenging the global health care system from time to time. The pregnant state, with alterations in hormone levels and decreased lung volumes due to a gravid uterus and slightly immunocompromised state may predispose patients to a more rapidly deteriorating clinical course and can get a greater risk of harm for both the mother and fetus. Therefore, this systematic review was aimed to assess the effect of coronavirus infection (SARS-CoV-2, MERS-CoV, and SARS-CoV) during pregnancy and its possibility of vertical maternalfetal transmission. Methods A systematic search was conducted on PubMed, Web of Science, Embase, Google Scholar and the Cochrane Library until the end of April. All authors independently extracted all necessary data using excel spreadsheet form. Only published articles with fully accessible data on pregnant women infected with SARS-CoV, MARS-CoV, and SARS-CoV-2 were included. Data on clinical manifestations, maternal and perinatal outcomes were extracted and analyzed. Result Out of 879 articles reviewed, 39 studies involving 1316 pregnant women were included. The most common clinical features were fever, cough, and myalgia with prevalence ranging from 30 to 97%, while lymphocytopenia and C-reactive protein were the most common abnormal laboratory findings (55100%). Pneumonia was the most diagnosed clinical symptom of COVID-19 and non-COVID-19 infection with prevalence ranged from 71 to 89%. Bilateral pneumonia (57.9%) and ground-glass opacity (65.8%) were the most common CT imaging reported. The most common treatment options used were hydroxychloroquine (79.7%), ribavirin (65.2%), and oxygen therapy (78.8%). Regarding maternal outcome, the rate of preterm birth <37 weeks of gestation was 14.3%, preeclampsia (5.9%), miscarriage (14.5%, preterm premature rupture of membranes (9.2%) and fetal growth restriction (2.8%). From the total coronavirus infected pregnant women, 56.9% delivered by cesarean, 31.3% admitted to ICU, while 2.7% were died. Among the perinatal outcomes, fetal distress rated (26.5%), neonatal asphyxia rated (1.4%). Only, 1.2% of neonates had apgar score<7 at 5 min. Neonate admitted to ICU was rated 11.3%, while the rate of perinatal death was 2.2%. In the current review, none of the studies reported transmission of CoV from the mother to the fetus in utero during the study period. Conclusion Coronavirus infection is more likely to affect pregnant women. Respiratory infectious diseases have demonstrated an increased risk of adverse maternal obstetrical complications than the general population due to physiological changes occurred during pregnancy. None of the studies reported transmission of CoV from the mother to the fetus in utero, which may be due to a very low expression of angiotensin-converting enzyme-2 in early maternalfetal interface cells. Background Coronaviruses (CoVs) are one of the major pathogens that are grouped in the family of Coronaviridae, which primarily target the human respiratory system. It is one of the emerging and reemerging viral outbreaks throughout the world. Previous outbreaks of coronaviruses include the severe acute respiratory syndrome (SARS)-CoV epidemic in 2003 and the Middle East respiratory syndrome (MERS)-CoV in 2012, while the newly emergent coronavirus, initially referred to as 2019-nCoV and subsequently termed SARS-CoV-2, the disease it produces has been termed COVID-19, which causes respiratory infection and can progress to severe pneumonia and, in a small number of cases, death. Although these coronaviruses were isolated from different human and animal hosts at different times and locations, they all belong to the species severe acute respiratory syndromerelated coronavirus. The increasing mortality rate warrants that vulnerable populations in the society be identified and protected. When COVID-19 and other CoV infect women who are pregnant, it increases the risk of adverse obstetrical and neonatal outcomes and results in severe respiratory disease. Previous data from multiple studies of influenza and other respiratory infectious diseases have demonstrated an increased risk of maternal obstetrical complications when compared with nonpregnant women due to physiological changes occurring during pregnancy. This association has also been previously demonstrated to occur when pregnant women became infected with either of the two pathogenic coronavirus infections (SARS-CoV 2 and MERS-CoV). Coronavirus infection in pregnant women makes clinical management more difficult by prolonging and complicating the illness and compromises the treatment. Researchers are still in question regarding the transmission of the novel and previous coronavirus infection from a pregnant woman to her fetus, a process termed vertical transmission. There are few published cases of coronavirus disease occurring during pregnancy and due to the possibility of mother-fetal vertical transmission, there is a concern that the fetuses may be at risk of congenital COVID-19 and other CoV outbreaks. Due to the alarming spread of CoV outbreaks throughout the world, a comprehensive understanding of the transmission of the virus from mother to fetus in utero like other emerging viral infections as Zika virus and Ebola virus, that can threaten the health and survival of an infected mother and fetus is essential for effective management of the infection and treatment. Therefore, this systematic review and meta-analysis was aimed to assess the effect of coronavirus infection (SARS-CoV-2, MERS-CoV, and SARS-CoV) during pregnancy and its possibility of vertical maternal-fetal transmission. Study design A systematic review and meta-analysis was aimed to assess the effect of coronavirus infection (SARS-CoV-2, MERS-CoV, and SARS-CoV) during pregnancy and its possibility of vertical maternal-fetal transmission following the methodological framework suggested by Arksey and O'Malley. Search strategies All relevant articles were searched without date limits using the following databases: PubMed, Web science, Embase, Google Scholar, Cochrane library, and Science Direct according to the Preferred Reporting Items for Systematic Reviews and Meta-analysis (PRISMA). All searches were limited to article written in English given that such language restriction does not alter the outcome of the systematic reviews and meta-analysis. The gray literature of observational studies was searched through the review of reference lists and input of content experts. We searched scientific publications from 2003 to 2020. All papers published until the end of April 30, 2020, and fulfill the inclusion criteria were considered. The search used the following keywords: coronavirus, novel coronavirus-2019 infection, pregnancy, Middle East respiratory syndrome, severe acute respiratory syndrome, severe acute respiratory syndrome coronavirus-2, and vertical transmission. We searched all terms with the help of Boolean operators like "AND" or "OR". Conclusion: Coronavirus infection is more likely to affect pregnant women. Respiratory infectious diseases have demonstrated an increased risk of adverse maternal obstetrical complications than the general population due to physiological changes occurred during pregnancy. None of the studies reported transmission of CoV from the mother to the fetus in utero, which may be due to a very low expression of angiotensin-converting enzyme-2 in early maternal-fetal interface cells. Assessment of study quality Studies selected for inclusion were assessed for methodological quality by all authors' independently using the standard critical appraisal instruments of the Joanna Briggs Institute Meta-Analysis of Statistics Assessment Review Instrument (JBI-MAStARI). The disagreements were resolved by consensus. Outcome measures The primary outcome variable of this study was the pregnancy outcomes observed, listed as follows: preterm birth (PTB; either before 37 or 34 weeks of gestation), preeclampsia, preterm prelabor rupture of membranes, (pPROM), fetal growth restriction (FGR), miscarriage, maternal death, mode of delivery and other clinical feature, laboratory findings and coexisting disease. The secondary outcomes were the perinatal outcomes observed as listed: fetal distress, apgar score < 7 at 5 min, neonatal asphyxia, admission to the neonatal intensive care unit (NICU), perinatal death, including both stillbirth, and neonatal death, evidence in utero transmission. Data extraction and synthesis The data were extracted using a standardized data extraction format, adapted from the Joanna Briggs Institute (JBI), by three authors (KD, EA, and AG), independently extracting all necessary data using an excel spreadsheet form. Then the extracted data were merged for systematic analysis. Any disagreements during the data extraction were resolved through discussion and consensus. The main outcomes extracted from the study were: primary author, study design, publication year, country, patient demographics, maternal and perinatal outcome, and evidence of in utero transmission of coronavirus. All clinical characteristics of pregnant women infected with coronavirus, laboratory and radiological findings, treatment options, and data on associated risk factors were extracted by the authors. Statistical analysis Following data extraction, systematic review and metaanalysis were carried out using R software version 3.6.1 and STATA statistical software (version 13) with usercontributed commands for meta-analyses: metaprop, metan, metainf, metabias, and metareg. The effect sizes and SEs of the studies were pooled using a random-effects model to calculate the pooled estimates of laboratory findings, other clinical features and coexisting diseases among patients with COVID-19 infection. A meta-analysis was also planned to assess the association of various comorbidities and laboratory findings with the severity of disease. Risk of bias and sensitivity analysis The standard error for each original study was calculated using the binomial distribution formula. Evidence for statistical heterogeneity among reported prevalence was using the Cochrane Q-test and I 2 statics. The pooled proportion was estimated by using the back-transform of the weighted mean of the transformed proportions for both the fixed-effects model and the random-effects model. A significance level of P < 0.10 and I 2 > 50% was interpreted as evidence of heterogeneity. A potential source of heterogeneity was investigated by subgroup analysis and meta-regression analysis. Where statistical pooling was not possible, the findings were presented in a narrative form including tables and figures to aid in data presentation where appropriate. Sensitivity analyses were conducted to weigh up the relative influence of each individual study on the pooled effect size using a user-written function, metainf. The presence of publication bias was assessed informally by visual inspection of funnel plots. Point prevalence, as well as 95% confidence intervals, was presented in the forest plot format. Study selection Database searches identified a total of 879 articles. From these initial articles, 29 articles were excluded due to duplication. From the remaining 850 articles, 786 articles were excluded after review of their titles and abstracts confirmed nonrelevance to this review. Therefore, 64 full-text articles were assessed for eligibility based on the preset criteria, which resulted in the further exclusion of 25 articles primarily due to the outcome of the interest being not reported in the study. Ultimately, 39 studies met the eligibility criteria and were included in the final review ( Fig. 1 and Table 1). Description of included studies In the current review, 39 articles with a total of 1316 pregnant women with laboratory-confirmed CoV [12, (Table 1). Commonly reported clinical feature and laboratory finding of pregnant women infected with coronaviruses (SARS-CoV-2, MERS-CoV, and SARS-CoV) From commonly reported laboratory findings, lymphocytopenia was the most frequently reported in the three coronavirus infections with prevalence ranged from 63 to 100%, followed by elevated C-reactive protein and leukopenia with prevalence ranged from 45 to 100% (Table 2). Commonly reported radiological finding and treatment of pregnant women infected with coronaviruses (SARS-CoV-2, MERS-CoV, and SARS-CoV) The most common computed tomography imaging features in pregnant women infected with coronaviruses were ground-glass opacity followed by bilateral pneumonia with a prevalence of 65.8% and 57.9%, respectively (Table 3). In this study, ribavirin and oseltamivir were the most commonly used antiviral therapy used for the treatment of viral pathogens among pregnant women infected with coronaviruses with a prevalence of 65.2% and 56.5%, while the most common antibiotic therapy used for the treatment of common bacterial coinfection was azithromycin with prevalence of 35%. In this study, hydroxychloroquine was the leading drug used by people infected with coronaviruses with a prevalence of 79.7%. From the total coronavirus-infected pregnant women, around 78.8% were treated with oxygen therapy while 18.1% were supported by mechanical ventilation ( Table 3). The outcome of pregnant women infected with coronavirus and their newborn Out of 1316 pregnant women infected with CoV, 46.5% give birth at > 37 weeks of gestation, while the rates of PTB < 34 and < 37 weeks of gestation were 9.5% and 14.3%, respectively. Preeclampsia was reported among 5.9% of pregnant women, while the rate of miscarriage for CoV infection was 14.5%. pPROM and FGR were rated 9.2% and 2.8%, respectively. From the total CoVinfected pregnant women, 31.3% were admitted to ICU from which 2.7% were died. The prevalence of cesarean delivery was 56.9%, while 28.6% had undergone normal delivery. Fetal distress was reported in 26.5%, while neonatal asphyxia was reported in only 1.4% of neonates. Only, 1.2% of neonates had apgar score < 7 at 5 min. Neonate admitted to ICU was rated 11.3%, while the rate of perinatal death was 2.2%. In the current review, none of the studies reported transmission of CoV from the mother to the fetus in utero during the follow-up period ( Table 4). In our systematic review, different comorbidities that aggravate the infection were found among pregnant women infected with CoV. From the total CoV-infected pregnant women, the rate of gestational diabetes was 9.6%, while hypertension was reported in 8.5% of pregnant women infected with CoV. The rate of asthma in pregnant women infected with CoV was 5.5%, while cardiovascular disease and digestive disease rated 5.7% and 3.6%, respectively ( Table 4). Comparison of severe cases among coronavirus infection (SARS-CoV-2, MERS-CoV, and SARS-CoV) In this meta-analysis, MERS-CoV was the most predominant causative agent of severe cases among infected pregnant women with a prevalence of 77% with 95% CI, followed by SARS-CoV rated 48% with 95% CI. According to our findings, SARS-CoV-2 was the least causative agent of severe cases among the infected The effect of SARS-CoV-2, MERS-CoV, and SARS-CoV in pregnant women and their newborns SARS-CoV-2 Out of 39 eligible articles, 25 studies [12, reported information on infections caused by SARS-CoV-2 among a total of 1271 pregnancies. The prevalence of SARS-CoV-2 among preterm birth at < 37 and 34 weeks of gestation was 14.3% and 8.9%, respectively, while 46.2% of pregnant women give birth at > 37 weeks of gestation. Preeclampsia was reported among 5.7% of pregnant women with COVID-19. pPROM was reported in 8.9%, while the rate of fetal growth restriction was reported in 1.2%. In this study, miscarriage was rated 2.4%. ICUadmitted pregnant women were accounted for 28.5%, while the rate of maternal death was reported in 1.5%. The prevalence of cesarean delivery was 57% (Table 5). Fetal distress was reported among 25%, while the rate of neonatal asphyxia was 1.6%. The prevalence of Apgar score < 7 at 5 min was 1.4%. The rate of newborns admitted to NICU was 11.6% in which perinatal death was reported among 2.9%. None of the studies reported transmission of SARS-CoV-2 from the mother to the fetus in utero during the follow-up period (Table 5). MERS-CoV Out of 35 eligible articles, seven studies reported information on 12 pregnant women infected with MERS-CoV. The prevalence of preterm birth among pregnant women of < 34 weeks of gestation was 33.3%, while 80% of pregnant women give birth at > 37 weeks of gestation. Preeclampsia was observed among 5.7% of pregnant women infected with MERS-CoV. ICU-admitted pregnant women accounted for 33.3%, while the rate of maternal death was reported to be 40%. The prevalence of pregnant women given birth by cesarean was 66.7%, while 16.7% of pregnant women underwent normal delivery. Perinatal death was reported among 33.3% of the newborns, while none of the studies reported fetal distress, apgar score < 7 at 5 min, neonatal asphyxia, and admission to the neonatal intensive care unit. None of the studies reported transmission of MERS-CoV from the mother to the fetus in utero during the follow-up period (Table 5). SARS-CoV Out of 35 eligible articles, seven studies reported information on 33 pregnant women infected with SARS-CoV. The prevalence of SARS-CoV among preterm birth < 37 and 34 weeks of gestation was 21.7% and 12%, respectively, while 38.5% of pregnant women give birth at > 37 weeks of gestation. pPROM was reported in 12.5%, while the rate of fetal growth restriction was reported in 12.5%. Miscarriage was reported among 38.1% of pregnant women. ICU admitted pregnant women were accounted for 54.5%, while the rate of maternal death was reported in 12.5%. The prevalence of pregnant women giving birth by cesarean was 50%, while 22.2% of pregnant women underwent normal delivery. The prevalence of fetal distress and perinatal death was 33.3% and 10%, respectively, while none of the studies reported apgar score < 7 at 5 min, neonatal asphyxia and admission to the neonatal intensive care unit. None of the studies reported transmission of SARS-CoV from the mother to the fetus in utero during the follow-up period (Table 5). Heterogeneity and risk of bias Subgroup analysis was conducted to justify the cause of heterogeneity. Subgroup analysis of the included studies showed that the possible cause of heterogeneity was a sample size difference, especially in SARS-CoV-2 (I 2 = 94%). The funnel plots suggest a publication bias for some of the study of the parameters (P < 0.02). Summary of findings We conducted a systematic review and meta-analysis to provide an overview of the effect of CoV (SARS-CoV-2, MERS-CoV, and SARS-CoV) infection on maternal and perinatal, and the possibility of vertical transmission of the virus from pregnant women to the fetus. The rapidly spreading nature of COVID-19 and previous CoV infections could have a significant effect on human health. Thus, attention should be given to pregnant women, and they should be included in preparedness and response plans. In previous outbreaks, clinicians did not volunteer to treat or vaccinate pregnant women because of concerns for fetal safety. The pregnant state, with alterations in hormone levels and decreased lung volumes due to a gravid uterus and slightly immunocompromised state may predispose patients to a more rapidly deteriorating clinical course and face a greater risk of harm if they get respiratory infections. In the current study, the predominant signs and symptoms of hospitalized pregnant women suffering from COVID-19 and other coronavirus infections were viral pneumonia, fever, cough, fatigue, and myalgia. The Centre for disease control listed these symptoms to be the leading clinical feature of patients infected with COVID-19 and other coronaviruses. The high fever after delivery may have resulted from immunity reduction due to fatigue and blood loss in childbirth, anatomy of female genitalia, sweating during puerperium, and postpartum lactation. Once postpartum fever occurred, obstetricians and gynecologists should follow and perform a differential diagnosis to exclude breast swelling, mastitis, urinary tract infections, common colds, and reproductive tract infections must be focused on. Gastrointestinal symptoms like diarrhea and abdominal pain were also observed in pregnant women with COVID-19 and other coronavirus infections. Gestational diabetes and hypertension were the most common coexisting disorders with a prevalence of 9.6% and 8.5%. More than half of the pregnant women infected with coronaviruses were treated by antiviral and antibiotic therapy. In our study, the most frequently reported laboratory findings was lymphocytopenia (66.1%), followed by elevated C-reactive protein marker (56.6%), leukopenia (48.3%) and elevated lactate dehydrogenase (34.8%). This is similar to previous studies reporting on COVID-19 and other CoV infections. Laboratory findings like leukopenia and lymphocytopenia were helpful to distinguish viral infections from common bacterial infections. The most common computed tomography imaging features in pregnant women with COVID-19 and non-COVID-19 pneumonia were ground-glass opacity and bilateral pneumonia with a prevalence of 57.9% and 65.8%, respectively. The pathological basis of these changes could be due to inflammatory cell infiltration and interstitial thickening, cell exudation, and hyaline membrane formation. The most common treatment options used were hydroxychloroquine (79.7%), ribavirin (65.2%), oseltamivir (56.5%) and azithromycin (35%) to treat common bacterial pathogens when secondary infections occurred and treat viral pathogens. Among CoVinfected pregnant women, oxygen therapy was 78.8%. Based on the findings of the present study, higher prevalence of COVID-19 and other CoV was reported among preterm birth < 37 weeks of gestation. According to some studies report, infection with COVID-19 during pregnancy can cause complications for both the mother and the fetus. This includes preeclampsia, preterm premature rupture of membranes, fetal growth restriction, and miscarriage. Large numbers of CoV-infected pregnant women with severe cases were admitted to the intensive care unit which even There is much controversy relating to the possibility of in utero transmission of SARS-CoV-2, MERS-CoV, and SARS-CoV. Multiple samples were obtained at the time of labor and delivery to test for the presence of coronavirus by qRT-PCR, including amniotic fluid aspirated from the vagina during labor, cord blood, and segments of the umbilical cord, fetal membranes, and placenta, neonatal nasopharyngeal and throat swabs, gastric aspirate and meconium samples tested negative for the coronaviruses, suggesting there was no evidence of vertical transmission in women who developed COVID-19 and non-COVID-19 coronavirus pneumonia in late pregnancy. Studies conducted in London reported a neonate born to a pregnant woman with COVID-19 that tested positive for SARS-CoV-2 in the pharyngeal swab sample 36 h after birth, it was subsequently confirmed that qRT-PCR testing of the placenta and cord blood was negative for SARS-CoV-2, it is believed that the mother or a family member transmitted the infection to the infant through close contact after delivery, not in utero through placenta. In the current study, the systematic testing procedures for coronavirus infection, including chest radiograph and serial RT-PCR assays with multiple clinical samples did not demonstrate the presence of SARS-CoV-2, MERS-CoV and SARS-CoV in the newborn. CoV antibody tests were performed with mother and newborn sera. In some mothers', sera immunoglobulin G was detected by using serological tests. However, CoV antibodies for IgG, IgM, and IgA were detected in none of the newborn's blood samples. Therefore, there is no evidence of intrauterine transmission of SARS-CoV-2 and other CoV from mother to newborn infants. This may be due to a very low expression of angiotensin-converting enzyme 2 (ACE2) in early maternal to fetal interface cells. The virus can be transmitted through close contact or droplets to a new born after birth. Thus, mothers and their neonates should be taken care of in isolated rooms to prevent neonatal transmission and effective protection measures should be implemented during delivery and postdelivery care to prevent transmission of the virus from mothers to the newborn. Limitations of the study Only English articles or reports were considered for this review. The small number of cases in some of the included studies, the study design, and the lack of standardized criteria were the major limitations of this systematic review. Additionally, there is a possibility that some patients were included in more than 1 report, although all authors independently reviewed all the included studies, carefully focusing on the different institutions reporting outcomes. We included case reports and case series, thus facing a higher risk of publication bias, which could affect the estimated outcome. Furthermore, lack of denominator in case series used in this review is the other major factor that affects the estimated outcome. Moreover, when focusing on the outcomes of COVID-19 infection, and particularly perinatal outcomes, reported data are intuitively limited to a very short-term followup period and thus infections that occurred proximate to the delivery. This has the potential to overestimate the magnitude of risks such as PTB and underestimate more longitudinal risks such as FGR. In some of the studies, we did not find standardized criteria and timing of delivery of pregnancies affected by CoV infection. Conclusion In general, based on the published data collected, fever, cough, and myalgia were the most common clinical features, while the predominant abnormal laboratory findings reported were lymphocytopenia and C-reactive protein. Bilateral pneumonia and ground-glass opacity were the most common radiological abnormal findings. Oxygen therapy was the most common treatment option used while bacterial coinfection was treated by antibiotics therapy, and viral pathogen was treated by antiviral therapy. Among the coronavirus species, MERS-CoV was the leading cause of severe cases in infected pregnant women. Pregnant women infected with coronaviruses are at increased risk of adverse obstetrical outcomes, compared with the general population. The infection outcome was mainly associated with a relatively higher rate of cesarean delivery, preterm birth, intensive care unit admission, preeclampsia, miscarriage, fetal distress, and perinatal death. None of the studies reported transmission of CoV from the mother to the fetus in utero. This may be due to a very low expression of angiotensin-converting enzyme 2 (ACE2) in early maternal-fetal interface cells as suggested by different experts. |
Solving the Regress Puzzle: J. F. Fries's Psychological Reconstruction of Kant's Transcendental Methodology abstract:Many commentators have noted that Kant's transcendental methodology seems to be in danger of infinite regress. This paper discusses an early and much-neglected attempt to resolve this Regress Puzzle. Jakob Friedrich Fries, one of the most prominent Kantians during the first decades of the nineteenth century, argued that in order to avoid the Regress Puzzle, Kant's transcendental methodology had to be reconstructed on empirical-psychological premises. As part of this argument, Fries developed a subtle and original account of the importance of psychology for pure philosophy, and of the proper relationship between the two disciplines, that remains of interest. |
Data storage technology focuses on providing the greatest capacity and availability, with the greatest performance, at a minimum cost. RAID technology increased the capacity of data storage systems for minimal cost by combining multiple independent, inexpensive hard disk drives into a large array. Later RAID technology increased data availability by adding fault tolerance at the expense of capacity and performance.
State of the art data storage systems are beginning to incorporate solid state drive (SSD) technology. SSDs are arrays of semiconductor memory elements, so every memory element is accessible with electrical signals as opposed to a hard disk drive which relies on mechanically spinning disks and mechanically actuated arms. SSDs are orders of magnitude faster than hard disk drives. SSDs are also more expensive than hard disk drives per unit of data storage.
Some data storage technologies have attempted to combine the performance of SSDs with the high capacity per unit cost of hard disk drives, but the high disparity in performance tends to negate the performance advantage of SSDs for any operation that accesses the hard disk drive.
Any data storage system attempting to incorporate multiple tiers of data storage devices to take advantage of the performance characteristics of each device will necessarily lose all of those performance advantages whenever the system performs an operation involving the slowest tier, such as a write operation. To provide data integrity, redundant fields are added, wasting capacity of faster, more expensive tiers, and slowing performance because of redundant write operations.
Consequently, it would be advantageous if a method and apparatus existed that are suitable for minimizing performance slowing operations and redundant capacity usage in a system having more than one storage tier, each storage tier having superior performance characteristics as compared to the previous tier. |
/**
* If enabled, it ensures that the FileIO's hadoop configuration will not be serialized.
* This might be desirable for decreasing the overall size of serialized table objects.
*
* Note: Skipping FileIO config serialization in this fashion might in turn necessitate calling
* {@link #checkAndSetIoConfig(Configuration, Table)} on the deserializer-side to enable subsequent use of the FileIO.
*
* @param config Configuration to set for FileIO in a transient manner, if enabled
* @param table The Iceberg table object
*/
public static void checkAndSkipIoConfigSerialization(Configuration config, Table table) {
if (table != null && config.getBoolean(InputFormatConfig.CONFIG_SERIALIZATION_DISABLED,
InputFormatConfig.CONFIG_SERIALIZATION_DISABLED_DEFAULT) && table.io() instanceof HadoopConfigurable) {
((HadoopConfigurable) table.io()).serializeConfWith(conf -> new NonSerializingConfig(config)::get);
}
} |
#!/usr/bin/env python
from __future__ import print_function
import sys
import math
DEBUG = '-d' in sys.argv
def debug(*args, **kwargs):
if DEBUG:
print(*args, file=sys.stderr, **kwargs)
return None
t = int(input().strip())
lst = []
for pos in range(t):
lst += [list(map(int, input().strip().split(" ")))]
# print(t, lst)
for case in range(len(lst)):
a, b = lst[case][0], lst[case][1]
if math.gcd(a, b) == 1:
print("Finite")
else:
print("Infinite")
|
Porous nanotube networks of SnO2/MoO3@Graphene as anodes for rechargeable lithium-ion batteries We successfully fabricated composite porous nanotube networks of SnO2/MoO3@Graphene through electrospinning and used it as lithium-ion battery anodes. When the ratio of SnO2 to MoO3 is 1:1, the composite of SnO2/MoO3 delivers a high capacity of 560 mAh g−1 at 1 A g−1 after 300 cycles. The excellent electrochemical performance was attributed to the unique 3D porous nanotube network structure which could provide more transmission channels for Li+ ions and electrons, and provide more electrochemical reaction sites. The hybrid nanostructure can also weaken local stress and relieve volume expansion which contributes to the attractive cycling stability. Moreover, we added a small amount of graphene in the composite to improve the electrical conductivity, and the SnO2/MoO3@Graphene composite showed favorable electrochemical performance (798 mAh g−1 at 1 A g−1 after 300 cycles). Finally, electrospinning technology is a simple and efficient synthesis strategy, which can promote the preparation of different types of metal oxide composite materials and has good application prospects. |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Skip-Thoughts model for learning sentence vectors.
The model is based on the paper:
"Skip-Thought Vectors"
<NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>.
https://papers.nips.cc/paper/5950-skip-thought-vectors.pdf
Layer normalization is applied based on the paper:
"Layer Normalization"
<NAME>, <NAME>, <NAME>
https://arxiv.org/abs/1607.06450
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from .ops import gru_cell
from .ops import input_ops
def random_orthonormal_initializer(shape, dtype=tf.float32,
partition_info=None): # pylint: disable=unused-argument
"""Variable initializer that produces a random orthonormal matrix."""
if len(shape) != 2 or shape[0] != shape[1]:
raise ValueError("Expecting square shape, got %s" % shape)
_, u, _ = tf.svd(tf.random_normal(shape, dtype=dtype), full_matrices=True)
return u
class SkipThoughtsModel(object):
"""Skip-thoughts model."""
def __init__(self, config, mode="train", input_reader=None):
"""Basic setup. The actual TensorFlow graph is constructed in build().
Args:
config: Object containing configuration parameters.
mode: "train", "eval" or "encode".
input_reader: Subclass of tf.ReaderBase for reading the input serialized
tf.Example protocol buffers. Defaults to TFRecordReader.
Raises:
ValueError: If mode is invalid.
"""
if mode not in ["train", "eval", "encode"]:
raise ValueError("Unrecognized mode: %s" % mode)
self.config = config
self.mode = mode
self.reader = input_reader if input_reader else tf.TFRecordReader()
# Initializer used for non-recurrent weights.
self.uniform_initializer = tf.random_uniform_initializer(
minval=-self.config.uniform_init_scale,
maxval=self.config.uniform_init_scale)
# Input sentences represented as sequences of word ids. "encode" is the
# source sentence, "decode_pre" is the previous sentence and "decode_post"
# is the next sentence.
# Each is an int64 Tensor with shape [batch_size, padded_length].
self.encode_ids = None
self.decode_pre_ids = None
self.decode_post_ids = None
# Boolean masks distinguishing real words (1) from padded words (0).
# Each is an int32 Tensor with shape [batch_size, padded_length].
self.encode_mask = None
self.decode_pre_mask = None
self.decode_post_mask = None
# Input sentences represented as sequences of word embeddings.
# Each is a float32 Tensor with shape [batch_size, padded_length, emb_dim].
self.encode_emb = None
self.decode_pre_emb = None
self.decode_post_emb = None
# The output from the sentence encoder.
# A float32 Tensor with shape [batch_size, num_gru_units].
self.thought_vectors = None
# The cross entropy losses and corresponding weights of the decoders. Used
# for evaluation.
self.target_cross_entropy_losses = []
self.target_cross_entropy_loss_weights = []
# The total loss to optimize.
self.total_loss = None
def build_inputs(self):
"""Builds the ops for reading input data.
Outputs:
self.encode_ids
self.decode_pre_ids
self.decode_post_ids
self.encode_mask
self.decode_pre_mask
self.decode_post_mask
"""
if self.mode == "encode":
# Word embeddings are fed from an external vocabulary which has possibly
# been expanded (see vocabulary_expansion.py).
encode_ids = None
decode_pre_ids = None
decode_post_ids = None
encode_mask = tf.placeholder(tf.int8, (None, None), name="encode_mask")
decode_pre_mask = None
decode_post_mask = None
else:
# Prefetch serialized tf.Example protos.
input_queue = input_ops.prefetch_input_data(
self.reader,
self.config.input_file_pattern,
shuffle=self.config.shuffle_input_data,
capacity=self.config.input_queue_capacity,
num_reader_threads=self.config.num_input_reader_threads)
# Deserialize a batch.
serialized = input_queue.dequeue_many(self.config.batch_size)
encode, decode_pre, decode_post = input_ops.parse_example_batch(
serialized)
encode_ids = encode.ids
decode_pre_ids = decode_pre.ids
decode_post_ids = decode_post.ids
encode_mask = encode.mask
decode_pre_mask = decode_pre.mask
decode_post_mask = decode_post.mask
self.encode_ids = encode_ids
self.decode_pre_ids = decode_pre_ids
self.decode_post_ids = decode_post_ids
self.encode_mask = encode_mask
self.decode_pre_mask = decode_pre_mask
self.decode_post_mask = decode_post_mask
def build_word_embeddings(self):
"""Builds the word embeddings.
Inputs:
self.encode_ids
self.decode_pre_ids
self.decode_post_ids
Outputs:
self.encode_emb
self.decode_pre_emb
self.decode_post_emb
"""
if self.mode == "encode":
# Word embeddings are fed from an external vocabulary which has possibly
# been expanded (see vocabulary_expansion.py).
encode_emb = tf.placeholder(tf.float32, (
None, None, self.config.word_embedding_dim), "encode_emb")
# No sequences to decode.
decode_pre_emb = None
decode_post_emb = None
else:
word_emb = tf.get_variable(
name="word_embedding",
shape=[self.config.vocab_size, self.config.word_embedding_dim],
initializer=self.uniform_initializer)
encode_emb = tf.nn.embedding_lookup(word_emb, self.encode_ids)
decode_pre_emb = tf.nn.embedding_lookup(word_emb, self.decode_pre_ids)
decode_post_emb = tf.nn.embedding_lookup(word_emb, self.decode_post_ids)
self.encode_emb = encode_emb
self.decode_pre_emb = decode_pre_emb
self.decode_post_emb = decode_post_emb
def _initialize_gru_cell(self, num_units):
"""Initializes a GRU cell.
The Variables of the GRU cell are initialized in a way that exactly matches
the skip-thoughts paper: recurrent weights are initialized from random
orthonormal matrices and non-recurrent weights are initialized from random
uniform matrices.
Args:
num_units: Number of output units.
Returns:
cell: An instance of RNNCell with variable initializers that match the
skip-thoughts paper.
"""
return gru_cell.LayerNormGRUCell(
num_units,
w_initializer=self.uniform_initializer,
u_initializer=random_orthonormal_initializer,
b_initializer=tf.constant_initializer(0.0))
def build_encoder(self):
"""Builds the sentence encoder.
Inputs:
self.encode_emb
self.encode_mask
Outputs:
self.thought_vectors
Raises:
ValueError: if config.bidirectional_encoder is True and config.encoder_dim
is odd.
"""
with tf.variable_scope("encoder") as scope:
length = tf.to_int32(tf.reduce_sum(self.encode_mask, 1), name="length")
if self.config.bidirectional_encoder:
if self.config.encoder_dim % 2:
raise ValueError(
"encoder_dim must be even when using a bidirectional encoder.")
num_units = self.config.encoder_dim // 2
cell_fw = self._initialize_gru_cell(num_units) # Forward encoder
cell_bw = self._initialize_gru_cell(num_units) # Backward encoder
_, states = tf.nn.bidirectional_dynamic_rnn(
cell_fw=cell_fw,
cell_bw=cell_bw,
inputs=self.encode_emb,
sequence_length=length,
dtype=tf.float32,
scope=scope)
thought_vectors = tf.concat(states, 1, name="thought_vectors")
else:
cell = self._initialize_gru_cell(self.config.encoder_dim)
_, state = tf.nn.dynamic_rnn(
cell=cell,
inputs=self.encode_emb,
sequence_length=length,
dtype=tf.float32,
scope=scope)
# Use an identity operation to name the Tensor in the Graph.
thought_vectors = tf.identity(state, name="thought_vectors")
self.thought_vectors = thought_vectors
def _build_decoder(self, name, embeddings, targets, mask, initial_state,
reuse_logits):
"""Builds a sentence decoder.
Args:
name: Decoder name.
embeddings: Batch of sentences to decode; a float32 Tensor with shape
[batch_size, padded_length, emb_dim].
targets: Batch of target word ids; an int64 Tensor with shape
[batch_size, padded_length].
mask: A 0/1 Tensor with shape [batch_size, padded_length].
initial_state: Initial state of the GRU. A float32 Tensor with shape
[batch_size, num_gru_cells].
reuse_logits: Whether to reuse the logits weights.
"""
# Decoder RNN.
cell = self._initialize_gru_cell(self.config.encoder_dim)
with tf.variable_scope(name) as scope:
# Add a padding word at the start of each sentence (to correspond to the
# prediction of the first word) and remove the last word.
decoder_input = tf.pad(
embeddings[:, :-1, :], [[0, 0], [1, 0], [0, 0]], name="input")
length = tf.reduce_sum(mask, 1, name="length")
decoder_output, _ = tf.nn.dynamic_rnn(
cell=cell,
inputs=decoder_input,
sequence_length=length,
initial_state=initial_state,
scope=scope)
# Stack batch vertically.
decoder_output = tf.reshape(decoder_output, [-1, self.config.encoder_dim])
targets = tf.reshape(targets, [-1])
weights = tf.to_float(tf.reshape(mask, [-1]))
# Logits.
with tf.variable_scope("logits", reuse=reuse_logits) as scope:
logits = tf.contrib.layers.fully_connected(
inputs=decoder_output,
num_outputs=self.config.vocab_size,
activation_fn=None,
weights_initializer=self.uniform_initializer,
scope=scope)
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=targets, logits=logits)
batch_loss = tf.reduce_sum(losses * weights)
tf.losses.add_loss(batch_loss)
tf.summary.scalar("losses/" + name, batch_loss)
self.target_cross_entropy_losses.append(losses)
self.target_cross_entropy_loss_weights.append(weights)
def build_decoders(self):
"""Builds the sentence decoders.
Inputs:
self.decode_pre_emb
self.decode_post_emb
self.decode_pre_ids
self.decode_post_ids
self.decode_pre_mask
self.decode_post_mask
self.thought_vectors
Outputs:
self.target_cross_entropy_losses
self.target_cross_entropy_loss_weights
"""
if self.mode != "encode":
# Pre-sentence decoder.
self._build_decoder("decoder_pre", self.decode_pre_emb,
self.decode_pre_ids, self.decode_pre_mask,
self.thought_vectors, False)
# Post-sentence decoder. Logits weights are reused.
self._build_decoder("decoder_post", self.decode_post_emb,
self.decode_post_ids, self.decode_post_mask,
self.thought_vectors, True)
def build_loss(self):
"""Builds the loss Tensor.
Outputs:
self.total_loss
"""
if self.mode != "encode":
total_loss = tf.losses.get_total_loss()
tf.summary.scalar("losses/total", total_loss)
self.total_loss = total_loss
def build_global_step(self):
"""Builds the global step Tensor.
Outputs:
self.global_step
"""
self.global_step = tf.contrib.framework.create_global_step()
def build(self):
"""Creates all ops for training, evaluation or encoding."""
self.build_inputs()
self.build_word_embeddings()
self.build_encoder()
self.build_decoders()
self.build_loss()
self.build_global_step()
|
<reponame>KashaketCompany/soulengine
// $jrsoftware: tb2k/Packages/tb2kdsgn_cb6.cpp,v 1.2 2002/11/14 18:07:19 jr Exp $
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
USEFORMNS("..\Source\TB2DsgnConverter.pas", Tb2dsgnconverter, TBConverterForm);
USEFORMNS("..\Source\TB2DsgnItemEditor.pas", Tb2dsgnitemeditor, TBItemEditForm);
USEFORMNS("..\Source\TB2DsgnConvertOptions.pas", Tb2dsgnconvertoptions, TBConvertOptionsForm);
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
// Package source.
//---------------------------------------------------------------------------
int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void*)
{
return 1;
}
//---------------------------------------------------------------------------
|
Biosynthetic Timing and Substrate Specificity for the Thiopeptide Thiomuracin. The biosynthesis of the thiopeptide thiomuracin is a well-orchestrated process involving a multitude of posttranslational modifications. We show that six Cys residues of a precursor peptide are first cyclodehydrated and oxidized to thiazoles in an ordered, but nonlinear fashion that is leader-peptide-dependent. Then four alcohols are glutamylated and converted to alkenes in a C-to-N terminal directional process that is leader-peptide-independent. Finally, two of these alkenes undergo a formal cycloaddition to form a trithiazole-substituted pyridine macrocycle. We describe here the factors that govern the substrate specificity and order of biosynthetic events that turn a ribosomal peptide into a powerful antibiotic. |
// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package split_data
import (
"fmt"
"github.com/chaos-mesh/horoscope/pkg/database"
"github.com/chaos-mesh/horoscope/pkg/keymap"
)
type (
Maps map[string]*Node
Node struct {
table *database.Table
links []*Link
}
Link struct {
node *Node
from, to string
}
)
func (n *Node) search(tableName string) *Node {
queue := make([]*Node, 0)
visited := make(map[*Node]bool)
tryPush := func(node *Node) {
if !visited[node] {
queue = append(queue, node)
visited[node] = true
}
}
drain := func() []*Node {
nodes := queue
queue = make([]*Node, 0)
return nodes
}
tryPush(n)
for len(queue) > 0 {
for _, node := range drain() {
if node.table.Name.String() == tableName {
return node
}
for _, link := range node.links {
tryPush(link.node)
}
}
}
return nil
}
func BuildMaps(db *database.Database, mapList []keymap.KeyMap, groupKey *keymap.Key) (maps Maps, err error) {
if err = checkKeymaps(db, mapList); err != nil {
return
}
maps = make(Maps)
for tableName, table := range db.BaseTables {
maps[tableName] = &Node{
table: table,
links: make([]*Link, 0),
}
}
for _, kp := range mapList {
node := maps[kp.PrimaryKey.Table]
for _, foreignKey := range kp.ForeignKeys {
otherNode := maps[foreignKey.Table]
node.links = append(node.links, &Link{
node: otherNode,
from: kp.PrimaryKey.Column,
to: foreignKey.Column,
})
otherNode.links = append(otherNode.links, &Link{
node: node,
from: foreignKey.Column,
to: kp.PrimaryKey.Column,
})
}
}
maps.autoPrune(mapList, groupKey)
return
}
func (m Maps) autoPrune(maps []keymap.KeyMap, groupKey *keymap.Key) {
if groupKey != nil {
m.prune(groupKey.Table)
}
for _, kp := range maps {
m.prune(kp.PrimaryKey.Table)
}
}
func (m Maps) prune(root string) {
if rootNode, ok := m[root]; ok {
for table := range m {
if table != rootNode.table.Name.String() && rootNode.search(table) != nil {
delete(m, table)
}
}
}
}
func checkKeymaps(db *database.Database, maps []keymap.KeyMap) error {
for _, kp := range maps {
if err := checkKey(db, kp.PrimaryKey); err != nil {
return nil
}
for _, key := range kp.ForeignKeys {
if err := checkKey(db, key); err != nil {
return nil
}
}
}
return nil
}
func checkKey(db *database.Database, key *keymap.Key) error {
if table := db.BaseTables[key.Table]; table == nil || table.ColumnsMap[key.Column] == nil {
return fmt.Errorf("key `%s` not exists", key)
}
return nil
}
|
<gh_stars>0
package ch.epfl.sweng.defensive.code.coverage;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import ch.epfl.sweng.defensive.code.coverage.CaseStudy;
import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class CaseStudyTest {
private ByteArrayOutputStream out = new ByteArrayOutputStream();
private PrintStream stdout;
@BeforeEach
public void before() {
stdout = System.out;
System.setOut(new PrintStream(out));
}
@AfterEach
public void after() {
System.setOut(stdout);
}
@Test
public void demonstrateTest() {
CaseStudy.demonstrate();
String expected = String.format("The lecturer%s", System.lineSeparator());
String obtained = out.toString();
assertEquals(obtained, expected);
}
}
|
<filename>src/datalab/notebook/notebook-command/command/utils.py
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import inspect
import time
from command.constants import (
CELL_ID,
DATA,
DISPATCH_SHELL,
EXECUTE_REQUEST,
HEADER,
HTTP_STATUS_OK,
ITEM_MAPPING,
MESSAGE,
MSG,
REPLY,
REQUEST,
RESULT,
RESULT_TABLE,
TRANSPORT_RETRY_INTERVAL,
TRANSPORT_RETRY_TIMES,
USERNAME,
)
from command.exceptions import ApiRequestException, ExecuteException
def get_bk_username():
"""
获取ws header中的用户名
"""
header = get_request_header()
return header[USERNAME]
def get_cell_id():
"""
获取ws header中的cell id
"""
header = get_request_header()
return header[CELL_ID]
def get_request_header():
"""
获取ws header
"""
frames = {}
for info in inspect.stack():
if info[3] == DISPATCH_SHELL:
frames[REQUEST] = info[0]
if info[3] == EXECUTE_REQUEST:
frames[REPLY] = info[0]
msg = frames[REQUEST].f_locals[MSG]
return msg[HEADER]
def parse_response(response, message):
"""
解析http接口返回体
:param response: 接口返回体
:param message: 接口返回失败时的提示信息
:return: 解析结果
"""
if response.status_code == HTTP_STATUS_OK:
res_json = response.json()
if not res_json[RESULT]:
raise ExecuteException("{}: {}".format(message, res_json[MESSAGE]))
return res_json[DATA]
else:
raise ApiRequestException("{}: {}".format(message, extract_error_message(response)))
def extract_error_message(response):
"""
提取http非200状态码的报错信息
:param response: 周边接口返回体
:return: 错误信息
"""
try:
message = response.json().get(MESSAGE)
except ValueError:
message = response.content
return message
def api_retry(func, task_id):
"""
添加api重试机制
:param func: 调用的api函数
:param task_id: 任务id
:return: 重试结果
"""
retry_flag, status_result = False, ""
for i in range(TRANSPORT_RETRY_TIMES):
time.sleep(TRANSPORT_RETRY_INTERVAL)
retry_flag, status_result = func(task_id)
if retry_flag:
break
return retry_flag, status_result
def transform_column_name(obj, output_type=RESULT_TABLE):
"""
转换产出物格式
:param obj: 产出物
:param output_type: 产出物类型
:return: 转换后的产出物
"""
if isinstance(obj, list):
return [transform_column_name(element, output_type) for element in obj]
elif isinstance(obj, dict):
return {ITEM_MAPPING[output_type].get(key): transform_column_name(value) for key, value in obj.items()}
else:
return obj
|
import { Scheduler } from '../Scheduler';
import { Observable, ObservableInput } from '../Observable';
export declare function timeoutWith<T>(this: Observable<T>, due: number | Date, withObservable: ObservableInput<T>, scheduler?: Scheduler): Observable<T>;
export declare function timeoutWith<T, R>(this: Observable<T>, due: number | Date, withObservable: ObservableInput<R>, scheduler?: Scheduler): Observable<T | R>;
|
This invention relates to containers and more particularly to collapsible or knock-down containers fashioned from paperboard or like stiff, foldable and resilient sheet material.
The paperboard container art is already aware of collapsible containers. For example, U.S. Pat. No. 2,943,780 issued to Bolding discloses a collapsible bottom wall construction for a container, the bottom wall formed by separate panels sliding together as in the manner of an iris aperture stop for a camera lens. Such containers exhibit the desirable feature of ease and rapidity of being erected from a collapsed condition. Another example of a collapsible container formed of paperboard or the like is illustrated in U.S. Pat. No. 2,430,755 issued to Bergstein. In that construction, unlike the construction of Bolding, the bottom forming portion is smooth and continuous.
While apparently satisfactory for the intended uses described in these patents, such constructions have not been totally satisfactory in certain applications. For example, in fast food retail outlets, which dispense greasy foodstuffs such as fried chicken, the grease will sooner or later seep or wick through the paperboard. This can result in food stains on the clothing of the purchaser or wicking onto a table top supporting the container. Accordingly, an iris aperture stop type construction, such as that of Bolding, would be unsatisfactory because of the discontinuities of the bottom wall of the container. While a bottom construction such as shown in the Bergstein patent is superior in this respect, the problem of wicking through the paperboard persists and accordingly grease stains on clothing or grease on the top of a table may result. |
<gh_stars>0
from setuptools import setup, find_packages
print("find_packages:", find_packages())
setup(
name='ck_edge_maker',
version="1.0.2",
description="A script for making spectra from the hdf5 dataset of eigenvalues and dynamical structure factors",
long_description="A script for making spectra from the hdf5 dataset of eigenvalues and dynamical structure factors",
url='https://github.com/nmdl-mizo/ck_edge_maker',
author='kiyou, nmdl-mizo',
author_email='',
license='MIT',
classifiers=[
# https://pypi.python.org/pypi?:action=list_classifiers
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Physics",
"Programming Language :: Python :: 3 :: Only",
"License :: OSI Approved :: MIT License",
],
keywords='tools',
install_requires=["numpy", "h5py", "tqdm"],
packages=find_packages(),
entry_points={
'console_scripts':[
'ck_edge_maker = ck_edge_maker.cli:main',
],
},
)
|
Pope Benedict XVI’s fourth encyclical will be released in the first half of 2013, timed to coincide with the Year of Faith.
VATICAN CITY — Pope Benedict XVI is to publish a new encyclical on faith sometime during the first six months of 2013, the Vatican has confirmed.
“The Pope is preparing a new encyclical on the subject of faith, to be published in the first half of next year, during the Year of Faith,” Vatican spokesman Father Federico Lombardi told the Register this morning.
The encyclical will be the Pope’s fourth; he has already written two encyclicals on the other two theological virtues of hope and charity. In 2006, he published Deus Caritas Est (God Is Love), followed by Spe Salvi (Saved in Hope) in 2007. Both were also related to his third “social” encyclical, Caritas in Veritate (Charity in Truth), published in 2009.
Many have, therefore, long speculated the Holy Father would address the third theological virtue of faith and, more recently, that such an encyclical would coincide with the Year of Faith.
According to a Nov. 11 article on the Italian website Vatican Insider, the encyclical is likely to focus on Easter, with a publication date expected during Lent 2013.
Quoting Vatican sources, the website says the Holy Father completed the encyclical during his summer vacation at Castel Gandolfo and is now making “finishing touches.” It says the Vatican wanted to avoid any “overlap” with the publication of the final volume of the Pope’s book Jesus of Nazareth: The Infancy Narratives, to be published Dec. 4.
Father Lombardi noted that, in August this year, Cardinal Tarcisio Bertone, the Vatican secretary of state, mentioned the likelihood of an encyclical, but it remained only a possibility, and the cardinal gave no other details.
The new encyclical will also coincide well with some major landmark anniversaries in the life of the Church: the 50th anniversary of the opening of the Second Vatican Council, the 20th anniversary of Pope John Paul II’s promulgation of the Catechism of the Catholic Church and the 1,700th anniversary of the Battle of Milvian Bridge.
At the battle, Emperor Constantine and his men had a vision of the Chi-Rho, one of the earliest symbols of Christ, with the words “Under this sign you will conquer." His victory heralded the beginning of Christian civilization in the West.
All these anniversaries took place in October this year.
It’s understood that during this Year of Faith the Pope will use the encyclical to share his reflections on what it means to be a Christian today, the role of faith in the life of man and society and the value of Christian truths. These will be linked to the “mystery” of Easter, at a time when, in many respects, the world is in crisis. |
Flower bouquet
A flower bouquet is a collection of flowers in a creative arrangement. Flower bouquets can be arranged for the decor of homes or public buildings, or may be handheld. Handheld bouquets are classified by several different popular shapes and styles, including nosegay, crescent, and cascading bouquets. Flower bouquets are often given for special occasions such as birthdays or anniversaries. They are also used extensively in weddings. Bouquets arranged in vases or planters for home decor can be arranged in either traditional or modern styles. Symbolism may be attached to the types of flowers used, according to the culture.
History
The arrangement of flowers for home or building decor has a long history throughout the world. The oldest evidence of formal arranging of bouquets in vases comes from ancient Egypt, and depictions of flower arrangements date to the Old Kingdom (~2500 BCE). The sacred lotus was often used, as were herbs, palms, irises, anemones, and narcissus.
In some cultures, ancient practises still survive today, for example in ikebana, the art of flower-arranging that comes from Japan. The oldest known book on flower-arranging is Japanese and dates from 1445. Simplicity and linear form are core features of ikebana, which has had a great influence on Western flower arranging since the late 19th century.
Flower-arranging as an art form was brought to Japan by Buddhist monks, who learned it while in China. In ancient China, flower-arranging developed into a highly refined art form, based on the principle that life is sacred, including the life of plants, therefore cut flowers were used sparingly in carefully planned arrangements. Flowers were a traditional ritual offering among Buddhists, however, and remain so.
In Europe, flower arranging as a formal art was first documented among the Dutch, who "in particular, painted wonderful informal arrangements of flowers [...] In the 18th century, arrangements were used to decorate the houses of the wealthy families and the aristocracy."
Flower symbolism is common in many cultures, and can be complex. In China, certain flowers symbolize seasons: white plum blossoms represent winter, peach and cherry blossoms represent spring, lotus represents summer, and chrysanthemums the fall.
Nosegay
The term "tussie-mussie" is sometimes used interchangeably with nosegay. A nosegay was also known as a "talking bouquet" or "flower poesy" during the Victorian era, when they became a popular gift. Traditionally, brides will also carry a small nosegay. Tussie mussies were introduced to England in the early 18th century, and were a fashionable accessory for young women by the early 19th century. A tussie mussie is a small circular bouquet like a nosegay, but carries symbolic meaning based upon the language of flowers, where particular flowers represent specific sentiments. They were commonly exchanged by lovers, who sent messages to one another based upon the flowers used in the bouquet. Traditionally, tussie mussies are arranged in a cone- or cornucopia-shaped container, made of tin or silver, with a chain attached for carrying the bouquet.
Language of flowers
Flower symbolism originated in Asia and the Middle East, where certain flowers, such as the lotus, were considered sacred, or at least to be associated with spiritual themes. This was often reflected in artwork, for example the use of bamboo in Chinese art to represent longevity and eternity. The language of flowers was introduced to England in the early 18th century by Mary Wortley, Lady Montague, whose husband was Ambassador to Turkey. By the Victorian era, almost every flower had a specific meaning attached to it. Small nosegay or "tussie mussie" bouquets might include chamomile flowers, which a woman might send to a romantic interest to tell him "Patience"; goldenrod represented indecision.
Wedding bouquets
Traditionally the bride will hold the bouquet, and the maid of honor will hold it during the ceremony. After the wedding the bride will toss it over her shoulder, and it is believed that whoever catches the bouquet is the next in line to be married. This practice may be related to the Golden Apple of Discord myth.
Wedding bouquet shapes
There are many different bridal bouquet styles from which to select. Brides typically choose the shape of their bouquets according to popular trends at the time of their wedding, however some choose bouquets which evoke another time period. While the language of flowers can contribute to a message to be conveyed about the couple, the shapes are a personal preference.
The Posy bouquet is typically round in shape and is thought of as modern due to the small size and relative simplicity of the arrangement. It is also popular for the ease of carrying and passing-off during the ceremony. It can be composed of an expensive flower, such as a rose, or can be a sampling of country flowers.
The Cascading bouquet is usually a large arrangement which tapers near the bottom. It was popularized as the arrangement of choice for the 1980s at the wedding of Lady Diana Spencer and the Prince of Wales at Westminster Abbey. It can, and is often, made up of many types of flowers and is enhanced with Baby's Breath and different types of greenery, such as ivy. This bouquet became less popular as bridal trends shifted towards simplicity, however it has found a resurgence in recent years.
The Presentation bouquet saw a surge in popularity at the turn of the twentieth century. It is most frequently composed of a long-stemmed bud, such as the Calla Lily, and is cradled in the bride's arms, rather than carried by the stems.
The following gallery shows popular bride's bouquet shapes, including cascading, hand-tied, nosegay, pomander, flower spray and Biedermeier. |
// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This file contains the implementation of the LookAt and Camera elements.
#include "kml/dom/abstractview.h"
#include "kml/base/attributes.h"
#include "kml/dom/kml_cast.h"
#include "kml/dom/serializer.h"
using kmlbase::Attributes;
namespace kmldom {
// AbstractView
void AbstractView::AddElement(const ElementPtr& element) {
if (!element) {
return;
}
if (element->IsA(Type_TimePrimitive)) {
set_gx_timeprimitive(AsTimePrimitive(element));
return;
}
Object::AddElement(element);
}
void AbstractView::Serialize(Serializer& serializer) const {
if (has_gx_timeprimitive()) {
serializer.SaveElementGroup(get_gx_timeprimitive(), Type_TimePrimitive);
}
}
void AbstractView::AcceptChildren(VisitorDriver* driver) {
Object::AcceptChildren(driver);
if (has_gx_timeprimitive()) {
driver->Visit(get_gx_timeprimitive());
}
}
// AbstractViewCommon
AbstractViewCommon::AbstractViewCommon()
: longitude_(0.0),
has_longitude_(false),
latitude_(0.0),
has_latitude_(false),
altitude_(0.0),
has_altitude_(false),
heading_(0.0),
has_heading_(false),
tilt_(0.0),
has_tilt_(false),
altitudemode_(ALTITUDEMODE_CLAMPTOGROUND),
has_altitudemode_(false),
gx_altitudemode_(GX_ALTITUDEMODE_CLAMPTOSEAFLOOR),
has_gx_altitudemode_(false) {
}
void AbstractViewCommon::AddElement(const ElementPtr& element) {
if (!element) {
return;
}
switch (element->Type()) {
case Type_longitude:
has_longitude_ = element->SetDouble(&longitude_);
break;
case Type_latitude:
has_latitude_ = element->SetDouble(&latitude_);
break;
case Type_altitude:
has_altitude_ = element->SetDouble(&altitude_);
break;
case Type_heading:
has_heading_ = element->SetDouble(&heading_);
break;
case Type_tilt:
has_tilt_ = element->SetDouble(&tilt_);
break;
case Type_altitudeMode:
has_altitudemode_ = element->SetEnum(&altitudemode_);
break;
case Type_GxAltitudeMode:
has_gx_altitudemode_ = element->SetEnum(&gx_altitudemode_);
break;
default:
AbstractView::AddElement(element);
break;
}
}
void AbstractViewCommon::SerializeBeforeR(Serializer& serializer) const {
AbstractView::Serialize(serializer);
if (has_longitude()) {
serializer.SaveFieldById(Type_longitude, get_longitude());
}
if (has_latitude()) {
serializer.SaveFieldById(Type_latitude, get_latitude());
}
if (has_altitude()) {
serializer.SaveFieldById(Type_altitude, get_altitude());
}
if (has_heading()) {
serializer.SaveFieldById(Type_heading, get_heading());
}
if (has_tilt()) {
serializer.SaveFieldById(Type_tilt, get_tilt());
}
}
void AbstractViewCommon::SerializeAfterR(Serializer& serializer) const {
if (has_altitudemode()) {
serializer.SaveEnum(Type_altitudeMode, get_altitudemode());
}
if (has_gx_altitudemode()) {
serializer.SaveEnum(Type_GxAltitudeMode, get_gx_altitudemode());
}
}
// <LookAt>
LookAt::LookAt()
: range_(0.0),
has_range_(false) {
}
void LookAt::AddElement(const ElementPtr& element) {
if (element && element->Type() == Type_range) {
has_range_ = element->SetDouble(&range_);
} else {
AbstractViewCommon::AddElement(element);
}
}
void LookAt::Serialize(Serializer& serializer) const {
ElementSerializer element_serializer(*this, serializer);
AbstractViewCommon::SerializeBeforeR(serializer);
if (has_range()) {
serializer.SaveFieldById(Type_range, get_range());
}
AbstractViewCommon::SerializeAfterR(serializer);
}
void LookAt::Accept(Visitor* visitor) {
visitor->VisitLookAt(LookAtPtr(this));
}
// <Camera>
Camera::Camera()
: roll_(0.0),
has_roll_(false) {
}
void Camera::AddElement(const ElementPtr& element) {
if (element && element->Type() == Type_roll) {
has_roll_ = element->SetDouble(&roll_);
} else {
AbstractViewCommon::AddElement(element);
}
}
void Camera::Serialize(Serializer& serializer) const {
ElementSerializer element_serializer(*this, serializer);
AbstractViewCommon::SerializeBeforeR(serializer);
if (has_roll()) {
serializer.SaveFieldById(Type_roll, get_roll());
}
AbstractViewCommon::SerializeAfterR(serializer);
}
void Camera::Accept(Visitor* visitor) {
visitor->VisitCamera(CameraPtr(this));
}
} // end namespace kmldom
|
// test if the given phrase belongs to a given token type: type = 1: lower case; type = 2: original case; OBT
public static boolean isOfType(Document tokens, ParseTree tree, ParseTreeNode node, String token, int type, String tag) throws Exception
{
String label = "";
if(type == 1)
{
label = node.label.toLowerCase();
}
else if(type == 2)
{
label = SimFunctions.lemmatize(node.label).toLowerCase();
}
Element tokenE = (Element)(tokens.getElementsByTagName(token)).item(0);
NodeList phrList = tokenE.getElementsByTagName("phrase");
for(int i = 0; i < phrList.getLength(); i++)
{
String phrText = phrList.item(i).getFirstChild().getNodeValue().trim();
if(phrText.split(" ").length == 1 && !label.contains(" "))
{
if(label.equals(phrText))
{
node.tokenType = token;
if(tag != null)
{
String attText = ((Element)phrList.item(i)).getElementsByTagName(tag).item(0).getFirstChild().getNodeValue().trim();
node.function = attText;
}
return true;
}
}
else if(phrText.split(" ").length == 1 && label.contains(" "))
{
if(label.contains(phrText+" "))
{
node.tokenType = token;
if(tag != null)
{
String attText = ((Element)phrList.item(i)).getElementsByTagName(tag).item(0).getFirstChild().getNodeValue().trim();
node.function = attText;
}
return true;
}
}
else if(phrText.contains(label))
{
if(phrText.equals(label))
{
return true;
}
String [] phrWords = phrText.split(" ");
int j = 0;
while(j < phrWords.length)
{
if(phrWords[j].equals(label))
{
break;
}
j++;
}
int index = node.wordOrder;
if((index - j > 0))
{
String wholePhrase = "";
for(int k = 0; (k<phrWords.length-1) && (tree.searchNodeByOrder(index-j+k)!=null); k++)
{
if(j == k)
{
wholePhrase += label + " ";
}
else
{
wholePhrase += tree.searchNodeByOrder(index-j+k).label + " ";
}
}
if(tree.searchNodeByOrder(index-j+phrWords.length-1)!=null)
{
wholePhrase += tree.searchNodeByOrder(index-j+phrWords.length-1).label;
}
if(wholePhrase.contains(phrText))
{
node.tokenType = token;
if(tag != null)
{
String attText = ((Element)phrList.item(i)).getElementsByTagName(tag).item(0).getFirstChild().getNodeValue().trim();
node.function = attText;
}
node.label = phrText;
for(int k = 0; k < phrWords.length; k++)
{
if(j != k)
{
if(tree.searchNodeByOrder(index-j+k) != null)
{
tree.deleteNode(tree.searchNodeByOrder(index-j+k));
}
}
}
return true;
}
}
}
}
return false;
} |
<gh_stars>1-10
from django.urls import path
from .views import DocumentListAPIView, DocumentInstanceAPIView, SectionAPIView
app_name = 'resource'
urlpatterns = [
path('', DocumentListAPIView.as_view(), name='documents_list'),
path('<int:doc_id>/',
DocumentInstanceAPIView.as_view(), name='document_sections'),
path('sections/<section_uuid>/', SectionAPIView.as_view(), name='section'),
]
|
The Cost Effectiveness of Unicompartmental versus Total Knee Arthroplasty. PURPOSE This study examines the potential cost savings for the health system and the community in a broadly accessible model through the increased utilization of UKA using robotic arm-assisted UKA vs conventional TKA. METHODS We retrospectively reviewed 240 patients where the first 120 consecutive robotic arm-assisted UKA performed during this period were matched to 120 conventional TKAs. Clinical data from the medical records and costs for procedure for each component were collected. Bivariate analyses were performed on the data to determine if there were statistically significant differences by surgery type in clinical outcomes and financial costs. RESULTS There was a significantly lower cost incurred for robotic arm-assisted UKA vs TKA with an average saving of AU$7179 per case. The operating time (86.0 min vs 75.9 min; p=0.004) was significantly higher for UKA but the length of stay was significantly lower (1.8 vs 4.8 days; p<0.001). There was a significant difference in the use of opioids between UKA compared to TKA (125.0 morphine equivalent (ME) vs 522.1 ME, p<0.001). CONCLUSION This study demonstrated that the use of robotic arm-assisted UKA rather than TKA in suitably indicated patients may realize significant cost savings. |
Monitoring and Evaluating Progress towards Universal Health Coverage in Brazil This paper is a country case study for the Universal Health Coverage Collection, organized by WHO. Mauricio Barreto and colleagues illustrates progress towards UHC and its monitoring and evaluation in Brazil. Please see later in the article for the Editors' Summary Background Brazil is a large and heterogeneous country, which has undergone rapid economic and social improvements, including changes in major social determinants of health and in the organization of the health system. Universal health coverage (UHC) is a fundamental principle of the Brazilian Unified Health System (SUS) targeted to implement the constitutional right (established by the Constitution of 1988) to health for all Brazilian citizens. Universal Health Coverage: The Policy Context Since 1988, Brazil has been making efforts to develop the SUS, aiming at providing comprehensive and universal care, at the preventive and curative level, through decentralized management and provision of health services. The SUS provides care at the primary, secondary, and tertiary levels, and promotes community participation. However, the Brazilian health system includes an intricate public-private mix, and approximately one-quarter of the Brazilian population (the wealthiest sector) is covered by private health plans. Monitoring and Evaluation for UHC The SUS has made advances in decentralized management processes, involving intermanagerial committees and negotiation mechanisms between federal, state, and municipal stakeholders for decision making on different managerial and funding aspects. The country has adopted a model of monitoring and evaluation (M&E) linked to the guidelines of the National Health Plan (NHP) to support the implementation of priority health policies. Serious efforts have been made to improve the coverage and quality of the national health databases, including the intensive use of information technologies. The expanded access and improved quality and coverage of these databases have resulted in their increased use, including for academic research. In order to analyze the evolution of selected indicators during the final years in this study we adopted a specific framework (see Text S1) that included social determinants of health and risk factors, access to the three levels of the health system (primary, secondary, and tertiary), relevant health outcomes, private insurance, and household expenditures. Progress towards UHC in Brazil Social determinants of health and risk factors. There has been a large improvement in important health determinants over the past 25 years, with the major changes occurring in less developed municipalities. Between 1991 and 2010, poverty and illiteracy rates decreased significantly, while access to water, electricity, and sanitation have increased, with an observed general reduction of inequalities between municipalities. In the same period smoking prevalence has decreased, while obesity has increased in the Brazilian population. Primary health care. All primary health care (PHC)related activities have improved in Brazil in the last decade, with coverage of the chief strategy, the Family Health Programme (FHP), greatly increasing and reaching more than 50% of the population. The increase was larger in less developed municipalities, with low coverage maintained in the more developed municipalities (Figure 1). Secondary health care. The percentage of hospital births in Brazil reached 91.8% in 2011, with the largest increase among less developed municipalities. The number of cesarean deliveries also increased, and the inequality measures among the selected indicators suggest a slight, and sometimes mixed, reduction in inequalities in secondary care. Tertiary health care. Rates of hospital admission for cardiovascular surgery increased slightly from 2008 to 2011, but the large differences between more and less developed municipalities remained unchanged. Similar trends were observed in hemodialysis and the number of kidney transplants, suggesting a global maintenance of inequality in tertiary care. Private insurance and health expenditures. The percentage of individuals ranging in age from 30 to 59 years who have private health insurance is close to 30%, reaching over 50% among wealthier individuals. Health expenditures in relation to the capacity to pay are higher but decreasing in the poorest quintiles of the population, and catastrophic health expenditures are minimal but still present, particularly in middle-income households. Health outcomes. Under-five mortality has greatly decreased in recent years, mainly in less developed municipalities, thereby reducing inequalities (Figure 2). There were significant increases in the percentage of individuals who reported a diagnosis of hypertension or diabetes, suggesting increasing access to health care. Conclusions and Recommendations The SUS has guaranteed access to free health care for the population over the last 25 years. Overall, UHC has increased at all levels of care, with some important positive trends toward equity. PHC, in particular through the expansion of the FHP, has succeeded in guaranteeing equitable coverage. FHP has demonstrated a high effectiveness and a synergistic effect with the national conditional cash transfer program (BFP). The final outcome was a marked reduction of inequalities in PHC access and utilization ; however, inequalities persist in secondary and tertiary care. The chronic underfunding of the system imposes serious limitations on the overall expansion of the SUS, particularly at the secondary and tertiary levels. In addition to ensuring adequate and sustained funding for the SUS, initiatives require support to increase access in all levels of care, and to improve the management of health services. Finally, continued monitoring of UHC indicators is recommended, with the goal of subsidizing policies to promote greater equity in health care provision and in the decrease of health determinants and risks. |
def _get_most_recent_reviews(self):
reviews_by_author = {}
for review in self._get_reviews():
if review.author in reviews_by_author:
if reviews_by_author[review.author].round < review.round:
reviews_by_author[review.author] = review
else:
reviews_by_author[review.author] = review
return reviews_by_author.values() |
The Role of the Work Station: Visibility of Ones Computer Screen to Coworkers Influences Cyberloafing Through Self-Efficacy to Hide Cyberloafing The use of the Internet at work for reasons unrelated to work, or cyberloafing, is a potentially harmful behavior for organizations. Past studies have shown cyberloafing is driven in part by characteristics of the work environment (Askew, Vandello, & Coovert, 2012). However, there remains little research on how the work environment influences cyberloafing. Here, we tested hypotheses that work station properties (and electronic monitoring) would influence cyberloafing through self-efficacy to hide cyberloafing among a sample of working adults (N = 202). We found evidence that visibility of ones computer screen influences cyberloafing through increased levels of ones self-efficacy to hide cyberloafing. In addition to the main study, we conducted a cross-validation study with a sample of Amazons Mechanical Turk workers. Using multiple data control techniques, we were able to replicate the original results, providing evidence that the effect is robust and not specific to our original sample. The investigation contributes to practice and theory in two important ways. First, this investigation identifies a novel intervention point for decreasing personal computer use at work, that is, the structuring or restructuring of the immediate work station to deter cyberloafing. Second, the results suggest an expansion to one of the major theories of cyberloafing (i.e., theory of planned behavior model of cyberloafing) to include visibility of ones computer screen as a distal antecedent, proximal to self-efficacy to hide. |
Type A botulinum toxin in the treatment of chronic facial pain associated with temporo-mandibular dysfunction. In an open-label study 41 patients suffering from the muscular form of temporo-mandibular dysfunction were treated with botulinum toxin type A injections into masticatory muscles (average of 200 U on each side) and followed for an average of 6.7 months. Eighty percent of patients improved by a mean reduction of 45% on a visual analogue pain scale. During the observation period, 17% of patients had to receive a second injection because of recurrent pain. Reversible speech and swallowing difficulties occurred in only 1 patient. These encouraging results need to be confirmed by a randomized controlled trial. |
/*
* Copyright (c) 2017 Public Library of Science
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package org.ambraproject.rhino.util;
import java.util.Date;
import java.util.Map;
import com.google.common.base.Preconditions;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.typeadapters.UtcDateTypeAdapter;
import org.hibernate.proxy.HibernateProxy;
public final class JsonAdapterUtil {
private JsonAdapterUtil() {
throw new AssertionError("Not instantiable");
}
/**
* Copy all members that aren't already present.
*
* @param source the object to copy from
* @param destination the object to copy members to
* @return {@code destination}
*/
public static JsonObject copyWithoutOverwriting(JsonObject source, JsonObject destination) {
Preconditions.checkNotNull(destination);
for (Map.Entry<String, JsonElement> fromEntry : source.entrySet()) {
String key = fromEntry.getKey();
if (!destination.has(key)) {
destination.add(key, fromEntry.getValue());
}
}
return destination;
}
/**
* Create a {@code GsonBuilder} preconfigured with utility adapters.
*
* @return a {@code GsonBuilder} object
*/
public static GsonBuilder makeGsonBuilder() {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new UtcDateTypeAdapter());
return builder;
}
/**
* If the object is a lazy-loaded HibernateProxy, force it to be replaced with its actual write-replacement. This can
* be used to work around Hibernate optimizations that disrupt Gson's automatic serialization.
* <p/>
* This may incur extra performance costs if the full object would not have otherwise been read.
*
* @param object a Hibernate model entity, which may be lazy-loaded
* @param classToken the model type
* @param <T> the model type
* @return a non-lazy-loading instance of the entity
* @see org.hibernate.proxy.HibernateProxy#writeReplace()
*/
public static <T> T forceHibernateLazyLoad(T object, Class<T> classToken) {
Preconditions.checkNotNull(classToken);
if (object instanceof HibernateProxy) {
HibernateProxy hibernateProxy = (HibernateProxy) object;
return classToken.cast(hibernateProxy.writeReplace());
}
return object;
}
}
|
Evaluation of Sublethal Toxicity of Nitrite to a Suite of Aquatic Organisms in Support of the Derivation of a Chronic Environmental Water Quality Benchmark Nitrite is a naturally-occurring inorganic compound that occurs in aquatic environments as an intermediary between nitrate and ammonia in the nitrogen cycle. It is a contaminant of potential concern resulting from anthropogenic activities in some cases. While the acute toxicity of nitrite has been characterized in previous studies, its sublethal toxicity is less understood. To determine the sublethal toxicity of nitrite on freshwater organisms, a suite of organisms was tested including: two salmonids (Oncorhynchus mykiss and O. kisutch), an alga (Pseudokirchneriella subcapitata), an aquatic macrophyte (Lemna minor), and three invertebrates (Ceriodaphnia dubia, Chironomus dilutus, and Neocloeon triangulifer). Test organisms were exposed to nitrite concentrations ranging between 0.02 and 1.28 mg/L nitrite (NO2-N). The toxicity tests were conducted according to procedures specified in standardized methods, allowing for the estimation of multiple endpoints for each test species. Species sensitivity distributions (SSDs) were generated using endpoints from the toxicity testing results, as well as data from previous studies, from which water chemistry approximated that used in the tests (i.e.,<5 mg/L chloride, an important toxicity-modifying factor for nitrite). The mayfly, N. triangulifer, was the most sensitive species, followed by the two salmonids (which represented the second and third most sensitive species), although they were not as sensitive to nitrite exposure as reported in previous studies. The fifth percentile hazard concentration (HC5) generated from the SSD could be used for derivation of regulatory benchmarks and threshold values for site-specific aquatic risk assessments. Highlights Sublethal effects of nitrite are tested with seven freshwater aquatic species. Mayfly larvae most sensitive to sublethal nitrite concentrations. Salmonids acutely sensitive to nitrite although low acute-to-chronic ratio. Toxicity data used in SSDs to generate environmental benchmark. Nitrite (NO 2 ) is an inorganic nitrogen compound which is an intermediary in the nitrification-denitrification processes of the nitrogen cycle, occurring between ammonia and nitrate. It can occur naturally as a result of the incomplete nitrification of ammonia by nitrifying aerobic bacteria or denitrification of nitrate by anaerobic bacteria, while anthropogenic inputs of nitrogen have led to increased concentrations in some surface waters. Examples of anthropogenic activities which have led to conditions of elevated nitrite include biological sewage treatment (Alleman 1985;), aquacultural wastewaters (, blasting agents at mine operations (), and fertilizers or wastes at agricultural operations (). It has been demonstrated that nitrite is more acutely toxic to aquatic organisms than ammonia and nitrate under most conditions (;Soucek and Dickinson 2011;US EPA 2010); however, the sublethal effects on aquatic organisms have been relatively understudied. Nitrite can reduce the oxygen-carrying capacity of aquatic animals through oxidation of hemoglobin and hemocyanin (), although it has not been well documented to which aquatic animals this toxic action may be of the most importance for long-term survival and growth; other modes of toxic action may exist (Soucek and Dickinson 2011). The effects of sublethal exposure to nitrite on freshwater fish, particularly salmonids, have been studied with alterations of hemoglobin status following exposure to nitrite of < 0.1 mg/L (Brown and McLeay 1975;Russo and Thurston 1977;Smith and Russo 1975;Wedemeyer and Yasutake 1978). Although reduced growth of salmonids has only been observed at nitrite concentrations orders of magnitude higher than the studies found to alter hemoglobin status (;). Thus, there is some uncertainty regarding concentrations of nitrite at which reduced salmonid growth and survival occurs. In addition, it has been demonstrated that cladocerans (US EPA 2010) and mayflies () are particularly sensitive to acute nitrite exposure, yet information is lacking on their sensitivity to longer term exposures. A recent review on toxicity of nitrite highlighted the lack of sublethal toxicity studies conducted with sensitive species, like aquatic insects, as a major data gap (). This study applied a suite of sublethal toxicity tests with fish (Order Salmoniformes), benthic aquatic insects (Orders Ephemeroptera and Diptera), a crustacean (Order Cladocera), an aquatic plant (Order Alismatales), and a green alga (Order Sphaeropleales). Water chemistry can have a significant influence on the acute toxicity of nitrite. Increases in chloride, pH, alkalinity, dissolved oxygen, bromide, hardness, and humic substances have all been shown to reduce nitrite toxicity (;). Chloride is a particularly strong modifying factor of nitrite toxicity; this has led to the introduction of chloride-dependent water quality guidelines (BC MoE 1986;). As less is known on the influence of these factors on sublethal toxicity, conducting sublethal tests with nitrite in water quality conditions representative of the site being assessed enhances the site-specific application of the results. The toxicity tests in this study were conducted using a formulated dilution water containing chloride concentrations approximating those reported during recent monitoring at a site in Northern B.C.; as the site is characterized by low chloride (i.e., < 2 mg/L), the data generated from the tests conducted as part of this study presents reflect a conservative scenario for the toxicity of nitrite. Due to the paucity of sublethal toxicity information, chronic water quality guidelines for nitrite in many jurisdictions have not been recently updated; those guidelines that have been established have used derivation approaches constrained by the lack of complete datasets (e.g., significant uncertainty factors). This study represented an opportunity to combine our data with other sublethal toxicity data to generate a statistically-robust Species Sensitivity Distribution (SSD), which could be used to derive a chronic environmental benchmark for this compound under the tested conditions. Dilution Water The formulated dilution water used in the toxicity tests was characterized by low chloride (i.e., < 2 mg/L) and high alkalinity and hardness (i.e., each 150 mg/L as CaCO 3 ), and was formulated using reagent-grade salt additions to de-ionized water (Table A9). A subsample from the dilution water used for each test was collected and measured for metals, alkalinity, sulfate, and chloride. The laboratory control water typically used for each of the sublethal toxicity tests (e.g., reconstituted moderately hard water) was also tested concurrently with the formulated dilution water control; the comparison between the standard water typically used and the formulated dilution water would ensure that the survival and growth of the aquatic organisms were not altered by a component of the formulated dilution water. Nitrite Concentrations Nitrite concentrations were established in test treatments by addition of sodium nitrite (NaNO 2 ). Seven nitrite exposure concentrations were used in each toxicity test including: 0.02, 0.04, 0.08, 0.16, 0.32, 0.64 and 1.28 mg/L NO 2 -N. The nitrite concentrations included the long-term chronic (0.02 mg/L) to well above the short-term acute (0.06 mg/L) British Columbia provincial water quality guidelines for nitrite (BC MoE 1986). Subsamples from all test concentrations were collected at test initiation, at a mid-point in new (i.e., freshly prepared solution used for renewal) and old (i.e., test solutions prior to renewal) solutions, and at test termination. Subsamples for acute tests with salmonids were collected at test initiation in the low, middle and high test concentrations. Subsamples were analyzed for nitrite using Ion Chromatography with UV detection (EPA 300.1) to ensure that target/nominal concentrations were achieved. Test Concentration and Endpoint Determination Test concentrations from the tests were calculated using analyzed nitrite concentrations; an arithmetic average of the measured values was used for the exposure concentrations. Lethal and sublethal effect concentrations (LCx, ICx) were reported in concentrations of NO 2 -N (i.e., nitrite as nitrogen) and were determined using the software program, CETIS (Version 1.9.4; Tidepool Scientific Software, McKinleyville, California, USA). Confidence limits for the point estimate endpoints can be found in Supplementary Material-Part B. The Lowest Effect Concentrations (or LECx) were calculated based on the method described in deBruyn and Elphick, with "x" representing the percent minimum significant difference (PMSD) from each test (based on a Dunnett's Comparison test). Briefly, the non-linear regression or linear interpolation model of the sublethal data was used to calculate the nitrite concentration at which a PMSD level of effect occurred. For example, if an 11% effect on biomass was the effect level that was statistically significant from the 1 3 control organism response, the nitrite concentration necessary to result in this level of inhibition is calculated (i.e., LEC11 or IC11). Toxicity Testing Toxicity test methods were selected with aquatic organisms which were regionally relevant to British Columbia. Sublethal toxicity tests were included with aquatic organisms that have been reported to have particular sensitivity to nitrite in acute exposures. The battery of toxicity tests included broad trophic level representation and employed standardized methods that have been demonstrated to be reproducible and relevant, and therefore, as a whole, would be usable for assessment of water quality according to classifications outlined in Keddy et al.. Salmonid Survival and Growth Test Larval rainbow trout (i.e., 2-6 days post swim-up) were received from Aqua Farms (Langley, BC) for testing using methods adapted from Lazorchak and Smith and Washington Department of Ecology (WDOE 2016). The method was adapted from a 7-d duration to a 14-d duration. The test volume was increased from 500 to 2000 mL at Day 7; an 80% solution renewal was conducted daily with freshly prepared test concentrations. Fry were fed freshly hatched Artemia twice daily. Endpoints from the test were dry weight (IC10, IC20 and IC50), biomass (IC10, IC20 and IC50; calculated with final dry weight divided by the initial number of organisms) and survival (LC50). The tests were considered acceptable if control survival was ≥ 90%. The 7-d test method also has an acceptability criterion of 1.5X growth increase from initiation to termination for the control fry; this was squared to 2.25X growth increase due to the doubling of the exposure duration. Additional details on the test method are provided in Supplementary Material-Part A Table A1. Acute Survival Test with Salmonids Acute lethality (96-h LC50) tests using rainbow trout (Oncorhynchus mykiss) and coho salmon (Oncorhynchus kisutch) were conducted following the Environment Canada test method (i.e., EPS 1/RM/09; Environment Canada 1990) adapted as necessary for coho salmon. Tests with rainbow trout were conducted using smaller fry (i.e., ≈0.1 g) and larger fry (i.e., ≈1.0 g) with 0.5X concentration series from 0.64 to 10.24 mg/L mg/L NO 2 -N and 0.16 to 2.56 mg/L NO 2 -N, respectively. Fry were received from Aqua Farms (Langley, BC). The acute lethality test with coho salmon used 3.5 g juveniles obtained from Northern Divine Aquafarms (Sechelt, BC). In order to accommodate the loading density requirements from the test method (i.e., 0.5 g wet weight per litre of test volume), two replicates of 25 L with five fish were employed per test concentration in the coho salmon test. Despite the increased test volume and the addition of a second replicate, the resulting loading density of this test was 0.8 g/L, which is above the Environment Canada biological test method, however, below loading densities of other acute survival methods with fish (OECD Test 203 2019). Salmonids used in the testing program were not acclimated for 14 days at the laboratory prior to testing as required by the Environment Canada biological test method. Rather, testing was conducted within a week of arrival and a concurrent reference toxicant test was conducted for the rainbow trout to ensure that the organisms were of appropriate sensitivity; no reference toxicant test was conducted with the coho salmon due to the lack of a historical reference toxicant database for this species in the laboratory. Additional details on these test methods are provided in Supplementary Material-Part A Tables A2 and A3. Chironomid Survival and Growth Test A 10-d survival and growth toxicity test using the chironomid, Chironomus dilutus, as the test species was conducted following methods that were adapted from the Environment Canada biological test method (i.e., EPS 1/RM/32; Environment Canada 1997). A small amount of clean beach sand (1 teaspoon) was placed in each test container, followed by the addition of test solutions. Water renewals were conducted on a Monday-Wednesday-Friday schedule. Endpoints from the test were survival (LC50) and dry weight (IC10, IC20 and IC50); tests were considered acceptable if ≥ 80% survival was observed in control exposures. Additional details on the test method are provided in Supplementary Material-Part A Table A4. Duckweed Growth Inhibition Test A 7-d survival and growth toxicity test with the duckweed, Lemna minor, was conducted following the Environment Canada test method (i.e., EPS 1/RM/37; Environment Canada 2007a). The test was conducted as a static-renewal test with solution renewals conducted on Days 3 and 5 of the exposure period. Endpoints from the test were the number of fronds (IC10, IC20 and IC50) and dry weight (IC10, IC20 and IC50); the tests were considered acceptable if there was an ≥ eightfold increase in the number of fronds from test initiation to termination in the control treatment. Additional details on the test method are provided in Supplementary Material-Part A Table A5. Nutrients (i.e., sodium nitrate and potassium phosphate) were added to the formulated dilution water at concentrations according to the APHA formulation recommended in the Environment Canada (2007a) test method. Ferric chloride additions were replaced by ferric sulfate to minimize chloride alteration, which is a major toxicity modifying factor for nitrite. Similarly, manganese chloride (MnCl 2 ) additions were reduced to minimize chloride addition. Other trace elements (i.e., B, Mo, Zn, Co, and Cu) were added to the water formulation as described in the Environment Canada (2007a) test method. Algal Growth Inhibition Test A 72-h algal growth inhibition test with the green alga, Pseudokirchneriella subcapitata (recently renamed Raphidocelis subcapitata), was conducted following the Environment Canada test method (i.e., EPS 1/RM/25; Environment Canada 2007b). Endpoints from the test were inhibition of cell growth (IC10, IC20 and IC50). The tests were considered acceptable if the final density of algal cells in the control treatment was at least 16 times higher than the initial density. Additional details on the test method are provided in Supplementary Material-Part A Table A6. Nutrients (i.e., sodium nitrate and potassium phosphate) were added to the formulated dilution water at concentrations recommended in the Environment Canada (2007b) method. Similar modifications made in the duckweed test solution (i.e., ferric chloride substituted with ferric sulfate and reduced MnCl 2 concentration) were made in the algal growth test solution to minimize chloride alterations to the dilution water. Mayfly Survival and Growth Test A 14-d survival and growth toxicity test with the mayfly, Neocloeon triangulifer, was conducted following methods adapted from Struewing et al.. The test was conducted in 1-L glass jars with four replicates of each test concentration and ten mayflies per replicate. No water replacements were conducted on the first three days of the test to avoid disturbance of the mayflies. Following this static period, 80% of the water was renewed thereafter on a Monday-Wednesday-Friday schedule. Endpoints of the test were dry weight (IC10, IC20 and IC50), biomass (IC10, IC20 and IC50; calculated with final dry weight divided by the initial number of organisms) and survival (LC50); the tests were considered acceptable if ≥ 80% survival is observed in control exposures. Additional details on the test method are provided in Supplementary Material-Part A Table A7. Cladoceran Survival and Reproduction Test A 6 to 8-d three brood survival and reproduction test with the cladoceran, Ceriodaphnia dubia, was conducted following the Environment Canada test method (i.e., EPS 1/RM/21, Environment Canada 2007c). Endpoints from the test were the inhibition of neonate reproduction (IC10, IC20 and IC50) and survival (LC50); the tests were considered acceptable if the control treatment had at least 80% survival and produced ≥ 15 neonates per organism. Additional details on the test method are provided in Supplementary Material-Part A Table A8. Species Sensitivity Distribution Species Sensitivity Distributions (SSDs) represent the variation in sensitivity of species to a chemical parameter by a statistical or empirical distribution function of responses for a sample of species (). The statistical distribution is then used to calculate a concentration expected to be safe to most species of interest. The Median Hazardous Concentration Affecting 5% of the species (i.e., the HC5) from the SSD was used to establish water quality guidelines and objectives, the approach suggested by the Canadian Council of Ministers of the Environment (CCME 2007). The ssdtools shiny web application was used to estimate HC5 values (BC MOECCS 2021). This application uses the R package (ssdtools version 0.2.0) to plot the toxicity data using maximum likelihood estimation (MLE). Six distributions (i.e., Gompertz, Weibull, Gaama, log-Gumbel, loglogistic and log-normal) were fitted to the toxicity data and a model averaging approach was applied with the best models to estimate an HC5 value. The best models were selected based on goodness-of-fit tests (i.e., Anderson-Darling and Akaike information criterion), as well as a visual assessment of the lower tails of the distribution, to ensure that only statistically-appropriate models were included in the derivation of the HC5. An SSD was calculated that included the data reported here for low chloride conditions of the formulated water and literature values from studies that also used low chloride concentrations (i.e., < 5.0 mg/L Cl). Values for the fathead minnow and Topeka shiner were available from Adelman et al. and for a C. dubia test from US EPA. Because C. dubia was one of the test species conducted in this study, the geometric mean of chronic values was calculated and included in the SSD. Separate SSDs were calculated using IC10 and LECx endpoint values, respectively. The provincial and federal guidance for the derivation of Water Quality Guidelines for Aquatic Life (BC MOECCS 2019; CCME, 2007) states that an EC/IC representing a no-effects threshold is the most preferred endpoint. As the LECx represents the point at which test produced a statistically distinguishable effect (deBruyn and Elphick 2013), it was considered an appropriate estimate 1 3 of the most preferred endpoint. The LECx method also allows for use of regression-based statistical data evaluation, which is preferred (BC MOECCS 2019; CCME 2007). Dilution Water The water chemistry for the dilution water used in the toxicity tests is provided in Table 1. The concentrations of major ions were approximate (i.e., within 20%) to targeted concentrations with the following exceptions: sodium and potassium concentrations were elevated in the green algae and duckweed tests due to addition of nutrients (i.e., sodium nitrate and potassium phosphate), chloride concentrations were lower in the mayfly test media in comparison to the other test waters. Test Concentrations Analyzed nitrite concentrations (reported in Supplementary Material-Part B) were within 15% of nominal concentrations in new/fresh test solutions and were stable in test solutions in most of the toxicity tests conducted and therefore average analyzed concentrations were used in effect endpoint determination. Analyzed nitrite concentrations deviated from nominal in test solutions of the duckweed, chironomid, cladoceran and mayfly tests and these deviations are described and discussed below. Concentrations of nitrite analyzed in subsamples collected from test containers prior to solution renewal (i.e., old solutions) of the Lemna minor (duckweed) test on Days 5 and 7, were slightly increased in comparison to nominal concentrations (Supplementary Material-Part B Table B5). A concentration of nitrite ranging between 0.030 and 0.052 mg/L was observed in the old solutions of the control treatments (both dilution water and laboratory control water) indicating that the duckweed naturally produced a small amount of nitrite. Upon correction for background, the test concentrations in Day 5 and 7 old test solutions were within 20% of nominal concentrations. Thus, low concentrations of nitrite observed in Lemna minor test solutions with no nitrite added are likely associated with the combination of the presence of excess nitrate in the test media (i.e., 44.2 mg/L as N) and the reported ability of this plant to reduce nitrate to nitrite (Joy 1969). Nitrite concentrations analyzed in new test solutions of the Chironomus dilutus test averaged 96 and 102% of nominal on Days 0 and 5-respectively (Supplementary Material-Part B Table B3). However, nitrite concentrations in old test solutions from Days 5 and 10, were substantially different than nominal concentrations. Additional investigations were undertaken to assess nitrogen compounds in chironomid tests. Nitrite concentrations were measured in the water from the test container of the control treatment (no nitrite) during the midge exposure, as well as in the overlying water from other control Toxicity Test Results Results of the reference toxicant tests conducted during the testing program fell within the range for organism performance of the mean ± two standard deviations, based on historical results obtained by the laboratory with these tests. Thus, the sensitivity of the organisms used in these tests was appropriate. The control performance met the requirements of the test methods in all cases. Results from the toxicity tests conducted as part of this study are summarized in Table 2 and described as follow: Survival and Growth Test with Rainbow Trout No reductions in growth or survival of rainbow trout were observed, except for the highest test concentration of 1.25 mg/L (as N), which resulted in a 20% reduction in survival after 14 days in comparison to the control treatment groups. Biomass (which incorporates both growth and survival) resulted in the most sensitive effect concentrations. An IC10 for biomass was estimated at 0.71 mg/L NO 2 -N. A 10.4% reduction in biomass was determined to be the PMSD and, therefore, an IC10.4 estimated at 0.72 mg/L NO 2 -N was determined to be the LECx for this test. Detailed results of Acute Lethality Tests with Salmonids Results from the acute lethality tests with rainbow trout and coho salmon conducted with nitrite resulted in 96-h LC50s ranging from 1.14 to 2.75 mg/L NO 2 -N. Smaller rainbow trout had higher LC50s than larger rainbow trout. The 96-h LC50s were similar for juvenile coho salmon and rainbow trout. Detailed results of the toxicity test are presented in Supplementary Material-Part B Table B2. Chironomid Survival and Growth No reduction in C. dilutus survival was observed after 10 days in any of the tested nitrite concentrations (Supplementary Material-Part B Table B4). Growth of the chironomids (i.e., dry weights of larvae) was also unimpaired with no statistically different growth in nitrite concentrations from between 0.018 and 1.28 mg/L NO 2 -N in comparison to the control treatment. Duckweed Growth Inhibition Test No significant inhibition of frond growth was observed in the 7-d exposure at any of the nitrite concentrations (Supplementary Material-Part B Table B5). The dry weight of the fronds was also not reduced. Therefore, the IC10s and IC50s are greater than the highest nitrite concentration of the test (i.e., 1.29 mg/L NO 2 -N). Algal Growth Inhibition Test No reduction in cell yield was observed in the nitrite concentrations tested; both the 72-h IC10 and IC50 endpoints were > 1.37 mg/L NO 2 -N (Supplementary Material-Part B Table B6). Mayfly Survival and Growth Test Reduced mayfly survival was determined in test concentrations of 0.064 mg/L NO 2 -N and above; the 14-d LC50 was estimated at 0.091 mg/L NO 2 -N. Growth (dry weight) of the mayfly was not significantly reduced at concentrations lower than 0.139 mg/L NO 2 -N, demonstrating that survival was a more sensitive endpoint than growth. Biomass was the most sensitive endpoint, with an IC10 estimated at 0.039 mg/L NO 2 -N. A 36.6% reduction in biomass was determined to be the PMSD and, therefore, an IC36.6 estimated at 0.059 mg/L NO 2 -N was determined to be the LECx for this test (Supplementary Material-Part B Table B7). Cladoceran Survival and Reproduction Test No survival of C. dubia was observed in the highest concentration tested (1.24 mg/L NO 2 -N) and the 6-d LC50 was estimated at 0.76 mg/L NO 2 -N. Reduced reproduction of C. dubia was also observed to occur in a dose-dependent manner with a 10% reduction (IC10) in reproduction estimated at 0.10 mg/L NO 2 -N. As a 16.4% reduction in reproduction was determined to be the PMSD (based on a Dunnett's Comparison test), an IC16.4 would represent the point at which significant reduction in reproduction occurred; this was estimated at 0.136 mg/L NO 2 -N, representing the LECx for this test (Supplementary Material-Part B Table B8). Species Sensitivity Distribution The battery of toxicity tests conducted allow the dataset, in conjunction with additional data from the literature, to meet the Canadian Council of Ministers of Environment (CCME) requirements to generate a water quality benchmark through the use of an SSD (i.e., three fish species, three invertebrate species and an algae/plant) (CCME 2007). Two uncertainties associated with the salmonid toxicity data generated in the sublethal testing portion of the study needed to be addressed prior to the inclusion of these data into the SSD. First, the study determined that nitrite toxicity differed depending upon the life stage of salmonids used in the tests; significantly higher sensitivity to nitrite was observed with juvenile rainbow trout in comparison to swim-up fry rainbow trout. Because the less-sensitive life stage (i.e., fry) was used for the sublethal exposures with rainbow trout, the potential for higher sensitivity of larger rainbow trout was addressed prior to the inclusion of these data in the SSD analysis. Second, acute toxicity effect concentrations (i.e., 96-h LC50s) were determined for coho salmon, while no sublethal toxicity data were generated, due to logistical limitations (e.g., lack of available coho salmon). To address these two uncertainties, an acute-to-chronic ratio (ACR) for salmonids was generated from the acute and chronic tests conducted with rainbow trout. The salmonid ACR was calculated by dividing the acute LC50 (96-h survival: 2.75 mg/L NO 2 -N) by the sublethal IC10 (14-d biomass: 0.71 mg/L NO 2 -N) from nitrite exposures with swimup rainbow trout (0.1 g). This ACR was then applied to the 96-h nitrite LC50s for the larger rainbow trout fry (1.0 g) and coho salmon fry (3.5 g) of 1.16 mg/L and 1.14 mg/L, respectively, to establish estimates of sublethal effect thresholds for the more sensitive larger fish. The results of this calculation (i.e., 96-h LC50 salmonid ACR) for rainbow trout and coho salmon was then included in the sublethal SSD. The SSD models generated with IC10 for all species tested are presented in Fig. 1 and the HC5 estimates from the SSDs using both IC10 and LECx values are presented in Table 3. SSD models generated with this dataset determined that three models (i.e., gamma, log-normal and Weibull) fit the data well (e.g., delta AICs < 1; Supplemental Information Part B Table B9), and therefore all three were used in a model average to derive the HC5s. The HC5s for IC10 and LECx values were 0.052 and 0.064 mg/L NO 2 -N, respectively. The lower HC5 estimate resulting from the inclusion of IC10 rather than the LECx would provide a higher level of conservatism, which is of particular importance for the mayfly, whose effect concentration was close to the HC5 estimates. Discussion Organism performance in the formulated dilution water was similar to that observed in the standard laboratory control water in the majority of tests conducted, with the exception of mayfly growth, which was lower in the formulated dilution water in comparison to the laboratory control water. However, the 14-d dry weight of the mayflies from the dilution water was within a range of dry weights observed in control water historically (i.e., based on internal laboratory data) and higher than that observed in a 14-d test with the same species conducted by Soucek et al.. Overall, the use of the data produced using formulated water in this 1 3 study provides a significant increase in measured sensitivity of the aquatic organisms to nitrite under low chloride concentrations. Information on the sublethal sensitivity of aquatic organisms to exposure to nitrite derived from these toxicity tests was in the same range as the reported nitrite sensitivities from the primary literature, as follows. Ephemeroptera species, such as the mayfly, N. triangulifer, are considered to be pollution-intolerant, and mayflies have been among the most sensitive species to acute nitrite exposure (). The results from this study indicate that they are the most sensitive species to nitrite exposure that have been tested. As this species was found to be 2 to 3 times more sensitive to nitrite than any of the other species tested, additional work addressing the effects of nitrite to this species may be warranted. For example, very low chloride conditions, as in the formulated dilution water of the mayfly test (i.e., 0.22 mg/L), may exacerbate the effects of nitrite. The 6-d IC50 for C. dubia reproduction determined in this study fell within the range of IC50s reported in Dave and Nilsson and US EPA (i.e., 0.22 to 2.4 mg/L as N). In US EPA, C. dubia was the second most sensitive species tested in acute and chronic exposures to nitrite, consistent with relative sensitivities observed in the suite of tests conducted in this study. The acute LC50 for C. dilutus was estimated to be 15.6 mg/L NO 2 -N by US EPA. The concentrations employed in this study with C. dilutus were ten-fold below this acute threshold and no sublethal effect was observed. No information was previously available in the literature with respect to the sensitivity of plants and algae to nitrite; in comparison to the other aquatic organisms tested in this study, the results from the plant and algae tests characterize them as relatively insensitive to nitrite exposure, which is not surprising considering the important role of nitrogenous species as nutrients for primary producers. Salmonids have been observed to be one of the more sensitive aquatic organisms to nitrite; results from studies with salmonids were the basis for the current provincial guideline (BC MOE 1986; 0.02 mg/L NO 2 -N). The nitrite concentration which caused a reduction in rainbow trout survival and growth determined in this study (i.e., a 14-d IC20 of 1.03 mg/L NO 2 -N) was similar to the nitrite concentration which caused adverse growth effects (i.e., LOEC of 1.0 mg/L NO 2 -N) from a 28-d test with rainbow trout (). The acute tests conducted in this study indicate that coho salmon were comparable to rainbow trout in their sensitivity to nitrite. In contrast, the BC Aquatic Life Guideline for nitrite was derived from studies which identified nitrite concentrations associated with an increase in blood methemoglobin in salmonids (MetHb; the form of hemoglobin not able to carry oxygen) at nitrite concentrations that were much lower (i.e., < 0.1 mg/L as N) than the sublethal growth effect concentrations reported in this study (i.e., > 0.5 mg/L as N). In the literature, a clear connection between the observed increase of MetHb at nitrite concentrations < 0.1 mg/L (as N) and an associated reduction in the growth of salmonids is lacking. For example, no significant reduction in salmonid growth was described in the studies that originally reported increased MetHb at < 0.1 mg/L (as N) (Brown and McLeay 1975;Wedemeyer and Yasutake 1978). The lack of effects on growth at these concentrations (i.e., < 0.1 mg/L (as N) in the 14-d sublethal test conducted in the water used here further suggests there is no growth impairment to salmonids under these low nitrite concentrations. Findings from the current study provide additional evidence supporting the possible adaptation of salmonids to nitrite exposure. The rainbow trout tests conducted during this study determined acute LC50s that were only slightly higher than the sublethal growth IC20 determined from the 14-d exposure; 96-h LC50s were as low as 1.14 mg/L NO 2 -N in comparison to a 14-d IC20 of 1.03 mg/L NO 2 -N. Therefore, the data indicate a low acute-to-chronic ratio for salmonids and nitrite exposures. This is consistent with other data that show salmonids activate coping mechanisms which can reverse initial increases in MetHb due to nitrite exposure (Almendras 1987;) by reducing MetHb back to functional hemoglobin (), leading to decreasing MetHb over time, during continued nitrite exposure (Doblander and Lackner 1997;). This suggests that initial increases in %MetHb in salmonids at lower nitrite concentrations (i.e., < 0.1 mg/L as N) may be temporary, and not associated with long-term reduction in the performance of salmonids. In summary, the data generated in this study indicate a threshold for effects on long-term growth for salmonids is of a higher magnitude (i.e., > 0.1 mg/L) than the MetHb thresholds used in the derivation of the provincial guideline (i.e., < 0.1 mg/L). The HC5 values derived from the SSD models with the data from this study, together with data for water with low chloride reported in the literature, provide the basis for an environmental benchmark for long-term nitrite exposure under these conditions. As the sublethal toxicity tests were conducted with low ambient chloride, the results of the toxicity tests likely represent a conservative assessment of the effects of nitrite. Thus, the HC5s determined represent a baseline environmental benchmark which could be adjusted for use on a site-specific basis with conditions of higher chloride. Additional research may be required to assess the modification of nitrite toxicity by chloride in longterm exposures, as has been done previously for short-term exposures. |
#!/usr/bin/python3
"""
princ.py - Wrapper function to print text in color.
"""
from colorama import Fore, Style
def princ(text, color):
"Print text in color"
color_code = ""
if color == "green": color_code = Fore.GREEN
elif color == "red": color_code = Fore.RED
elif color == "blue": color_code = Fore.BLUE
elif color == "cyan": color_code = Fore.CYAN
print(color_code+text+Style.RESET_ALL)
|
The Psychological Processes Involved in the Development of a High-Quality Relation with ones Dog Background. Several studies have found an effect of pet ownership on human health and well-being. We propose that these benefits can only occur when the pet owner perceives the dog in a certain way: As having a human-like psychological functioning and experience of the world (anthropomorphism), and as part of ones identity (assimilation). These perceptions are thought to support the development of a high-quality relationship with the dog that can lead to positive effects on health and well-being. Method. Two samples of dog owners (N=136 and N=928) completed an online questionnaire assessing anthropomorphism and assimilation, and relationship satisfaction and commitment to the dog (as measures of the quality of the relationship). In addition, a set of measures to validate the new anthropomorphism and assimilation scales were assessed. Results. Anthropomorphism and assimilation were related to satisfaction and commitment in moderation and in mediation. That is, the relation between anthropomorphism and commitment was especially strong when assimilation was low, and the relation between assimilation and commitment was largely mediated by anthropomorphism. Furthermore, validating the new scales, anthropomorphism was significantly related to secondary emotions recognized in the dog, and assimilation was significantly and negatively related to self-esteem and loneliness. Conclusion. The results show that anthropomorphism and assimilation had a significant relation with satisfaction and commitment, which is in line with the notion that this psychological process is important for the development of a high-quality relationship between owner and dog. |
<reponame>AlbertoPaz/ABSA-PyTorch
# -*- coding: utf-8 -*-
# file: lcrs.py
# author: albertopaz <<EMAIL>>
# Copyright (C) 2018. All Rights Reserved.
from layers.dynamic_rnn import DynamicLSTM
from layers.attention import Attention
import torch
import torch.nn as nn
import torch.nn.functional as F
class LCRS(nn.Module):
'''
hyperparameters
lr: 0.1
L2: 1e-5
dropout: 0.5
SGD: 0.9 momentum
embeddings: GloVe 300, out-vocabulary: U(-0.1, 0.1)
bias: 0
TO DO , USE EMBED DIM INSTEAD OF HIDDEN DIM
'''
def __init__(self, embedding_matrix, opt, memory_weighter = 'no'):
super(LCRS, self).__init__()
self.opt = opt
self.memory_weighter = memory_weighter
self.embed = nn.Embedding.from_pretrained(torch.tensor(embedding_matrix, dtype=torch.float))
self.blstm_l = DynamicLSTM(opt.embed_dim, opt.hidden_dim, num_layers=1, batch_first=True, rnn_type = 'LSTM')
self.blstm_c = DynamicLSTM(opt.embed_dim, opt.hidden_dim, num_layers=1, batch_first=True, rnn_type = 'LSTM')
self.blstm_r = DynamicLSTM(opt.embed_dim, opt.hidden_dim, num_layers=1, batch_first=True, rnn_type = 'LSTM')
self.dense = nn.Linear(opt.hidden_dim*4, opt.polarities_dim)
# target to context attention
self.t2c_l_attention = Attention(opt.hidden_dim, score_function='bi_linear')
self.t2c_r_attention = Attention(opt.hidden_dim, score_function='bi_linear')
# context to target attention
self.c2t_l_attention = Attention(opt.hidden_dim, score_function='bi_linear')
self.c2t_r_attention = Attention(opt.hidden_dim, score_function='bi_linear')
def locationed_memory(self, memory_l, memory_r, x_l_len, x_c_len, x_r_len, dep_offset):
position = 'linear'
memory_len = x_l_len + x_c_len + x_r_len
# loop over samples in the batch
for i in range(memory_l.size(0)):
# Loop over memory slices
for idx in range(memory_len[i]):
aspect_start = x_l_len[i] + 1 # INCORRECT: ASSUME x_l_len = 0 THEN aspect_start = 0
aspect_end = x_l_len[i] + x_c_len[i]
if idx < aspect_start: # left locationed memory
if position == 'linear':
l = aspect_start.item() - idx
memory_l[i][idx] *= (1-float(l)/int(memory_len[i]))
elif position == 'dependency':
memory_l[i][idx] *= (1-float(dep_offset[i][idx])/int(memory_len[i]))
elif idx > aspect_end: # right locationed memory
if position == 'linear':
l = idx - aspect_end.item()
memory_r[i][idx] *= (1-float(l)/int(memory_len[i]))
elif position == 'dependency':
memory_r[i][idx] *= (1-float(dep_offset[i][idx])/int(memory_len[i]))
return memory_l, memory_r
def forward(self, inputs):
# raw indices for left, center, and right parts
x_l, x_c, x_r, dep_offset = inputs[0], inputs[1], inputs[2], inputs[3]
x_l_len = torch.sum(x_l != 0, dim=-1)
x_c_len = torch.sum(x_c != 0, dim=-1)
x_r_len = torch.sum(x_r != 0, dim=-1)
# embedding layer
x_l, x_c, x_r = self.embed(x_l), self.embed(x_c), self.embed(x_r)
# Memory module:
# ----------------------------
# left memory
if x_l_len == 0: memory_l = x_l
if x_l_len > 0 : memory_l, (_, _) = blstm_l(x_l, x_l_len)
# center memory
if x_c_len == 0: memory_c = x_c
if x_c_len > 0 : memory_c, (_, _) = blstm_c(x_c, x_c_len)
# right memory
if x_r_len == 0: memory_r = x_r
if x_r_len > 0 : memory_r, (_, _) = blstm_r(x_r, x_r_len)
# Target-Aware memory
# locationed-memory
if self.memory_weighter == 'position':
memory_l, memory_r = self.locationed_memory(memory_l, memory_r, x_l_len,
x_c_len, x_r_len, dep_offset)
# context-attended-memory
if self.memory_weighter == 'cam':
pass
# ----------------------------
# Aspect vector representation
x_c_len = torch.tensor(x_c_len, dtype=torch.float).to(self.opt.device)
v_c = torch.sum(memory_c, dim=1)
v_c = torch.div(v_c, x_c_len.view(x_c_len.size(0), 1))
# Rotatory attention:
# ----------------------------
# [1] Target2Context Attention
v_l = self.t2c_l_attention(memory_l, v_c).squeeze(dim=1) # left vector representation
v_r = self.t2c_r_attention(memory_r, v_c).squeeze(dim=1) # Right vector representation
# [2] Context2Target Attention
v_c_l = self.c2t_l_attention(memory_c, v_l).squeeze(dim=1) # Left-aware target
v_c_r = self.c2t_r_attention(memory_c, v_r).squeeze(dim=1) # Right-aware target
# ----------------------------
# sentence representation
v_s = torch.cat((v_l, v_c_l, v_c_r, v_r), dim=-1) # dim : (1, 800)
# v_s = torch.cat((v_l, v_c_l, v_c_r, v_r), dim = 0) # dim : (4, 300)
# Classifier
out = self.dense(v_s)
out = F.softmax(out, dim=-1)
return out
|
Preparative SDS-PAGE Electroelution for Rapid Purification of Alkyl Hydroperoxide Reductase from Helicobacter pylori. Background: Alkyl hydroperoxide reductase (AhpC) of Helicobacter pylori is considered as a diagnostic antigen. Therefore, this antigen can be used to detect H. pylori infection by stool immunoassays such as ELISA. The aim of this study was to simplify the AhpC protein purification procedures. Methods: For whole cell protein extraction, the bacterial cells were ruptured by octly--D glucopyranoside. The isolation and purification of AhpC protein were attempted by various techniques including ammonium sulfate precipitation, dialysis, preparative sodium dodecyl sulfate polyacrylamide gel electrophoresis (SDS-PAGE) and electroelution. Results: A simple method was used for protein purification AhpC protein. One-dimensional preparative gel electrophoresis allows a single and short purification step; the high resolution capacity of this technique leads to a high level of purity of the protein. Moreover, it avoids contamination by other non-specific proteins which often appear during protein purification by column chromatography. Conclusion: The present method is simple, rapid and makes it possible to preparate AhpC from H. pylori. Introduction Helicobacter pylori, an oxygen-sensitive microaerophilic bacterium, contains an alkyl hydroperoxide reductase homologue (AhpC) that is closer to eukaryotic peroxiredoxin than to other bacterial AhpC proteins. H. pylori AhpC is a major component of the AhpC-thioredoxin-thioredoxin reductase dependent peroxiredoxin system that catalyzes the reduction of hydroperoxides including H 2 O 2 and organic hydroperoxides, and the reduction of peroxinitrite. The AhpC protein has previously been reported as species-specific protein which is antigenically conserved. Although not identified as a peroxidase at that time, the AhpC was characterized as a homodimer of 26 kDa polypeptide chains with inter-chain disulfide linkage and the protein was also suggested to be useful as a diagnostic antigen in enzyme immunoassay (EIA) tests for detection of H. pylori infection. H. pylori express abundant levels of AhpC protein. Based on densitometric measurement of the protein bands on the gel, it has been shown that the protein constitutes more than 2% of the total protein in the wild-type cell which confirms of the results of proteome analysis which has been shown AhpC as the third most abundant protein in H. pylori. Results of another study has shown about 20-30% sequence homology between H. pylori AhpC and other bacterial AhpC, with as high as 43% sequence homology between the protein and the mammalian (human or mouse) peroxiredoxin. In addition, by immunoblotting the stool of the infected individuals, it has been shown that the 26 kDa protein antigen was present in all samples and has been suggested that this antigen is one of the major antigens of H. pylori which is released into the stool and can be considered as a diagnostic antigen which might be used in diag-nostic kit development. Furthermore, by applying comparative proteomic and immunoproteomic analysis of different H. pylori strains, AhpC has been described as a protein with potential diagnostic and therapeutic value. AhpC is among the most conserved and unique H. pylori antigens. It may also serves as a potential target for antimicrobial agents or vaccine development. In order to obtain the purified AhpC we used preparative SDS-PAGE and electroelution techniques. Although preparative SDS-PAGE and electroelution are well-described methods, they usually require appropriate apparatuses. Furthermore, this approach has not been previously reported for AhpC purification from H. pylori. Bacterial strains Five strains of H. pylori were isolated from biopsy specimens of 5 patients with gastritis. Biopsies were delivered to Laboratory of Microbiology, Faculty of Sciences, Tehran University, in transport medium. Samples were cultured immediately on selective Brucella agar containing 5% sheep blood, vancomycin (5 mg/l), trimethoprim (5 mg/l) and polymyxin B (2500 u/l). After 2-3 d of microaerobic incubation at 37 o C, single colonies were cultured on Brucella blood agar. Bacterial strains were identified as H. pylori according to microscopic observation of Gramnegative spiral bacteria and positive catalase, oxidase and urease reactions. To obtain about 7 grams of a mixed bacterial pellet, 400 plated cultures of 5 H. pylori strains were harvested in to phosphate-buffered saline (PBS) and centrifuged at 5000 g for 20 min. Bacterial pellet was stored at -20 o C until use. Protein extraction from bacteria In order to extract proteins from H. pylori, frozen cell pellets were thawed, suspended in PBS (pH 7.2) containing 1.0 mM phenylmethylsulfonyl fluoride (PMSF) (Across Organics, New Jersy, USA), 4 mM EDTA and 0.6% (w/v) octyl--D glucopyranoside (Sigma-Aldrich, St. Louis, USA) and incubated for 60 min at the ambient temperature with gentle agitation. Samples were then centrifuged at 6000 g for 15 min and the supernatant was collected. The procedure was repeated once more on the bacterial pellet. The pooled supernatants were cleared by centrifugation at 35000 g for 20 min and 50% ammonium sulfate was added to the supernatant. After overnight incubation at 4 o C, the sample was spun at 35000 g for 30 min and the pellet was suspended in 5 ml of 0.05 M Tris-HCl containing 0.145 M NaCl (Tris-saline ). Then the sample was dialyzed against the same buffer and protein assay was performed as described. SDS-PAGE One dimensional preparative and analytical SDS-PAGE were performed in a vertical slab gel unit using 12.5% separating gels and 5.0% stacking gels. The protein extract (1.5 ml) was separated by preparative SDS-PAGE (1801602.5 mm) using Tris-HCl buffer and stained with Coomassie Brilliant Blue solution . Analytical electrophoresis was also done as described above. Removal of CBB-R250 and electrophoretic elution of proteins from gel In order to extract the protein from polyacrylamide gel, the method of electrophoretic elution was applied using dialysis membrane for protein retention. Protein band with 26 kDa size was excised and cut into small fragments. Removing of CBB-R250 from the gel fragments was performed according to the described method. Briefly, destaining solution containing 50% isopropanol and 3.0% SDS was added to gel pieces in 1275 mm glass test tubes and the tubes were capped with parafilm. Tubes were placed in a 37 o C water bath set for overnight without agitation. After cooling to room temperature, the liquid was removed and the gel fragments containing the appropriate protein were used for electrophoretic elution. For electophoretic elution, gel fragments were equilibrated twice in 0.125 M Tris-HCl buffer (pH 6.8) and 2.0% solution of 2-mercaptoethanol for 15 min. A final equilibration of the gel fragments in 0.125 M Tris-HCl buffer (pH 6.8) containing 1.0% (w/v) SDS was performed. The equilibrated gel fragments were then placed in a dialysis tube with a minimum amount of tris-glycine buffer containing SDS (25 mM Tris, 192 mM glycine, and 0.1% SDS). The dialysis tubes were treated and electroelution was carried out as described by previously. Briefly, electroelution was performed at 50 V for 12 h at 4 o C in Trisglycine buffer containing 0.1% SDS (pH 8.3). At the end of electrophoretic elution, the polarity of the electrodes was changed for 60 S in order to avoid the absorption of protein on the dialysis tubes. Removal of SDS and renaturation of enzymatic activity Remove of SDS and renaturation of enzymatic activity was performed as described. Briefly, four volume of cold acetone (-20 o C) was added to the electoeluted protein and the sample was allowed to precipitate 30 min in a dry ice-ethanol bath. The tube was then centrifuged 10 min at 10,000 rpm, the acetone supernatant poured off, and the tube was inverted to drain. In order to renaturation of enzymatic activity, the acetone precipitate was allowed to dry for about 10 min and dissolved in 20 l of 6 M guanidine-HCl in dilution buffer consisted of 0.05 M Tris-HCl, 20% glycerol, 0.1 mg/ml BSA, 0.15 M Na Cl, 1 mM dithiothreitol (DTT), and 0.1 mM EDTA. The pellet was dissolved thoroughly and allowed to stand at room temperature for 15-20 min. The solution was then diluted 50-fold with dilution buffer and permitted to renaturation overnight at room temperature. AhpC enzymatic activity assay The peroxide reductase activity of AhpC was monitored with a CECIL 9000 spectrophotometer (Cambridge, England) at 25 o C by following the decease in A 340 within 12 min due to NADPH oxidation. Each assay was performed in a total volume of 1.0 ml of 50 mM potassium phosphate buffer (pH 7.0)/ 0.1 M ammonium sulfate/ 0.5 mm EDTA containing thioredoxin system, 0.5 M thioredoxin, 0.5 M thioredoxin reductase, 150 M NADPH and 1 mM H 2 O 2. Results Assuming that the total protein content of the cells is 30% on a dry weight basis, then the expected maximum protein content in 0.92 g (dry weight) of bacterial cell lysate in a volume of 25 ml PBS, pH 7.4 would be 11 mg/ml, if all of the protein content is released. In practice, the total intracellular protein, 3.5 mg/ml, was determined by complete extraction of the protein from the cells with 4.0 M sodium hydroxide. The details of protein purification are given in Table 1. The crude extract from H. pylori showed a brownish color and contained approximately 30 bands when analyzed in a CBB-R250 stained SDS-PAGE gel as shown in Fig.1, lane A. Fig. 1, lane B shows that in an analytical SDS-PAGE, the electroeluted protein migrated as a single band confirming its purity to homogeneity. Fig. 2 shows the various steps and a summary of the techniques used in the present work to purify the AhpC protein antigen to homogeneity. Discussion There has been a growing interest in stool antigen tests for detection of H. pylori. The application of polyclonal antibodies against H. pylorispecific antigens such as AhpC may increase the specificity of the EIA. Furthermore, AhpC protein has been suggested as a potential target for the development of therapeutic agents against H. pylori and anti-AhpC is useful for proteomic studies of H. pylori. H. pylori AhpC protein is typically purified using two or more chromatographic steps (3,. These protocols often involve a precipitation step, followed by an ion-exchange and/or gel filtration chromatography. Another approach is based on molecular biology tools, which involves cloning the codifying gene in order to produce the recombinant enzyme in a proper expression vector. In the present work, a different methodology was used to simplify the purification of H. pylori AhpC protein. This approach is based on preparative SDS-PAGE and electroelution. A summary of the techniques used in the present work to purify the AhpC protein has been shown in Fig. 2. The bacterial cells were first disintegrated by 0.6% octly -D-glucopyranoside as non-ionic detergent. Then, the whole cell protein extraction was carried out by various techniques including ultracentrifugation, ammonium sulfate precipitation and dialysis techniques (Fig. 2, step 1). At the end of protein extraction, the concentration and specific activity were determined to be 7.4 mg/ml and 487 U/mg protein respectively (Table 1). For the preparative SDS-PAGE, approximately four milligram of protein extract was run for about 12 h at 50 V (Fig.2, step 2). The molecular weight standard was applied in the middle well between two wide wells to determine the approximate size of protein bands. After electrophoresis, the gel was stained with CBB-R250 and destained for revealing the protein bands (Fig. 2, step 3) and the 26 kDa protein band was excised precisely, cut into pieces, (Fig. 2, step 4), and destained completely according to the described method (Fig.2, step 5). Gel pieces were subsequently dialyzed in bags previously filled with 25 mM Tris buffer containing 192 mM glycine and 0.1% SDS, pH 8.3. The appropriately identified tubing was placed in a horizontal flat bed gel electrophoresis apparatus, filled with the same buffer mentioned above. Electroelution of the protein from gel fragments was performed at 50 V (Fig. 2, step 6) for 12 h. Finally, the gel fragments were discarded and the protein concentration was determined to be 300 g per milliliter. In addition to, after remove of SDS and renaturation of enzymatic activity the Ahpc activity was measured to be 17473 U/mg protein (Table 1). In fact, analysing the specific activity of the electroeluted fraction of purification process revealed that the Ahpc was purified more than 100-fold from whole cell lysate (Table 1). Fig. 1, lane B shows that in an analytical SDS-PAGE, the electroeluted protein migrated as a single band confirming its purity to homogeneity (Fig. 2, step 8). While the AhpC protein of H. pylori has been purified by several multi-step procedures (3, the present report provides a simple method of purification. Moreover, several types of apparatus for electroelution are commercially available, but we used only electrophoretic elution using dialysis membrane for protein retention with good results. In the present study, we used a simple method to purify AhpC which avoids the long term purification of the AhpC protein. One-dimensional preparative gel electrophoresis allows a single short purification step and the high resolution of this technique leads to a high level of protein purity. Moreover, it avoids contamination by other nonspecific proteins which often appear during protein purification by column chromatographic techniques. In conclusion, the present method is simple, rapid and makes it possible to preparation AhpC from H. pylori. |
def extract_item(item_key):
def callable_(key, data, errors, context):
items = data.get(key)
if type(items) is dict:
data[key] = items.get(item_key)
return callable_ |
Quantitative Measure of Hysteresis for Memristors Through Explicit Dynamics We introduce a mathematical framework for the analysis of the input-output dynamics of externally driven memristors. We show that, under general assumptions, their dynamics comply with a Bernoulli differential equation and hence can be nonlinearly transformed into a formally solvable linear equation. The Bernoulli formalism, which applies to both charge- and flux-controlled memristors when either current- or voltage-driven, can, in some cases, lead to expressions of the output of the device as an explicit function of the input. We apply our framework to obtain analytical solutions of the i-v characteristics of the recently proposed model of the Hewlett-Packard memristor under three different drives without the need for numerical simulations. Our explicit solutions allow us to identify a dimensionless lumped parameter that combines device-specific parameters with properties of the input drive. This parameter governs the memristive behavior of the device and, consequently, the amount of hysteresis in the i-v. We proceed further by defining formally a quantitative measure for the hysteresis of the device for which we obtain explicit formulas in terms of the aforementioned parameter and we discuss the applicability of the analysis for the design and analysis of memristor devices. I. INTRODUCTION According to classical electrical circuit theory, there are three fundamental passive circuit elements: the resistor, the inductor and the capacitor. Back in 1971, Chua challenged this established perception 1. He realized that only five out of the six possible pairwise relations between the four circuit variables (current, voltage, charge and magnetic flux) had been identified. Based on a symmetry argument, he postulated mathematically the existence of a fourth basic passive circuit element that would establish the missing link between charge and magnetic flux. The postulated element was named the memristor because, unlike a conventional ohmic element, its instantaneous resistance depends on the entire history of the input (voltage or current) applied to the component 2, 3. Hence the memristor can be understood in simple terms as a non-linear resistor with memory. Chua and Kang 4,5 generalized this concept to a broader family of non-linear dynamical systems, which they termed memristive, and demonstrated their usefulness in the modeling and understanding of physical and biological systems such as discharge tubes, the thermistor, or the Hodgkin-Huxley circuit model of the neuron. Although in the intervening years experimental devices with characteristics similar to the memristor (i.e., hysteresis, zero crossing and memory) were investigated, researchers generally failed to associate or explain them in the context of memristive systems 6. The memristor remained an elusive theoretical component until recently, when scientists at Hewlett-Packard (HP) fabricated a solid-state device which was recognized as a memristor 7,8. In that work, Williams, Strukov and co-workers also provided a simple heuristic model to understand how memristive behavior could emerge from the underlying physical process. The report of the fabrication of the HP memristor reignited the interest of the community in such circuits, due to their potential widespread applications. This has resulted in various attempts to build memristor devices based on different underlying physical principles, as well as efforts to understand pre-existing devices in the context of memristive systems. Examples include thin-films 7,9-13, nano-particle assemblies 14, spintronics 15 or neurobiological systems 16,17. On the theoretical front, however, the analysis of these systems has been mostly restricted to numerics (i.e., temporal integration of model differential equations and numerical sweeping of parameters) due to the absence of a general mathematical framework that can provide analytical solutions to their dynamics. Here, we introduce a mathematical framework for the study of memristors that allows us to provide analytic solutions for their dynamics and input-output characteristics. The framework is based on the compliance of a general class of ideal memristor dynamics with Jacob Bernoulli's differential equation, a classic nonlinear equation that can be solved analytically. This formulation provides a powerful and systematic methodology for the analysis, characterization and design of devices governed by Bernoulli dynamics that does not rely on computationally expensive sweeping of parameters. Moreover, our analytical results can be used to reveal the relevant combinations of parameters that govern the response characteristics of the memristor. The paper is structured as follows. Firstly, we introduce the general theoretical framework for memristor dynamics and the analytical solutions that follow from the Bernoulli differential equation. We then illustrate its application through the HP memristor 8, which is shown to comply with the Bernoulli framework, and we obtain analytical expressions of the output of the model when excited by three fundamental inputs: sinusoidal, bipolar square and triangular waves. To exploit further the insight provided by the framework, we define a quantitative measure of the hysteresis of the memristor in terms of the work done by the driving signal, and we use the derived analytical solutions to show that the hysteresis of the device depends on a specific dimensionless lumped quantity that combines all the parameters of the model. This lumped parameter relates fabrication and device properties together with characteristics of the input signal and shows how such experimental parameters can be used to design and control the response of the memristor. A. Definitions and background Consider the four fundamental circuit variables: voltage v, current i, charge q, and magnetic flux. There are six distinct relations linking these variables pairwise. Two of these relations correspond to the definitions of charge and magnetic flux as time-integrated variables: Three other links are given by the implicit equations that define the constitutive laws of the generalized fundamental circuit elements: f C (v, q) = 0 for the capacitor, f L (, i) = 0 for the inductor. ( In order to complete the symmetry of the systemtheoretic structure, Chua's insight was to postulate that the remaining link between q and should be completed by another constitutive relation which would correspond to a missing element: the memristor. In this sense, the memristor complements the other three fundamental circuit elements as the fourth ideal passive two-terminal component 1,2,5. Assume a time-invariant memristor with no explicit dependence on time, i.e., ∂f M /∂t = 0. Then the time derivative of the constitutive relation leads to which serves us to define the memristance M(q, ) 1,2 : Since we are considering strictly passive elements, with M(q, ) > 0, the constitutive law defines a strictly monotonically increasing function in the (q, ) plane. It then follows that we can express the memristor constitutive law as an explicit function either in terms of the flux, q = q M (), or in terms of the charge, = M (q), indistinctly and to our convenience 21. Take, for instance, a current-driven memristor, in which i(t) is the time-dependent input under our control, then we can formally express the input-output relationship in terms of q, an integrated variable of the input i(t) over its past: a form that makes explicit the memory of the device. Note, in contrast, that a time-invariant resistor governed by has a differential resistance The input-output relationship of a current-driven passive resistor is then given by which is in general nonlinear but, unlike Eq., it exhibits no memory. Hence, the memory property follows from the integration necessary to go from the i − v plane, which is readily accessible to experiments, to the q − plane in which the memristor constitutive law is defined 1,3. The memristance and the resistance are thus dimensionally congruent but they only coincide if they are both constant, i.e., for the ohmic (linear and constant) resistor 1. B. Solution of memristor dynamics under time-dependent inputs: the Bernoulli equation Although the constitutive relation of the memristor is defined in the q − plane, such devices are characterized experimentally in the i − v plane. Specifically, it is typical to characterize their output dynamics in response to time-dependent inputs. The particular relationship imposed by the definition of the memristor translates into a restricted form of the differential equations that govern the dynamics in the i − v time domain. In particular, the dynamics obey a Bernoulli differential equation (BDE) that can be reduced to an associated linear timedependent differential equation (LDE). In some cases, this structure can be exploited to provide analytical solutions for the input-output dynamics without the need for explicit numerical integration of the model. The Bernoulli equation has the form 22 : where n ∈ N. If n = {0, 1}, the equation is linear. For n > 1 this family of nonlinear ODEs can be solved analytically using the nonlinear change of variable z = y 1−n to give the LDE from which the general solution follows: Here m(x) = e (1−n) f (x)dx is an integrating factor and C is the constant of integration. In the case of memristor dynamics, the mathematical transformation that relates the BDE/LDE pair is not only a convenient manipulation but is also associated with the experimental measurement setup and the intrinsic description of the memristor: both the BDE and LDE can appear depending on the choice of externallydriven variable (i or v) in conjunction with the internal variable (q or ) through which the memristive behavior is controlled. In particular, consider an experiment in which the memristor is described in terms of the integrated input, e.g., a current-driven memristor with input i(t) whose memristance is charge-controlled, M(q). The dynamical system can then be written in the canonical form of a memristive system:q This leads directly to the following LDE: which has the standard analytical solution shown in Table I. However, in certain situations, it might be more meaningful (or convenient) to express the memristance as a function of the integrated dependent variable. For instance, if the memristor is voltage-driven with input v(t) but the memristance is given in terms of the charge M(q), we have and the resulting equation is: which has a Bernoulli form. Indeed, this is the case for the first HP memristor model 8, as shown in the next section. In general, the output dynamics of the general memristor leads to four cases. Differentiating with respect to time yields If the device is current-driven, the dynamical equations are: while for the voltage-driven memristor we have: where we have emphasized in the equations the explicit dependence on time of the externally controlled drives. Note that the dynamics are formally either a BDE (Eqs. (17b) and (18b)) or a LDE (Eqs. (17a) and (18a)), which are related through the nonlinear transformation given above. For strictly passive memristors 1,4 (for which M(q), or equivalently M(), is always positive), the memristance can be represented as a function of either the independent or dependent variable, as convenient, due to the existence of the inverse function 21. Therefore, once we specify the intrinsic integrated variable (i.e., q or ) that controls the specific memristor, we can obtain BDEs and LDEs as summarized in Table I with their corresponding general solutions. The above discussion shows that the constitutive relationship of the memristor leads generally to Bernoulli dynamics which can be reduced to the corresponding timevarying linear dynamics through a nonlinear transformation. The analytical solutions obtained can be used to understand explicitly the parameter dependence of memristor models as well as to aid in the design process without the need for parameter sweeping via numerical simulations of the dynamics. In particular, we obtain below analytical expressions for the behavior of a memristor model when driven with different input waveforms. Furthermore, our analytical solutions allow us to show that the behavior of the system is fully characterized by a particular lumped parameter that incorporates all the physical parameters of the memristor. This renormalized parameter is shown to encapsulate both the hysteretic and nonlinear characteristics of the device and its memristive character. C. Dynamics of the HP memristor under time-varying inputs We exemplify our approach with the HP model, which was introduced by Strukov et al. to describe the behavior of their fabricated memristor 8. Their device consists of a thin-film semiconductor of TiO 2 with thickness D placed between two metal contacts made of Pt. The film has two regions: a doped region of thickness w with low resistivity R ON due to the high concentration of dopants (positive oxygen ions) and an undoped region with thickness (D − w) and high resistivity R OF F. The total resistance of the film is modeled as two variable resistors in series whose resistance depends on the position of the boundary between the doped and undoped regions. Applying an external voltage across the device will have the effect of moving the boundary between the doped and undoped region effectively changing the total resistance of the device. Assuming ohmic electronic conductance and linear ionic drift with average vacancy mobility v, the device is modeled by the following pair of equations 8 : Equation means that the position of the boundary between regions is proportional to the total charge that passes through the device. Hence Eq. is a memristor relationship of the form given in Eq. with memristance controlled by charge 23 : When the device is voltage-driven (as is the case in the original model 8 ) the dynamics is governed by Eq.. A simple inspection of Table I shows that the solution of the corresponding BDE leads to an i − v relationship with the following explicit form: where the constant of integration R 0 ∈ is the resistance of the device at t 0, the initial time at which the input signal is applied. We can use the explicit solution to calculate the output response of the HP memristor to different voltage drives. Here, we will study periodic input signals v(t) with period T 0 = 2/ 0, amplitude A, and zero mean value, 1 T0 T0 0 v( )d = 0. Such inputs are standard test signals for electronic devices and lead to the classic characterization of the memristor through hysteresis and Lissajous-type i − v curves 1. In particular, we consider three test signals widely used in engineering settings, namely, the sinusoidal, bipolar piece-wise linear and triangular waveforms, all defined over a period 0 < t ≤ T 0 as follows: (i) Sinusoidal voltage input: (ii) Bipolar piece-wise linear wave: (iii) Triangular wave: For the bipolar piece-wise linear wave, the parameter 0 < m ≤ 1/4 determines the rise and fall time, assumed equal here. In particular, m = 0 corresponds to the (Heaviside) square wave, while m = 1/4 is the triangular wave. The three input waveforms are shown in Figs. 1a-1c. It is convenient to normalize the i − v characteristics in terms of rescaled variables: a normalized time (or phase): to give where we have defined, a positive dimensionless quantity which combines the parameters of the device and of the input drive: Note that the renormalized parameter includes material and fabrication properties of the device ( v, R ON, R OF F, D); parameters dependent on the preparation of the state of the device (R 0 ); as well as properties of the driving signal (A, 0 ). We will show below that the memristive behavior of the device is fully encapsulated by the parameter. Using the solution, the response to inputs - over a period 0 ≤ x ≤ 2 is: (i) Sinusoidal voltage input: (ii) Bipolar piece-wise linear wave: Figure 1 shows the response of the HP memristor for different values of under the three periodic inputs shown in Figures 1a-1c. Figures 1d-1f show the (nonlinear) output current from the HP memristor for three values of, with the more positive values having a larger deviation from the linear output from an ohmic (linear) resistor with resistance R 0 (dashed black lines). The response dynamics give rise to Lissajous-type i − v characteristics, which are typical of memristors when driven by a periodic excitation with zero mean value 1. In such cases, the output is a double-valued function that forms a simple closed curve with no self intersections except at the origin. Equivalently, this corresponds to a hysteresis loop crossing the origin in the i − v plane 4,5. As our results show, the amount of hysteresis in the device is dependent on, which changes as a combination of different experimental factors. Figures 1g-1i illustrate the effect of on the i − v characteristics: the hysteretic behavior of the device is enhanced for the most positive values of. Again, the dashed black line is the limiting case when the memristor tends to a linear resistor R 0, which corresponds to the limiting case of = 0. Our analysis above shows that the dynamical response of the HP memristor is governed by the lumped parameter. This dimensionless parameter represents in a single quantity the collective effect of device parameters of diverse origin including: material properties, such as carrier mobility and doping ratio (R ON, R OF F, v ); device fabrication, such as the depth of the thin-film layer (D); preparation of the initial state of the device (R 0 ); as well as properties of the driving input (A, 0 ). Therefore, one does not need to consider each individual parameter separately-our analytical expressions show that similar responses can be achieved by changing different properties of the device if they lead to the same value of. Furthermore, for a given fabricated device one can tune the properties of the input drive in the experiment to produce particular output responses. We now examine some of the characteristics of the parameter. From the definition, it follows that > 0 since R OF F > R ON. As → 0, the memristor tends to the behavior of a linear resistor with historydependent resistance R 0. Hence, for a given fabricated device with particular physical characteristics, the linear behavior will be revealed experimentally in the limit of low amplitude/high frequency drive (A → 0 and/or 0 → ∞). In the process of designing memristors, linear behavior will be more likely when the dimension of the device is large (D → ∞); when the mobility of the carriers is low ( v → 0); when the doping ratio is small (R ON /R OF F → 1), or with a combination of all of those. In fact, note that ≡ 0 when R ON = R OF F. This corresponds to building an ohmic resistor, rather than a memristor, with just one (undoped) region. In this case, the resistor always responds linearly with the same unique resistance independently of history or preparation protocol, i.e., R 0 = R OF F. In the case of the HP model, the value of is also bounded from above, as follows from requiring that the arguments in the square roots in Eqs. - be positive, so that the output current is real and finite. This leads to the following bounds for for each type of input: for v(t) = ∧(t). In order to make the comparison across input drives more direct, it is thus helpful to define the following rescaled parameter: such that ∈ for all three drives. When = 0, the memristor becomes a linear resistor, while as → 1, the HP memristor becomes maximally nonlinear and hysteretic and the separation of the two branches in the i − v plane is maximized. In the next section, we make this notion more precise through the introduction of a quantitative measure of hysteresis. It should be noted that the upper bound of, that stems from the requirement that the output remains real and finite, is a manifestation of a limitation of the first simplified HP memristor model 8, i.e., that the device does not saturate or break down as the memristance is driven towards its lower bound R ON. Although such a mechanism is not accounted for by Eqns. and, this limitation has already been addressed by models that contain a windowing function, in which it becomes increasingly difficult to change the memristance as the boundary between the doped and undoped region reaches either of the two ends of the device 8,24,25. A. Definition Controlling and designing the hysteretic pinch of the i − v curve of the memristor is crucial for the use of these devices both individually or as part of larger circuits. It is important, therefore, to have a method to control the hysteretic effect of a particular model in order to achieve the required specifications for an application. We propose here a quantitative measure of the hysteresis of the i − v curve in terms of the work carried out by the driving input on the device. We will then use the analytical solutions obtained for the HP model in the previous section to calculate the hysteresis of the model for the three different drives in terms of the parameter. Finally, we will show how these expressions may be used as an aid to fabricate a memristor with a prescribed i − v curve. Our measure of hysteresis is based on the calculation of the work done by the input signal through the device. Let H denote the positive scalar quantity measuring the difference between the work done while traversing the upper and lower branches of the hysteresis loop in the i − v plane: where t 1 to t 2 and t 2 to t 3 is the time required to move along the upper and lower branch of the hysteresis loop, respectively. Here, P (t) = i(t)v(t) is the instantaneous power and, as it is customary by now, H corresponds to the rescaled quantity. Clearly, H is defined in terms of the energy dissipated by the device and becomes zero when the memristor tends to a linear resistor since W + and W − coincide in that case. Therefore, it is useful to scale the hysteresis by W 0, the work done on the linear resistor R 0 when driven for one complete cycle by the same signal for which H is evaluated: We define the scaled hysteresis as: B. Analytical expressions for the hysteresis of the HP memristor We now use our analytical results for the HP model to obtain the hysteresis of this device under the three drives specified in the previous section. Sinusoidal drive: Consider an HP memristor with sinusoidal input v(t) = (t) and the corresponding output current i, given by Eq.. The hysteresis H is then: The work done by the input signal (t) for a complete cycle on the linear resistor R 0 is: Using the symmetry of the functions, the scaled hystere-sisH is given by: which can be rewritten as 26,27 : where k 2 = −1 and 2 = arcsin 1− 2−. Here, F (, k) and E(, k) are the incomplete elliptic integrals of the first and second kind, respectively, while K(k) and E(k) denote the complete elliptic integrals of the first and second kind, respectively 26,27. Bipolar piecewise linear input After some algebra, the scaled hysteresis of the bipolar input waveform v(t) = ⊓(t) is obtained as 27 : where m = 1 − 2m. 42)). The hysteresis curves achieve finite maximaHmax at = 1. For a given lumped parameter (e.g., 0 = 0.9), we can obtain the hysteresis of the memristor when driven by any of the three inputs studied in Fig. 1. The corresponding i − v characteristics of the HP model with 0 = 0.9 are shown in (b). Conversely, one can evaluate the hysteresis from i − v curves, obtained either theoretically or experimentally, and determine the corresponding. Triangular wave input The hysteresis for the triangular wave input v(t) = ∧(t) is obtained by particularizing Eq. for m = 1/4: C. The dependence of the hysteresis on the parameter The definition of hysteresis is based on the integration of the instantaneous power consumed by the device over the course of an input cycle. Figure 2 shows a plot of the instantaneous power for the HP model driven by the bipolar wave ⊓(t). Each of the areas w 1 to w 4 indicate the work done by the input signal for the corresponding time interval. The hysteresis is given by H = (w 2 + w 3 ) − (w 1 + w 4 ) where W + = w 2 + w 3 and W − = w 1 + w 4. Note that w 2 = w 3 = w 1 = w 4. This asymmetry is a reflection of the difference in the work carried out on each of the two branches of the i − v curve due to the nonlinearity of the device and giving rise to the hysteresis. The expressions of the memristor hysteresis subject to the three drives given by Eqs. - are all explicit functions of, the lumped parameter that combines the physical parameters of the device together with the properties of the drive. Figure 3a shows that for all drives, the hysteresis of the device is zero when = 0 and increases as → 1. It is important to remark that the device has a finite maximum value of hysteresis it can exhibit, i.e., the value ofH does not diverge as → 1. In fact, we can use our analytical expressions to calculate the upper bound of the hysteresis for each drive. For instance, from Eq. the maximum hysteresis for the HP memristor driven by a sinusoidal input is: while for the triangular input, the upper bound of the hysteresis is slightly lower: Therefore, the maximum hysteresis exhibited by the HP memristor, understood as the difference between the work along the upper and lower branches of the i − v over a period of the input, is equivalent to ∼ 50% of the energy dissipated by the equivalent ohmic resistor. The dependence of the hysteresis on the lumped parameter can be used during the design process of a memristor or during the characterization of a fabricated device. If the aim is to design a memristor with a prespecified i − v response that needs to operate under a particular input, one may calculate first the hysteresis H of the desired i − v curve and the value of that will produce the desired response. The identified value can then be used to restrict our fabrication parameters. Similarly, for a given fabricated memristor, one can generate different i − v characteristics under a particular type of drive with varying frequency and/or amplitude, and/or under a different type of drive. For each i − v curve, the scaled hysteresisH can be obtained from the experimental data. If the data is well described by the HP model, our expressions could be used to fit some of the intrinsic parameters of the device that are contained in. The interplay between hysteresis and is exemplified in Fig. 3b for the i − v curves generated by a memristor with 0 = 0.9 under the three input drives. IV. DISCUSSION In this paper, we have presented a mathematical framework for the analysis of the input-output dynamics of memristors. Although these are nonlinear elements, the form of the constitutive relation of the memristor leads in general to Bernoulli dynamics, which can be directly linked to an associated linear differential equation through a nonlinear transformation. Table I highlights this general form of memristor dynamics and the duality that emerges when devices with distinct internal control variables are interrogated with different externally controlled variables, i.e., charge-and flux-controlled memristances which can be voltage-and current-driven. Our methodology allows us to obtain, in some cases, the output of the device as an explicit function of the input. We exemplified our analysis with the recently introduced HP memristor model 8, which is shown to be a Bernoulli memristor, for which we obtain analytically the output current explicitly as a function of the voltage for three typical input signals, namely, the sinusoidal, bipolar piecewise linear and triangular waveforms. Our analysis led us to the identification of the dimensionless lumped parameter, which combines physical parameters of the device as well as properties of the input drive, and controls the hysteretic properties of the i − v characteristics. We have shown elsewhere 28 that the same parameter also quantifies the amount of nonlinearity in the output spectrum of the device. Consequently, controls both the hysteresis of the memristor and the harmonic distortion that the device introduces. The functional form makes apparent how controls the memristive character of the device and reveals the fundamental interlinking between nonlinearity, hysteresis and memory in these devices. The explicit solutions thus obtained can be of use not only for the understanding of memristive dynamics but also as a means to parameterize experiments and to study the deviation from idealized models. They can also be used to devise experiments that can reveal the memristive properties of particular devices. For instance, it is possible to use to design an input drive (e.g., its functional form, amplitude and frequency) that will enhance the hysteretic response of a particular memristor, dependent on the physical properties of the device and the underlying transport mechanism of the charge carriers. The parameter also indicates which fabrication parameters are likely to enhance (or reduce) memristive behavior. In the HP model, the small dimensions of the device, a large carrier mobility, and large differences between the doped and undoped resistances all contribute to make the memristive behavior more conspicuous. The results presented could be applicable to experiments given that the simple HP model studied here has already been shown to provide a reasonable approximation of the behavior of particular experimental realizations 29. Although we have focused here on particular examples, this analytical approach has been extended to other memristor models 30. Furthermore, equivalent analytical input-output relations can be obtained for networks of memristors and other mem-elements connected to circuit parasitics 28. The study of such directions as well as the investigation of more realistic memristor models (in particular those that account for non-linear dopant kinetics) will be the object of further research. |
/**
* A helper class to define a needed method invocation replacement in an efficient way.
*/
protected class MethodReplacement extends AbstractReplacement
{
final String matchingClassName;
final String matchingMethodName;
final String matchingMethodDesc;
final String replacementClassName;
final String replacementMethodName;
final String replacementMethodDesc;
final StringMatcher classNameMatcher;
final StringMatcher methodNameMatcher;
final StringMatcher descMatcher;
MethodReplacement(String className, String methodName, String methodDesc,
String replacementClassName, String replacementMethodName, String replacementMethodDesc)
{
this.matchingClassName = className;
this.matchingMethodName = methodName;
this.matchingMethodDesc = methodDesc;
this.replacementClassName = replacementClassName;
this.replacementMethodName = replacementMethodName;
this.replacementMethodDesc = replacementMethodDesc;
classNameMatcher = new ClassNameParser(null).parse(matchingClassName);
methodNameMatcher = new NameParser(null).parse(matchingMethodName);
descMatcher = matchingMethodDesc.equals("**") ?
new ConstantMatcher(true) :
new ClassNameParser(null).parse(matchingMethodDesc);
}
private boolean isValid()
{
return replacementClassName.contains("*") ||
replacementClassName.contains("<1>") ||
findReferencedClass(replacementClassName) != null;
}
private String getDescReplacement(String original, String actual, String replacement)
{
if (matchingMethodName.equals("<default>"))
{
// Extend the replacement descriptor.
String replacedDesc = getReplacement(original, actual, replacement);
return "(" + ClassUtil.internalTypeFromClassName(matchingClassName) + replacedDesc.substring(1);
}
else
{
return getReplacement(original, actual, replacement);
}
}
boolean matches(Clazz clazz, RefConstant methodrefConstant)
{
String className = methodrefConstant.getClassName(clazz);
String methodName = methodrefConstant.getName(clazz);
String methodDesc = methodrefConstant.getType(clazz);
// Get the referenced class for the matching className.
// Might be null for wildcard classNames.
Clazz referencedMatchingClass = findReferencedClass(matchingClassName);
Clazz referencedClass = methodrefConstant.referencedClass;
if (referencedClass == null)
{
// Might happen if the project is not setup correctly.
// The class to be replaced is not present.
return false;
}
Member referencedMember = methodrefConstant.referencedMember;
if (referencedMember == null)
{
// Might happen if the project is not setup correctly.
// The method to be replaced is not present.
return false;
}
return classPatternMatches(className, referencedClass, referencedMatchingClass) &&
methodPatternMatches(methodName, referencedClass, referencedMember) &&
descPatternMatches(methodDesc);
}
private boolean classPatternMatches(String className, Clazz referencedClazz, Clazz referencedMatchingClass)
{
return classNameMatcher.matches(className) ||
(referencedClazz != null && referencedClazz.extendsOrImplements(referencedMatchingClass));
}
private boolean methodPatternMatches(String methodName, Clazz referencedClass, Member referencedMember)
{
return methodNameMatcher.matches(methodName) ||
// or the method is a default method and the pattern matches all default methods
(matchingMethodName.equals("<default>") && isDefaultMethod(referencedClass, referencedMember)) ||
// or the method is static and the pattern matches all static methods
(matchingMethodName.equals("<static>") && isStatic(referencedMember));
}
private boolean descPatternMatches(String methodDesc)
{
return descMatcher.matches(methodDesc);
}
void replaceInstruction(int offset, Clazz clazz, Method method, RefConstant refConstant)
{
String className =
getReplacement(matchingClassName, refConstant.getClassName(clazz), replacementClassName);
String methodName =
getReplacement(matchingMethodName, refConstant.getName(clazz), replacementMethodName);
String methodDesc =
getDescReplacement(matchingMethodDesc, refConstant.getType(clazz), replacementMethodDesc);
methodDesc = replaceDescriptor(clazz, methodDesc);
Clazz referencedClass = findReferencedClass(className);
if (referencedClass == null)
{
// Might happen if the project is not setup correctly.
// The class to be replaced is not present.
return;
}
Method referencedMethod = findReferencedMethod(referencedClass,
methodName,
methodDesc);
if (referencedMethod == null)
{
warningPrinter.print(clazz.getName(),
className,
String.format("Warning: could not find replacement method '%s.%s(%s)',\n" +
" not converting method instruction at offset %d " +
"in method '%s.%s(%s)'.",
ClassUtil.externalClassName(className),
methodName,
ClassUtil.externalMethodArguments(methodDesc),
offset,
ClassUtil.externalClassName(clazz.getName()),
method.getName(clazz),
ClassUtil.externalMethodArguments(method.getDescriptor(clazz))));
return;
}
boolean isInterfaceMethod = isInterface(referencedClass);
byte replacementInstructionOpcode = isStatic(referencedMethod) ?
InstructionConstants.OP_INVOKESTATIC :
isInterfaceMethod ?
InstructionConstants.OP_INVOKEINTERFACE :
InstructionConstants.OP_INVOKEVIRTUAL;
int methodConstant =
isInterfaceMethod ?
constantPoolEditor.addInterfaceMethodrefConstant(className,
methodName,
methodDesc,
referencedClass,
referencedMethod) :
constantPoolEditor.addMethodrefConstant(className,
methodName,
methodDesc,
referencedClass,
referencedMethod);
codeAttributeEditor.replaceInstruction(offset,
new ConstantInstruction(replacementInstructionOpcode,
methodConstant));
if (DEBUG)
{
System.out.println(String.format("Replacing instruction at offset %d: %s.%s%s -> %s.%s%s",
offset,
refConstant.getClassName(clazz),
refConstant.getName(clazz),
refConstant.getType(clazz),
className,
methodName,
methodDesc));
}
}
} |
Inefficacy of Piracetam in the Prevention of Painful Crises in Children and Adolescents with Sickle Cell Disease Analgesia and hydration remain the only safe treatment for painful crises of sickle cell disease; hydroxyurea is effective, but the toxicity is still a problem. Piracetam is a nootropic drug that has reportedly been effective and non-toxic in sickle cell patients, but most studies were not placebo-controlled and included a small number of patients. The present study evaluated the drug in a double-blind crossed placebo-controlled clinical trial in 73 children and adolescents suffering from moderate to severe painful crises for 13 months. Information regarding frequency and severity of pain was acquired through monthly clinical evaluation, visits and house calls, and 4,300 weekly questionnaires filled out by the patients in their domiciles. A monthly pain score was calculated for each patient. Pain was the most frequent adverse manifestation of the disease stressing its significant bio-psycho-social impact. Although nearly all patients and relatives reported a better clinical course throughout the whole study, the drug was ineffective in the prevention of painful crises. This placebo effect may be ascribed to an unplanned and unsystematic cognitive-behavioural management of the children. The pain score in the second semester of the study both in the experimental and in the control groups was significantly smaller than that in the first semester. In conclusion, piracetam was found to be ineffective in the prevention of painful crises; a powerful placebo effect due to adequate patient care was demonstrated. |
/**
* the class handling the animations and
* actions and the jwidgets for a svg picture
*
* @author Jordi SUC
*/
public class SVGPictureAnimActionsHandler {
/**
* the name of the attribute allowing to specify the name of the server IP address
*/
public static String serverAddressName="serverIPAddress";
/**
* the svg picture to which the animations and actions handler is associated
*/
private SVGPicture picture;
/**
* the file of the project into which the svg file is inserted
*/
private File projectFile;
/**
* the path of the view in the xml database
*/
private String viewPath;
/**
* the right level for this picture
*/
private int rightLevel=0;
/**
* the IP address of the server that should update tags
*/
private String serverIPAddress="";
/**
* whether the animations have been added
*/
private boolean animationsAdded=false;
/**
* the data changed listeners
*/
protected final List<DataChangedListener> dataChangedListeners=
new CopyOnWriteArrayList<DataChangedListener>();
/**
* the jwidget animations
*/
protected final List<JWidgetAnimation> jwidgetAnimations=
new CopyOnWriteArrayList<JWidgetAnimation>();
/**
* the actions
*/
protected final List<fr.itris.glips.rtda.animaction.Action> actions=
new CopyOnWriteArrayList<fr.itris.glips.rtda.animaction.Action>();
/**
* the map associating an element to a jwidget runtime object
*/
protected final Map<Element, JWidgetRuntime> elementToJWidgetRuntime=
new ConcurrentHashMap<Element, JWidgetRuntime>();
/**
* the list of blinking value modifiers, that handle the blinking colors
* in the canvas that are not inside an animation node
*/
protected final List<BlinkingValueModifier> blinkingValueModifiers=
new CopyOnWriteArrayList<BlinkingValueModifier>();
/**
* the constructor of the class
* @param picture a svg picture
*/
public SVGPictureAnimActionsHandler(SVGPicture picture){
this.picture=picture;
//setting the project file
try{
projectFile=AnimationsToolkit.getProjectFile(new URI(picture.getUri()), false);
}catch (Exception ex){ex.printStackTrace();}
}
/**
* initializes the animations and actions handler
*/
protected void initialize(){
//getting the configuration document corresponding to this picture
ConfigurationDocument confDoc=
picture.mainDisplay.getPictureManager().getConfigurationDocument(picture);
if(confDoc!=null){
rightLevel=confDoc.getAuthorizationLevelForView(viewPath);
//getting the IP address of the server that should update tags
serverIPAddress=confDoc.getRootElement().getAttribute("serverIPAddress");
}
//getting the view path of this view
viewPath=picture.mainDisplay.getPictureManager().
getViewXMLPath(getProjectName(), picture.uri);
}
/**
* builds the animations, the actions and the jwidgets linked to the canvas
*/
public void buildAnimActionsJwidgets(){
Document document=picture.doc;
if(document!=null){
DataChangedListener dataChangedListener=null;
fr.itris.glips.rtda.animaction.Action action=null;
Element cur=null;
Node node=null;
//for each node of the svg file, tests if it an animation node,
//and if this is such a case, creates a new data changed listener, an action or a jwidget
for(NodeIterator it=new NodeIterator(
document.getDocumentElement()); it.hasNext();){
node=it.next();
if(node!=null && node instanceof Element) {
cur=(Element)node;
if(cur.getNodeName().startsWith(AnimationsToolkit.rtdaPrefix)){
if(cur.getNodeName().equals(JWidgetRuntime.jwidgetTagName)) {
createJWidgetRuntime(cur);
}else if(! elementToJWidgetRuntime.containsKey(cur.getParentNode())) {
if(ListenerActionBuilder.isAnimationNodeSupported(cur.getNodeName())){
//getting the listener
dataChangedListener=ListenerActionBuilder.
createDataChangedListener(picture, cur);
if(dataChangedListener!=null){
dataChangedListeners.add(dataChangedListener);
}
}else if(ListenerActionBuilder.isActionNode(cur.getNodeName())) {
action=ListenerActionBuilder.createAction(
picture, getProjectName(), picture.getCanvas(), cur.getParentNode(), cur);
if(action!=null) {
actions.add(action);
}
}
}else {
createJWidgetAnimActions(cur);
}
}else{
//creating the blinking value modifiers that handle the blinking colors
//in the canvas that are not inside an animation node
blinkingValueModifiers.addAll(
picture.mainDisplay.getColorsAndBlinkingsToolkit().
getNotInAnimationsNodeBlinkingValueModifiers(
cur, picture, getProjectFile()));
}
}
}
}
}
/**
* creates the jwidget runtime associated to and element
* @param jwidgetElement a jwidget element
*/
protected void createJWidgetRuntime(Element jwidgetElement){
//creating the jwidget runtime object
JWidgetRuntime jwidgetRuntime=picture.mainDisplay.getJwidgetRuntimeManager().
createJWidgetRuntime(picture, jwidgetElement);
if(jwidgetRuntime!=null) {
elementToJWidgetRuntime.put(
(Element)jwidgetElement.getParentNode(), jwidgetRuntime);
jwidgetRuntime.initialize();
}
}
/**
* creates the animation or the action of a jwidget
* corresponding to the provided element
* @param element an animation or action element
*/
protected void createJWidgetAnimActions(Element element){
//as the action or the animation belongs to a jwidget runtime object, the corresponding
//jwidget runtime object is retrieved
JWidgetRuntime jwidgetRuntime=
elementToJWidgetRuntime.get(element.getParentNode());
if(jwidgetRuntime!=null) {
//checking if the node matches an animation
JWidgetAnimation anim=JWidgetRuntimeManager.
createAnimation(jwidgetRuntime, element);
Action action=null;
if(anim!=null){
jwidgetAnimations.add(anim);
}else{
//the action is created
action=JWidgetRuntimeManager.createAction(jwidgetRuntime, element);
if(action!=null) {
actions.add(action);
}
}
}
}
/**
* destroys the animations listeners of the canvas
*/
public void destroyAnimations(){
//disposing the animations
for(ListenerAction anim : dataChangedListeners){
if(anim!=null){
anim.dispose();
}
}
for(JWidgetAnimation anim : jwidgetAnimations){
anim.dispose();
}
//disposing the actions
for(Action action : actions){
action.dispose();
}
//clearing the collections and maps
dataChangedListeners.clear();
jwidgetAnimations.clear();
actions.clear();
elementToJWidgetRuntime.clear();
blinkingValueModifiers.clear();
//removes the colors and blinkings maps associated with the canvas
picture.mainDisplay.getColorsAndBlinkingsToolkit().removeColorsAndBlinkings(
getProjectName());
ActionsLoader.removeClasses(getProjectName());
}
/**
* initializes the animations and actions once the canvas is displayed
* and before calls to the <code>dataChanged(DataEvent evt)</code> method
*/
protected void initAnimActionsOnceCanvasVisible() {
//handling the jwidgets
for(JWidgetRuntime jwidgetRuntime : elementToJWidgetRuntime.values()){
if(jwidgetRuntime!=null){
jwidgetRuntime.initializeWhenCanvasDisplayed();
}
}
//handling the animations
for(ListenerAction listener : dataChangedListeners) {
if(listener!=null) {
listener.initializeWhenCanvasDisplayed();
}
}
//handling the jwidget animations
for(JWidgetAnimation anim : jwidgetAnimations) {
if(anim!=null) {
anim.initializeWhenCanvasDisplayed();
}
}
//handling the actions
for(fr.itris.glips.rtda.animaction.Action action : actions) {
if(action!=null) {
action.initializeWhenCanvasDisplayed();
}
}
}
/**
* registers the animations and actions in the animations handler
*/
protected void addAnimationsActions() {
if(! animationsAdded){
for(JWidgetRuntime jwidgetRuntime : elementToJWidgetRuntime.values()){
if(jwidgetRuntime!=null && jwidgetRuntime.requiresListening()){
picture.mainDisplay.getAnimationsHandler().registerListenerOrAction(
serverIPAddress, jwidgetRuntime);
}
}
//adding the data changed listeners
for(ListenerAction listener : dataChangedListeners) {
if(listener!=null) {
picture.mainDisplay.getAnimationsHandler().registerListenerOrAction(
serverIPAddress, listener);
}
}
//adding the jwidget animations
for(JWidgetAnimation anim : jwidgetAnimations) {
if(anim!=null) {
picture.mainDisplay.getAnimationsHandler().registerListenerOrAction(
serverIPAddress, anim);
}
}
//adding the actions
for(fr.itris.glips.rtda.animaction.Action action : actions) {
if(action!=null) {
picture.mainDisplay.getAnimationsHandler().registerListenerOrAction(
serverIPAddress, action);
}
}
//adding the blinking value modifiers to the blinkings handler
picture.mainDisplay.getAnimationsHandler().getBlinkingsHandler().
addBlinkingValueModifiers(blinkingValueModifiers);
//loading this view//
//getting the project name corresponding to the picture
String projectName=getProjectName();
if(projectName!=null && ! projectName.equals("")) {
picture.mainDisplay.getAnimationsHandler().loadView(viewPath, serverIPAddress);
}
if(picture.getMainDisplay().getAnimationsHandler().isTestVersion()){
//refreshing all the tag values
picture.mainDisplay.getAnimationsHandler().refreshAllTags();
}
//refreshing the state of the jwidget runtime objects
for(JWidgetRuntime jwidgetRuntime : elementToJWidgetRuntime.values()){
if(jwidgetRuntime!=null){
jwidgetRuntime.refreshComponentState();
}
}
synchronized (this) {
animationsAdded=true;
}
}
}
/**
* unregisters the animations and actions from the animations handler
*/
public void unregistersAnimationsActions() {
if(animationsAdded){
//unloading this view//
//getting the project name corresponding to the picture
String projectName=getProjectName();
if(projectName!=null && ! projectName.equals("")) {
picture.mainDisplay.getAnimationsHandler().unLoadView(
viewPath, serverIPAddress);
}
//removing the jwidget runtime objects
for(JWidgetRuntime jwidgetRuntime : elementToJWidgetRuntime.values()){
if(jwidgetRuntime!=null && jwidgetRuntime.requiresListening()){
picture.mainDisplay.getAnimationsHandler().unregistersListenerOrAction(
serverIPAddress, jwidgetRuntime);
}
}
//removing the data changed listeners
for(DataChangedListener listener : dataChangedListeners){
if(listener!=null){
picture.mainDisplay.getAnimationsHandler().
unregistersListenerOrAction(serverIPAddress, listener);
picture.getMainDisplay().getAnimationsHandler().
getInvalidityNotifier().unregisterListener(listener);
}
}
//removing the jwidget animation
for(JWidgetAnimation anim : jwidgetAnimations) {
if(anim!=null) {
picture.mainDisplay.getAnimationsHandler().
unregistersListenerOrAction(serverIPAddress, anim);
}
}
//removing the actions
for(fr.itris.glips.rtda.animaction.Action action : actions) {
if(action!=null) {
picture.mainDisplay.getAnimationsHandler().
unregistersListenerOrAction(serverIPAddress, action);
}
}
//removing the blinking value modifiers
picture.mainDisplay.getAnimationsHandler().getBlinkingsHandler().
removeBlinkingValueModifiers(blinkingValueModifiers);
//refreshing the state of the jwidget runtime objects
for(JWidgetRuntime jwidgetRuntime : elementToJWidgetRuntime.values()){
if(jwidgetRuntime!=null){
jwidgetRuntime.refreshComponentState();
}
}
synchronized (this) {
animationsAdded=false;
}
}
}
/**
* @return whether the picture can be displayed
*/
public boolean isEntitled(){
return (picture.mainDisplay.getUserRights().
getRightForViewLoading()>=rightLevel);
}
/**
* @return the ip address of the server
*/
public String getServerIPAddress() {
return serverIPAddress;
}
/**
* @return the project name
*/
public String getProjectName() {
return Toolkit.getFileName(projectFile);
}
/**
* @return the project file
*/
public File getProjectFile() {
return projectFile;
}
/**
* @return the map associating an element to a jwidget runtime
*/
public Map<Element, JWidgetRuntime> getElementToJWidgetRuntime() {
return elementToJWidgetRuntime;
}
/**
* disposes this handler
*/
public void dispose(){
//removing the animations
unregistersAnimationsActions();
//destroying the jwidget runtime objects
for(JWidgetRuntime jwidgetRuntime : elementToJWidgetRuntime.values()) {
jwidgetRuntime.dispose();
picture.mainDisplay.getJwidgetRuntimeManager().
removeJWidgetRuntimeObject(jwidgetRuntime);
}
//destroying the animations
destroyAnimations();
}
/**
* @return the view path
*/
public String getViewPath() {
return viewPath;
}
} |
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
__all__ = ['HFF_k_matrix', 'mse_EucDistance', 'sklearn_kt_regressor', 'glmnet_kt_regressor']
# Cell
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
from sklearn.metrics import pairwise_kernels, mean_squared_error
from sklearn.preprocessing import Normalizer
from sklearn.linear_model import Lasso
import glmnet_python; from glmnet import glmnet; from glmnetPredict import glmnetPredict
# Cell
def HFF_k_matrix(fml = None,
fm = np.array([]),
kernel='laplacian',
num_meas_array = np.array([]),
varMs = np.array([])
):
""" Function to generate a kernelized matrix. The kernel used
defaults to laplacian (manhattan distance).
___Parameters___
>__fml__ : ndarray of shape (n_examples, n_features)
>- dictionary of reference measurements/observations with format of
> [num_runs * n_types of measurements]x[measurements/features]
>
>__fm__ : ndarray of shape (n_examples, n_features), optional
>- set of measurements/observations of same format as fml
>
>__kernel__ : str, default = 'laplacian'
>- This determines kernel - see scikit-learn's pairwise kernels
> function. Values typically used here are 'rbf' and 'laplacian'
> with other values including [‘additive_chi2’, ‘chi2’, ‘linear’,
> ‘poly’, ‘polynomial’, ‘sigmoid’, ‘cosine’]
>
>__num_meas_array__ : ndarray of shape (n_types of measurements,), default = np.array([])
>- numpy array that provides the number of each type of measurements
> (112ea TDOA, 16ea RSS, 8ea AoA is np.array([112,16,8])). Note
> that if single total number or empty array of measurements
> then defaults to simply pairwise_kernel for entire dictionary.
>
>__varMs__ : ndarray of shape (n_types of measurements,), default = np.array([])
>- scale factor for kernel/similarity measurement of each
> measurement type. It can be related to variance of each
> measurement type.
__Returns__
>returns a kernel matrix (k_matrix)
"""
#initialize some values and check entries
if (np.size(num_meas_array) != np.size(varMs)):
raise ValueError("Number of scales,{:d}, doesn't match number of feature types, {:d}".format(np.size(num_meas_array),np.size(varMs)))
#check to see if 'new' measurements, if not, use reference measurements only
if fm.size == 0:
fm = fml
#if number of measurements is not passed, then only one type of measurements
if num_meas_array.size == 0:
num_meas_array = np.array([np.size(fml.shape[1])])
#if none passed, set all scales to one
if varMs.size == 0:
varMs = np.ones(num_meas_array.size)
#basic parameter settings
num_features = len(num_meas_array);
idx = np.cumsum(num_meas_array)
#calculate kernel matrix
#calculate kernel matrix for first measurement type
k_matrix = pairwise_kernels(fm[:,0:idx[0]],fml[:,0:idx[0]],
metric = kernel,
gamma = varMs[0])
#loop through rest of measurement types, calculate kernels and concatenate them
for m in np.arange(num_features-1):
k_matrix = np.hstack((k_matrix, pairwise_kernels(fm[:,idx[m]:idx[m+1]],fml[:,idx[m]:idx[m+1]],
metric = kernel,
gamma = varMs[m+1])
))
return k_matrix
# Cell
def mse_EucDistance(yV, yVhat):
"""Scoring function to calculate the mean physical distance error of
estimated location versus the actual location. This is the mean
Euclidean distance error
__Parameters__
>__y__ : ndarray of shape (n_obs, n_dims)
>- Each row is a actual location with colums being cartesian coordinates
> 2D or 3D.
>
>__yhat__ : ndarray of shape (n_obs, n_dims)
>- Each row is a estimated location with colums being cartesian
> coordinates 2D or 3D.
__Returns__
>__mse__ : float
>- Mean euclidean distance error
"""
diff = yV-yVhat
diff_sq = np.multiply(diff,diff)
mse = np.average(np.sqrt(np.sum(diff_sq,axis=1)))
return mse
# Cell
class sklearn_kt_regressor(BaseEstimator):
"""
This is kernel trick regressor model class based on Sci-Kit Learn's
base estimator class. Estimator wraps any passed SKLearn model along
with kernel parameters which allows leveraging SKLearn tools and
methods for optimizing and tuning kernel trick models.
__Parameters__
>__skl_model__ : SKLearn estimator object, default = Lasso()
>- Typical models used are Ridge() and Lasso() for regression
>
>__skl_kernel__ : str, default = 'laplacian'
>- This determines kernel used in kernel trick - see scikit-learn's
> pairwise kernels function. Values typically used here are 'rbf'
> and 'laplacian' with other values including [‘additive_chi2’,
> ‘chi2’, ‘linear’, ‘poly’, ‘polynomial’, ‘sigmoid’, ‘cosine’]
>
>__n_kernels__ : integer, default = 1
>- Number of kenerls concatenated together in kernel trick
>
>__kernel_s1-s3__ : float, default = 1e-3, None, None
>- Kernel scales applied to each of the `skl_kernel`s. The total
> number of kernels deteremined by `kernel_scales`
>
>__n_meas_array__ : integer ndarray, default = np.array([])
>- ndarray that provides the number of each type of measurements
> (112ea TDOA, 16ea RSS, 8ea AoA is np.array([112,16,8])). Note
> that if one measurement then defaults to simply pairwise_kernel
> for entire dictionary.
"""
def __init__(self, skl_model=Lasso(), skl_kernel='laplacian', n_kernels=1,
kernel_s0 = 1e-3, kernel_s1 = None, kernel_s2 = None,
n_meas_array=np.array([])):
self.skl_model = skl_model
self.skl_kernel = skl_kernel
self.n_kernels = n_kernels
self.kernel_s0 = kernel_s0
self.kernel_s1 = kernel_s1
self.kernel_s2 = kernel_s2
self.n_meas_array = n_meas_array
def fit(self, X, y):
"""
Kernelizes passed data and then fits data according to passed
model. Function inherits all attributes and features of
SKLearn's base esimator class as well as passed model. As part
of fit process, feature data is kernelized (based on instance
kernel parameter) and normalized -- should parameterize
normalization or functionalize both together outside `fit`.
__Parameters__
> __X__ : ndarray of shape (n_samples, n_features)
>- Training data
>
> __y__ : ndarray of shape (n_samples, spatial dimensions)
>- Response data (location of Tx for each sample set
> of measurements)
__Returns__
> Self, sets self.X_, self.Y_
"""
# Check that X and y have correct shape
X, y = check_X_y(X, y, multi_output=True)
# Check that number of kernels and number of kernel scales is same
if self.n_kernels != len(self.n_meas_array):
raise ValueError("n_kernels is not same as number of n_meas_array")
# Check that number of each measurement types is correct
if sum(self.n_meas_array) != X.shape[1]:
raise ValueError("Sum of n_meas_array is not same as number of features in X")
#put kernel scales together (reset in case called multiple times)
kernel_scales = np.array([self.kernel_s0])
for i in range(1,self.n_kernels):
kernel_scales = np.append(kernel_scales,self.get_params()["kernel_s"+str(i)])
# Generate kernelized matrix for fit input
X_kernel = HFF_k_matrix(fml=X, kernel=self.skl_kernel,
num_meas_array=self.n_meas_array,
varMs=kernel_scales)
#normalize
X_kernel = Normalizer().fit_transform(X_kernel)
# Fit
self.skl_model.fit(X_kernel, y)
# Store X,y seen during fit
self.X_ = X
self.y_ = y
# Return the regressor
return self
def predict(self, X):
"""
Applies pair-wise kernel between observed with fitted data. The
predicts based on fitted model. As part of predict process,
feature data is kernelized (based on instance kernel parameter)
and normalized -- should parameterize normalization or
functionalize both together outside `predict`.
__Parameters__
> __X__ : ndarray of shape (n_samples, n_features)
>- Sample data used for predictions
>
__Returns__
> Estimated target(s)
"""
# Check is fit had been called
check_is_fitted(self)
# Input validation
X = check_array(X)
#put kernel scales together (reset in case called multiple times)
kernel_scales = np.array([self.kernel_s0])
for i in range(1,self.n_kernels):
kernel_scales = np.append(kernel_scales,self.get_params()["kernel_s"+str(i)])
#kernelize input
X_kernel = HFF_k_matrix(fml=self.X_, fm=X,
kernel=self.skl_kernel,
num_meas_array=self.n_meas_array,
varMs=kernel_scales)
#normalize
X_kernel = Normalizer().fit_transform(X_kernel)
#predict and return
return self.skl_model.predict(X_kernel)
# Cell
class glmnet_kt_regressor(BaseEstimator):
"""
This is kernel trick regressor model class based on Sci-Kit Learn's
base estimator class. Estimator wraps a GLMnet model along
with kernel parameters which allows leveraging SKLearn tools and
methods for optimizing and tuning kernel trick models.
See [Glmnet Vignette](https://glmnet-python.readthedocs.io/en/latest/glmnet_vignette.html)
for indepth information on GLMnet model.
__Parameters__
>__glm_alpha__ : float, default = 1
>- glmnet elasticnet parameter where
> - 0 is Ridge regressino
> - 1 is Lasso
> - (0,1) is ElasticNet
>
>__lambdau__ : float, default = 1e-3
>- lambda for penalty (aka alpha in SKLearn). Note that this is
> converted to an ndarray internally due GLMnet accepting an
> array of lambda's. **This is not supported with this wrapper!**
>
>__skl_kernel__ : str, default = 'laplacian'
>- This determines kernel used in kernel trick - see scikit-learn's
> pairwise kernels function. Values typically used here are 'rbf'
> and 'laplacian' with other values including [‘additive_chi2’,
> ‘chi2’, ‘linear’, ‘poly’, ‘polynomial’, ‘sigmoid’, ‘cosine’]
>
>__n_kernels__ : integer, default = 1
>- Number of kenerls concatenated together in kernel trick
>
>__kernel_scales__ : integer ndarray, default = np.array([])
>- Kernel scales applied to each of the `skl_kernel`. The total
> number of kernels deteremined by `kernel_scales`
>
>__n_meas_array__ : integer ndarray, default = np.array([])
>- ndarray that provides the number of each type of measurements
> (112ea TDOA, 16ea RSS, 8ea AoA is np.array([112,16,8])). Note
> that if one measurement then defaults to simply pairwise_kernel
> for entire dictionary.
>
>__glmnet_args__ : dictionary, default = {}
>- parameters for underlying GLMnet object
"""
def __init__(self, glm_alpha=1, lambdau=1e-3, skl_kernel='laplacian', n_kernels=1,
kernel_s0 = 1e-3, kernel_s1 = None, kernel_s2 = None,
n_meas_array=np.array([]), glmnet_args = {}):
self.glm_alpha=glm_alpha
self.lambdau=lambdau
self.skl_kernel = skl_kernel
self.n_kernels = n_kernels
self.kernel_s0 = kernel_s0
self.kernel_s1 = kernel_s1
self.kernel_s2 = kernel_s2
self.n_meas_array = n_meas_array
self.glmnet_args = glmnet_args
def set_glmnet_args(self, glmnet_args):
"""Enables setting any of glmnet params except alpha and lambdau
initialized in class instance. For alpha and lambdau, use
inherited set_params().
__Parameter__
> __glmnet_args__ : dictionary
>- dictionary of arguments to pass to glmnet
"""
self.glmnet_args={**self.glmnet_args,**glmnet_args}
return self
def fit(self, X, y):
"""
Kernelizes passed data and then fits data according to passed
model. Function inherits all attributes and features of
SKLearn's base esimator class as well as passed model. As part
of fit process, feature data is kernelized (based on instance
kernel parameter) and normalized -- should parameterize
normalization or functionalize both together outside `fit`.
__Parameters__
> __X__ : ndarray of shape (n_samples, n_features)
>- Training data
>
> __y__ : ndarray of shape (n_samples, spatial dimensions)
>- Response data (location of Tx for each sample set
> of measurements)
__Returns__
> Self, sets self.X_, self.Y_
"""
# Check that X and y have correct shape
X, y = check_X_y(X, y, multi_output=True)
# Check that number of kernels and number of kernel scales is same
if self.n_kernels != len(self.n_meas_array):
raise ValueError("n_kernels is not same as number of n_meas_array")
# Check that number of each measurement types is correct
if sum(self.n_meas_array) != X.shape[1]:
raise ValueError("Sum of n_meas_array is not same as number of features in X")
#put lambdau into ndarray
self.lambdau = np.array([self.lambdau])
#put kernel scales together (reset in case called multiple times)
kernel_scales = np.array([self.kernel_s0])
for i in range(1,self.n_kernels):
kernel_scales = np.append(kernel_scales,self.get_params()["kernel_s"+str(i)])
# Generate kernelized matrix for fit input
X_kernel = HFF_k_matrix(fml=X, kernel=self.skl_kernel,
num_meas_array=self.n_meas_array,
varMs=kernel_scales)
#normalize
X_kernel = Normalizer().fit_transform(X_kernel)
# Fit
self.glmnet_model = glmnet(x = X_kernel, y = y.copy(), alpha = self.glm_alpha,
lambdau = self.lambdau, **self.glmnet_args)
# Store X,y seen during fit
self.X_ = X
self.y_ = y
# Return the regressor
return self
def predict(self, X):
"""
Applies pair-wise kernel between observed with fitted data. The
predicts based on fitted model. As part of predict process,
feature data is kernelized (based on instance kernel parameter)
and normalized -- should parameterize normalization or
functionalize both together outside `predict`.
__Parameters__
> __X__ : ndarray of shape (n_samples, n_features)
>- Sample data used for predictions
>
__Returns__
> Estimated target(s)
"""
# Check is fit had been called
check_is_fitted(self)
# Input validation
X = check_array(X)
#put kernel scales together (reset in case called multiple times)
kernel_scales = np.array([self.kernel_s0])
for i in range(1,self.n_kernels):
kernel_scales = np.append(kernel_scales,self.get_params()["kernel_s"+str(i)])
#kernelize input
X_kernel = HFF_k_matrix(fml=self.X_, fm=X,
kernel=self.skl_kernel,
num_meas_array=self.n_meas_array,
varMs=kernel_scales)
#normalize
X_kernel = Normalizer().fit_transform(X_kernel)
#predict and return
#glmnet returns with extra dimension, squeeze to remove
return np.squeeze(glmnetPredict(self.glmnet_model, X_kernel)) |
It seems counting is all the rage on the Internet these days - particularly when it involves nice, even numbers.
First it was Facebook that made it to 200 million users (and probably has way more than that by now).
Then there was the CNN/Ashton Kutcher race to be the first Twitter user with 1 million followers.
Now Apple is upping the ante with its quest for 1 billion downloads of applications for the iPhone. Check out Apple.com's rolling counter. It looks like iPhone apps may hit the 1 billion mark by Thursday morning.
What's more interesting, however, is that each event gives observers a chance to weigh in on the state of the Internet, and what this tells us about our culture.
There's plenty of talk about the most popular iPhone apps. According to ReadWriteWeb, the majority are used for entertainment. News is the next-hottest category. Apple says the Facebook app is the most popular of the free applications, and Crash Bandicoot tops the paid list (at about $6).
TechCruch writes that Apple seems to be estimating its billionth app download off of your computer's clock. At one point, Apple's counter was set to switch to 1 billion at 3:24 a.m. ET, the site says. Now the clock has been set back a bit, according to TechCrunch.
For those of you new to the app world, here's a guide.
In the comments sections, feel free to tell CNN what apps you find interesting, and how you use them. Has the iPhone changed the way you live and interact with other people? What about other phones? Are the apps as good?
Have you seen a "Facebook ghost?"
There have been several reports of privacy scams on Facebook, and "Facebook ghosts" have surfaced as a new iteration of the trend.
Earlier this month, Yahoo! Sports created a ton of buzz when it reported one NFL team allegedly uses fake Facebook profiles to tempt recruits into unknowingly handing over their personal information.
One popular Facebook "ghost" was a blond female temptress, the site reports.
The team allegedly would use these fake profiles to get friend-level access to recruits' information on the site. The thinking there is that if a team official spots a player in Facebook photos smoking dope or partying hard, the team might avoid a bad draft pick and a potential public relations problem.
The fake profiles are called "ghosts" because they disappear soon after they surface.
I wonder if this technique exists in other spheres of recruiting? At law firms? At banks? In other sports?
There's no hard evidence the NFL ghost-profile incident is part of a trend, said Justin Smith, editor of the blog Inside Facebook, which tracks the social networking site.
More often, people leak information from their Facebook pages accidentally by posting messages their bosses or colleagues can see.
It would be difficult for Facebook to prevent scams similar to the one allegedly used by NFL teams without requiring users to input personal information when setting up an account, Smith said. That's something that's unlikely to happen, he said, because social network users would move elsewhere.
Do you know of examples of Facebook "ghost" profiles appearing in an effort to access your private information? Is this a concern, and if so, what should be done? Your thoughts could turn into a future CNN.com story.
Wednesday tech trends: is that my face?
FACES: A company called Polar Rose offers a relatively new service that scans photos and determines who's in them - using facial-recognition technology. As CNET reports, the service currently exists as an add-on for the photo-sharing site Flickr. It could have future applications for Facebook (which means we'll all just have to wake up earlier to untag ourselves from embarrassing photos).
PROFILE: Google offers a new service that lets you set up a Google profile, which, a Wired blogger writes, soon could be the first search item to pop up with your name is searched on the site. Beware, the blog says, because this gives Google unprecedented power over your online persona.
DATING: Sick of the dating scene? SkyeCandy is a new speed-dating service that lets would-be love birds hold 5-minute video chats online through Skype. Check out this slightly creepy intro video on SkyeCandy's homepage.
I knew then that the book's migration to the digital realm would not be a simple matter of trading ink for pixels, but would likely change the way we read, write and sell books in profound ways. It will make it easier for us to buy books, but at the same time make it easier to stop reading them.
What's on your mind today? Found any interesting sites or new online services? Share your thought in the comments section below.
SEARCH: Cooliris has a cool tool out that lets you scan through photos and search results on a massive, 3-D wall of images. This spawned a Fortune magazine story about the future of search engines: will they always be text-based? Perhaps not.
BLOGS: There are several stories out about new government data that says there are now more paid bloggers in the country than there are paid lawyers. Not that they make the same kind of cash, although the Wall Street Journal says a blogger with 100,000 unique visitors per month can make $75,000 per year.
MAPS: IRLConnect is trying to make a name for itself with map-based social media. Using the site, you can pull in your Facebook and Twitter accounts to get a visual representation of what your posse is up to.
GOOGLE: Finally, in case you haven't seen it, Google's News Timeline is worth a look. You can pull in RSS feeds to make a weekly news timeline of your own.
A turning point for online piracy?
There was plenty of online chatter this weekend about file sharing and Internet piracy.
This follows Friday's news that four people who ran a popular file-sharing site called Pirate Bay were found guilty of violating copyright law in Sweden.
By searching for pirated music or video, Google users can easily scan a range of lesser-known pirate sites to dig up illicit content. Those looking for the upcoming film X-Men Origins: Wolverine, for instance, can search for "wolverine torrent." The first result is a link to file-sharing site isoHunt, with a torrent tracker file that allows the user to download the full film. In fact, searches for "wolverine torrent" on Google have more than quadrupled since the movie file was first leaked to peer-to-peer networks on April 5, according to Google Trends.
DownloadSquad responded with a counterpoint to Forbes' story.
In the US, Napster was shut down even though it did not host files directly. When services like Grokster sprang up in Napster's wake and tried to make their services more decentralized to avoid even the appearance of control, courts still didn't accept the argument that they had clean hands.
Copyright owners around the globe have gone on the attack. They're backing antipiracy legislation in France and Sweden. They're lobbying Internet service providers in the United States to crack down on customers who download files illegally. They're pressuring hardware and software companies to prevent their products from being used as "pirate toolboxes." They're threatening legal action against Google and other sites that aggregate news without permission.
"Anyone who does something good, particularly if you get really lucky and do a great artistic thing and have a mega hit, I think you should get rewarded for that."
Do you download pirated media? What should governments do about this issue? If you're an artist, what do you think? Feel free to weigh in with comments to this post.
Robot servants, and the end of the Internet?
ROBOTS: BBC News reports that two (likely unrelated) trends are driving robotics these days: older people and violent conflict. One expert in the story sees it this way: "Even just having robots do lightweight transport of objects from one room to another, whether it's grandma's knitting or a cup of coffee, could be tremendously valuable."
INTERNET: Is there an end to the Internet? Maybe, if your cable company says so. Nielsen Online says Internet service providers and cable companies are putting caps on how much bandwidth their customers can use. That comes as Internet users are downloading more video, particularly from Hulu, the site says.
CLOUD COMPUTING: There's been a bunch of news about cloud computing lately, and a lot of it may be hype, ars technica writes today. The notoriously vague concept generally refers to the process of hosting computer programs online. Many companies are interested, but that may not make financial sense, the site says.
FACEBOOK: Finally, what blog would be complete these days without a Facebook reference. A CNET writer wonders today whether or not the uber-popular social networking site should charge users $1 per month to avoid financial stress. What would you pay?
Facebook may have started in the U.S., but its fastest growth is now overseas in places like Europe, where it's spreading like crazy.
According to new data from comScore, Inc., which measures Internet use, Facebook now accounts for more than 4 percent of all minutes spent online in Europe - up from 1.1 percent a year ago.
As of February the social-networking site had almost 100 million users in Europe - a 314-percent increase over February 2008. In Italy alone, Facebook grew by more than 2,700 percent over the past year, suggesting that some Italians may be giving up face-to-face socializing over espressos for networking online instead.
In other news: Back on the other side of the pond, Americans conducted 14.3 billion online searches in March, a 9-percent gain over February, according to new data released Wednesday by comScore.
As usual, Google sites led the way 63.7 percent of the searches conducted in the U.S., followed by Yahoo! sites (20.5 percent), Microsoft sites (8.3 percent), Ask Network (3.8 percent) and AOL (3.7 percent).
Google search sites gained almost half a percentage point since February, while all the others dipped slightly except Microsoft, which gained 0.1 percent.
Are you thinking about buying an iPhone but waiting until the device is available on wireless carriers other than AT&T? You may have to wait a while.
Apple and AT&T met last August and agreed to extend AT&T's contract as exclusive carrier of the iPhone through the end of 2009 - at which time Apple would presumably be allowed to start selling the popular smartphone on other carriers.
Now, AT&T wants to extend that deal another two years, according to a report Tuesday evening in The Wall Street Journal.
An Apple spokeswoman declined to comment, saying only, "We have a great relationship with AT&T."
Some iPhone users have grumbled about spotty AT&T service - notably during last month's South by Southwest Interactive conference in Austin, Texas, where thousands of iPhone-carrying attendees overloaded AT&T's network.
It'll be interesting to see if Apple agrees to AT&T's request or seeks to broaden the iPhone's popularity by opening the device to Verizon, Sprint and other carriers. |
/**
* @fileoverview Disallows class mutations on self
* @author <NAME> <https://github.com/43081j>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import rule from '../../rules/no-self-class';
import {RuleTester} from 'eslint';
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
const ruleTester = new RuleTester({
parserOptions: {
sourceType: 'module',
ecmaVersion: 2015
}
});
const parser = require.resolve('@typescript-eslint/parser');
ruleTester.run('no-self-class', rule, {
valid: [
{
code: `class Foo {
method() {
this.classList.add('foo');
this.classList.remove('foo');
this.classList.toggle('foo');
this.classList.replace('foo', 'bar');
this.className = 'foo';
this.className += 'foo';
}
}`
},
{
code: `function x() {
this.classList.add('foo');
this.classList.remove('foo');
this.classList.toggle('foo');
this.classList.replace('foo', 'bar');
this.className = 'foo';
this.className += 'foo';
}`
},
{
code: `node.classList.add('foo');
node.classList.remove('foo');
node.classList.toggle('foo');
node.classList.replace('foo', 'bar');
node.className = 'foo';
node.className += 'foo';
`
},
{
code: `class Foo extends HTMLElement {
method(node) {
node.classList.add('foo');
node.classList.remove('foo');
node.classList.toggle('foo');
node.classList.replace('foo', 'bar');
node.className = 'foo';
node.className += 'foo';
}
}`
},
{
code: `class Foo extends HTMLElement {
method(node) {
node.setAttribute('class', 'x');
}
}`
}
],
invalid: [
{
code: `class Foo extends HTMLElement {
method() {
this.classList.add('foo');
this.classList.remove('foo');
this.classList.toggle('foo');
this.classList.replace('foo', 'bar');
this.className = 'foo';
this.className += 'foo';
}
}`,
errors: [
{
messageId: 'selfClass',
line: 3,
column: 11
},
{
messageId: 'selfClass',
line: 4,
column: 11
},
{
messageId: 'selfClass',
line: 5,
column: 11
},
{
messageId: 'selfClass',
line: 6,
column: 11
},
{
messageId: 'selfClass',
line: 7,
column: 11
},
{
messageId: 'selfClass',
line: 8,
column: 11
}
]
},
{
code: `class Foo extends HTMLElement {
constructor() {
this.classList.add('foo');
this.classList.remove('foo');
this.classList.toggle('foo');
this.classList.replace('foo', 'bar');
this.className = 'foo';
this.className += 'foo';
}
}`,
errors: [
{
messageId: 'selfClass',
line: 3,
column: 11
},
{
messageId: 'selfClass',
line: 4,
column: 11
},
{
messageId: 'selfClass',
line: 5,
column: 11
},
{
messageId: 'selfClass',
line: 6,
column: 11
},
{
messageId: 'selfClass',
line: 7,
column: 11
},
{
messageId: 'selfClass',
line: 8,
column: 11
}
]
},
{
code: `class Foo extends HTMLElement {
method() {
if (true) {
if (true) {
this.classList.add('foo');
}
}
}
}`,
errors: [
{
messageId: 'selfClass',
line: 5,
column: 15
}
]
},
{
code: `class Foo extends HTMLElement {
method() {
this.setAttribute('class', 'foo');
}
}`,
errors: [
{
messageId: 'selfClass',
line: 3,
column: 11
}
]
},
{
code: `/** @customElement **/
class Foo extends Bar {
method() {
this.className += 'test';
}
}`,
errors: [
{
messageId: 'selfClass',
line: 4,
column: 11
}
]
},
{
code: `@customElement('x-foo')
class Foo extends Bar {
method() {
this.className += 'test';
}
}`,
parser,
errors: [
{
messageId: 'selfClass',
line: 4,
column: 11
}
]
},
{
code: `class Foo extends Bar {
method() {
this.className += 'test';
}
}`,
settings: {
wc: {
elementBaseClasses: ['Bar']
}
},
errors: [
{
messageId: 'selfClass',
line: 3,
column: 11
}
]
}
]
});
|
export default {
secret: "mysecret",
expiresIn: "15m",
refreshSecret: "myanothersecret",
refreshExpiresIn: "7d"
};
|
A version of this article appeared in the print edition of The Daily Star on December 06, 2018, on page 12.
Downtown's Slowear Store hosted the debut of "Reality Expanded," Tuesday evening, a one-day-only augmented reality exhibition staged in Slowear franchises across the globe. The Italian menswear store hosted the pop-up exhibition in collaboration with Alchemica (Milano), with the ambitious aim of fusing the worlds of fashion and technology (and presumably art, based on the promotional material) in one shared space.
Whilst it seems likely that the future of art and marketing, as well as lifestyle, lies in augmented reality technology, the necessary use of mobile phones hindered the experience of "Reality Expanded".
Rather than living up to its promise to take art lovers on an adventurous "journey to another reality," however, "Reality Expanded" left a strong taste of an impending future whose daily life is inescapably monopolized by technological mediation. |
/**
* Method for sending a message, gets the string from the text field creates a new message with the content.
* Sends the data to the firebase and updates the number of messages in the current room.
*/
private void sendMessage() {
final FirebaseFirestore db = FirebaseFirestore.getInstance();
String text = messageText.getText().toString();
if (text.equals("") && filepath == null) {
return;
}
HandleSubscription();
try {
Message message = new Message(text);
db.collection("chat-rooms").document(currentRoom).collection("messages").add(message).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
uploadImage(documentReference);
}
});
db.collection("chat-rooms").document(currentRoom).update("numberOfMessages", messageList.size() + 1);
db.collection("chat-rooms").document(currentRoom).update("newestMessage", message.getDate());
} catch (Exception e) {
Log.e("Error", e.getMessage());
} finally {
messageText.setText("");
findViewById(R.id.preview).setVisibility(View.GONE);
}
} |
Jenny McCarthy to Host Pop Culture Talk Show on VH1 This Summer!
Most people remember Jenny McCarthy as the ball-of-energy sidekick on MTV's Singled Out in the mid-'90s and she followed that up with her own sketch-comedy show in 1997.
But now the time has finally come to put Jenny back in the spotlight. VH1 has picked up a talk show with the funny lady to air this summer.
The network announced today that it will launch The Jenny McCarthy Show, and she will "celebrate as well as skewer everyone and everything in pop culture, news, fashion, TV, movies and the Web."
“Our viewers connect with smart, funny, and outspoken women, and Jenny certainly represents all of those elements wrapped up in a style that makes people smile,” Jeff Olde, executive vice president of original programming and production, said in a statement.
The comedienne-actress will also welcome guests to the show in the same way that The Chelsea Handler Show does, and if Jenny is lucky enough to have Chelsea Handler's success, she will be in a great place.
Will you watch Jenny's new show? |
One thing’s for certain, outstanding food is always a hit. Whether it be for a crowd, your partner or even yourself, nothing makes for big smiles and happy tummies like homemade , good food. These recipes are easy-to-follow, diverse and most importantly produce amazing results. You’ll make the best impression on your lucky tasters.
Trini Christmas is the best! I'm always looking for a way to sneak our local ingredients and traditions into everyday treats. Sorrel is the shining star of this extremely simple and delicious recipe. Short on time? Grab pre-made sorrel from the grocery to make these bars.
1 Preheat oven to 350°F.
2 Line a 13-inch by 9-inch baking dish with foil; grease with non-stick spray.
3 In food processor, blend dry crust ingredients together. Add melted butter and mix. Then, press into the greased pan.
4 Bake for 10 minutes. Let the crust cool in the pan.
5 For cheesecake, add sorrel to a large saucepan and bring to a rolling boil. Allow sorrel to reduce by half, about 10 minutes. Set aside to cool.
6 In a large bowl, beat cream cheese and sugar together until smooth.
7 Add reduced sorrel drink into bowl and stir until combined.
8 Add egg, food colouring, lime juice and heavy cream; stir until just combined. Be careful not to overbeat this filling as this will cause air pockets to form and eventually burst in the oven.
9 For sorrel gel, bring sorrel to boil in a medium saucepan.
10 In a small bowl, combine cornstarch and water to form a slurry. Add the slurry to boiling sorrel and allow to thicken, about two minutes. Remove from heat; allow to cool. Pour cream cheese filling into the cooled crust.
11 Drizzle sorrel gel into filling. Using a knife, skewer or toothpick, gently move gel throughout the filling to form a swirled design.
12 Bake bars for 30 minutes. Remove from oven and allow to cool.
13 Once at room temperature, place in refrigerator for 2 hours.
14 Using a sharp knife, cut bars into squares. Serve and enjoy! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.