content
stringlengths
10
4.9M
/* * @test /nodynamiccopyright/ * @bug 6943289 * * @summary Project Coin: Improved Exception Handling for Java (aka 'multicatch') * @author mcimadamore * @compile/fail/ref=Neg03.out -XDrawDiagnostics Neg03.java * */ class Neg03 { static class A extends Exception { public void m() {}; public Object f;} static class B1 extends A {} static class B2 extends A {} void m() throws B1, B2 { try { if (true) { throw new B1(); } else { throw new B2(); } } catch (Exception ex) { ex = new B2(); //effectively final analysis disabled! throw ex; } } }
Tie Knots The Windsor (1): Popularized by the Duke of Windsor, this knot creates a perfectly symmetrical shape, suitable to fill wide spread collars. The Half Windsor (2): The Windsor knot only less so, the half Windsor has one less loop and a slimmer shape, with the same symmetry as its big brother. The Four-in-Hand (3): The simplest knot of all. Suitable for smaller and softer collars like button-downs. Collars The Small Collar (1): A low collar redolent of the sixties, it's the sort you should look for if you're into leaner suits and narrower ties. Its tie knot: the four-in-hand. The Spread Collar (2): A classic shape that works for all ages and neck shapes. Its tie knot: the Windsor. The Tall Collar (3): Set on a wider band with two buttons at the neck, the tall collar can be worn without a tie altogether, since it's substantial enough on its own. Its tie knot: the half Windsor. Cuffs The Turnback Cuff (1): Rare but in the ascendant, the turnback cuff was popularized by the first James Bond, Sean Connery, in Dr. No. It combines the elegance of a double cuff with the ease of buttons. The Button Cuff (2): Functional and modern, with none of the fiddliness of cuff links, the button cuff is right for normal office days but not too dressy. The Double Cuff (3): Still the most dressed-up choice, the double cuff, or French cuff, is best for showing a quarter inch of shirt cuff from underneath your jacket sleeve.
<gh_stars>1-10 import {Component, OnInit} from '@angular/core'; import {AppointmentService} from '../../../../services/appointment/appointment.service'; import {Appointment} from 'src/app/interfaces/appointment'; import {MatDialog, MatDialogConfig} from '@angular/material'; import {CancelDialogComponent} from 'src/app/components/cancel-dialog/cancel-dialog.component'; import {HomeComponent} from "../home.component"; import {ActivatedRoute} from "@angular/router"; import {ErrorDialogComponent} from "../../../../components/error-dialog/error-dialog.component"; @Component({ selector: 'app-employee-appointments', templateUrl: './employee-appointments.component.html', styleUrls: ['./employee-appointments.component.scss'] }) export class EmployeeAppointmentsComponent implements OnInit { businessId: number; displayedColumns: string[] = ['service', 'date', 'time', 'duration', 'client', 'employee', 'status', 'actions']; displayedColumnsPastAppointments: string[] = ['service', 'date', 'time', 'duration', 'client', 'employee', 'status']; appointments: Appointment[]; pastAppointments: Appointment[]; constructor( private errorDialog: MatDialog, private route: ActivatedRoute, private dialog: MatDialog, private appointmentService: AppointmentService) { this.appointments = []; this.pastAppointments = []; } ngOnInit() { this.dialog.afterAllClosed .subscribe(() => { // update appointments when we cancel one on dialog close. this.businessId = parseInt(this.route.snapshot.paramMap.get("businessId")); this.appointments = []; this.getAllAppointments(); }) } getAllAppointments(): void { this.appointmentService.getMyAppointmentsEmployee(this.businessId).subscribe( res => { const now = new Date(); for (const appointment of res) { const appointmentStart = new Date(appointment.date + ' ' + appointment.startTime); if (now <= appointmentStart) { this.appointments.push(appointment); } else { this.pastAppointments.push(appointment); } } }, err => { console.log(err); } ); } openDialog(element_id: any, row_id: any) { let appointmentToCancel: Appointment = this.appointments[row_id]; console.log(appointmentToCancel); const dialogConfig = new MatDialogConfig(); let longDescription: any; dialogConfig.disableClose = true; dialogConfig.autoFocus = true; dialogConfig.data = { appointment: appointmentToCancel, serviceName: appointmentToCancel.service.name, }; this.dialog.open(CancelDialogComponent, dialogConfig); } checkIfCancelled(row_number: any) { console.log(this.appointments[row_number].status); return this.appointments[row_number].status == 'CANCELLED'; } openErrorDialog( errorMessage : any) { const dialogConfig = new MatDialogConfig(); dialogConfig.disableClose = true; dialogConfig.autoFocus = true; dialogConfig.data = { title: "ERROR", message: errorMessage, }; this.dialog.open(ErrorDialogComponent, dialogConfig); } }
/** * Created by Administrator on 2018/5/25. */ public class W30OTAActivity extends WatchBaseActivity implements RequestView{ private static final String TAG = "W30OTAActivity"; @BindView(R.id.progressBar_upgrade) ProgressBar progressBarUpgrade; @BindView(R.id.btn_start_up) Button btnStartUp; RequestPressent requestPressent; int localVersion ; private String downloadUrl = null; /** * 下载请求. */ private DownloadRequest mDownloadRequest; private String downPath ; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.w30s_frrinware_upgrade); ButterKnife.bind(this); requestPressent = new RequestPressent(); requestPressent.attach(this); localVersion = Integer.valueOf((String)SharedPreferenceUtil.get(W30OTAActivity.this,"W30S_V","ab")); downPath = Environment.getExternalStorageDirectory()+"RaceDown/"; getNetWorke(); } /** * getNetWorke()获取后台版本 */ public void getNetWorke(){ try { String w30S_v = (String) SharedPreferenceUtil.get(W30OTAActivity.this, "W30S_V", "20"); if (WatchUtils.isEmpty(w30S_v)) return; String baseurl = URLs.HTTPs; JSONObject jsonObect = new JSONObject(); jsonObect.put("clientType", "android"); jsonObect.put("version", "1"); if (requestPressent != null) { //获取版本 requestPressent.getRequestJSONObject(1, baseurl + URLs.getVersion, W30OTAActivity.this, jsonObect.toString(), 0); } } catch (JSONException e) { e.printStackTrace(); } } @OnClick(R.id.btn_start_up) public void onViewClicked() { downloadData(); //下载升级包 } private void downloadData() { // 开始下载了,但是任务没有完成,代表正在下载,那么暂停下载。 if (mDownloadRequest != null && mDownloadRequest.isStarted() && !mDownloadRequest.isFinished()) { // 暂停下载。 mDownloadRequest.cancel(); } else if (mDownloadRequest == null || mDownloadRequest.isFinished()) {// 没有开始或者下载完成了,就重新下载。 mDownloadRequest = new DownloadRequest(downloadUrl, RequestMethod.GET, downPath,true, true); // what 区分下载。 // downloadRequest 下载请求对象。 // downloadListener 下载监听。 CallServer.getInstance().download(0, mDownloadRequest, downloadListener); // 添加到队列,在没响应的时候让按钮不可用。 //mBtnStart.setEnabled(false); } } @Override protected void onDestroy() { super.onDestroy(); requestPressent.detach(); } @Override public void showLoadDialog(int what) { } @Override public void successData(int what, Object object, int daystag) { Log.e(TAG,"---------succ-="+object); if(what == 1){ UpDataBean upDataBean = new Gson().fromJson(object.toString(), UpDataBean.class); if(upDataBean.getResultCode().equals("001")){ int version = Integer.valueOf(upDataBean.getVersion().trim()); String downUrl = upDataBean.getUrl(); if(version > localVersion){ //有新版本 downloadUrl = downUrl; } } } } @Override public void failedData(int what, Throwable e) { } @Override public void closeLoadDialog(int what) { } /** * 下载监听 */ private DownloadListener downloadListener = new DownloadListener() { @Override public void onStart(int what, boolean isResume, long beforeLength, Headers headers, long allCount) { } @Override public void onDownloadError(int what, Exception exception) { Logger.e(exception); } @Override public void onProgress(int what, int progress, long fileCount, long speed) { updateProgress(progress, speed); } @Override public void onFinish(int what, String filePath) { Logger.d("Download finish, file path: " + filePath); } @Override public void onCancel(int what) { } private void updateProgress(int progress, long speed) { } }; }
Please enable Javascript to watch this video DAVIS COUNTY -- Utah law allows county jails to charge inmates for restitution, and since the law was passed in 2007, the Davis County Sheriff's Office has been charging inmates $10 a day during their incarceration. But, have they been going about this illegally? The Davis County Jail has been doing this for the past seven years, and it wasn't until 2013 that questions surrounding the Pay For Stay program came into question. A judge stated that he has received numerous letters from inmates stating that money was being taken from their commissary accounts. Vickie Hinze has a son serving time in the Davis County Jail. "If I put money in for my son to buy food, he won't get it,” she said. “It'll go to his bill, which frustrates me because when I specify where it goes that's where it should go." Another person who didn't want to be identified said: "I wasn't told anything about the Pay For Stay. I put over $200 in for the commissary, and then after the fact I was told that nothing was used towards the commissary, it was a Pay For Stay." Since 2007, the Davis County Sheriff's office has been charging inmates $10 a day for the duration of their incarceration, with some of that money coming out of the inmate's commissary account, which a judge has now ordered them to stop doing. Utah Representative Paul Ray, R-District 13, said, "What it comes down to is the judge is interpreting the law differently than how the legislature has written it." According to the Davis County Attorney, the Sheriff's Office has been breaking the law. According to emails from Davis County Attorney Troy Rawlings: "Prior to collection, there must be a restitution claim, a court order, and a judgment. This is not a difficult concept to grasp. If there is non-compliance, there is no legitimate way to collect it. The Keith Major pre-sentencing pre-court-ordered-restitution accounting enema of an inmate's account is not legal." Rawlings goes on to explain that the Davis County Sheriff's Office cannot collect on Pay For Stay until a claim has been submitted for restitution, after sentencing, based on the court determined sum, and after the primary victim and others have been paid first. Rep. Ray stands behind the county's collection methods, claiming the $10 a day restitution from inmates has significantly reduced the taxpayer burden. He said: "They're giving them money to buy treats with, to buy commissaries, all these extras in the jail, and the county is saying, ‘No, wait a minute. You have a debt to society that you're gonna pay before you buy those Twinkies.’” A response from the Davis County Sheriff's Office states, "The Davis County Sheriff's Office will comply with Judge Allphin's order, but is deeply concerned with the suggestion to the public that it has violated the law. The policies in place by the Davis County Sheriff's Office are identical to policies used by many other jails in the State of Utah." Rep. Ray said Davis County has the highest collection rate in the state. In 2013, the Davis County Sheriff's Office collected $369,000 through the Pay For Stay program. Ray also said he's already opened up a bill file to modify the law and reduce ambiguity during the next legislative session.
/** * Parses input arguments and creates a new ViewCommitHistoryCommand object. */ public class ViewCommitHistoryParser implements Parser<ViewCommitHistoryCommand> { /** * Parses the given {@code String} of arguments in the context of the * ViewCommitHistoryCommand and returns an ViewCommitHistoryCommand object for * execution. */ public ViewCommitHistoryCommand parse(String args) { return new ViewCommitHistoryCommand(); } }
Thomas Nast (; German: [nast]; September 27, 1840 – December 7, 1902) was a German-born American caricaturist and editorial cartoonist considered to be the "Father of the American Cartoon".[1] He was the scourge of Democratic Representative "Boss" Tweed and the Tammany Hall Democratic party political machine. Among his notable works were the creation of the modern version of Santa Claus (based on the traditional German figures of Sankt Nikolaus and Weihnachtsmann) and the political symbol of the elephant for the Republican Party (GOP). Contrary to popular belief, Nast did not create Uncle Sam (the male personification of the United States Federal Government), Columbia (the female personification of American values), or the Democratic donkey,[2] though he did popularize these symbols through his artwork. Nast was associated with the magazine Harper's Weekly from 1859 to 1860 and from 1862 until 1886. Albert Boime argues that: As a political cartoonist, Thomas Nast wielded more influence than any other artist of the 19th century. He not only enthralled a vast audience with boldness and wit, but swayed it time and again to his personal position on the strength of his visual imagination. Both Lincoln and Grant acknowledged his effectiveness in their behalf, and as a crusading civil reformer he helped destroy the corrupt Tweed Ring that swindled New York City of millions of dollars. Indeed, his impact on American public life was formidable enough to profoundly affect the outcome of every presidential election during the period 1864 to 1884.[3] Early life and education [ edit ] Nast was born in military barracks in Landau, Germany (now in Rhineland-Palatinate), as his father was a trombonist in the Bavarian 9th regiment band.[4] Nast was the last child of Appolonia (Abriss) and Joseph Thomas Nast. He had an older sister Andie; two other siblings had died before he was born. His father held political convictions that put him at odds with the Bavarian government, so in 1846, Joseph Nast left Landau, enlisting first on a French man-of-war and subsequently on an American ship.[5] He sent his wife and children to New York City, and at the end of his enlistment in 1850, he joined them there.[6] Nast attended school in New York City from the age of six to 14. He did poorly at his lessons, but his passion for drawing was apparent from an early age. In 1854, at the age of 14, he was enrolled for about a year of study with Alfred Fredericks and Theodore Kaufmann, and then at the school of the National Academy of Design.[7][8] In 1856, he started working as a draftsman for Frank Leslie's Illustrated Newspaper.[9] His drawings appeared for the first time in Harper's Weekly on March 19, 1859,[10] when he illustrated a report exposing police corruption; Nast was 18 years old at that point.[11] Career [ edit ] Self-caricature of Thomas Nast In February 1860, he went to England for the New York Illustrated News to depict one of the major sporting events of the era, the prize fight between the American John C. Heenan and the English Thomas Sayers[12] sponsored by George Wilkes, publisher of Wilkes' Spirit of the Times. A few months later, as artist for The Illustrated London News, he joined Garibaldi in Italy. Nast's cartoons and articles about the Garibaldi military campaign to unify Italy captured the popular imagination in the U.S. In February 1861, he arrived back in New York. In September of that year, he married Sarah Edwards, whom he had met two years earlier. He left the New York Illustrated News to work again, briefly, for Frank Leslie's Illustrated News.[13] In 1862, he became a staff illustrator for Harper's Weekly. In his first years with Harper's, Nast became known especially for compositions that appealed to the sentiment of the viewer. An example is "Christmas Eve" (1862), in which a wreath frames a scene of a soldier's praying wife and sleeping children at home; a second wreath frames the soldier seated by a campfire, gazing longingly at small pictures of his loved ones.[14] One of his most celebrated cartoons was "Compromise with the South" (1864), directed against those in the North who opposed the prosecution of the American Civil War.[15] He was known for drawing battlefields in border and southern states. These attracted great attention, and Nast was referred to by President Abraham Lincoln as "our best recruiting sergeant".[16] After the war, Nast strongly opposed the Reconstruction policy of President Andrew Johnson, whom he depicted in a series of trenchant cartoons that marked "Nast's great beginning in the field of caricature".[17] Style and themes [ edit ] The American River Ganges, a cartoon by Thomas Nast showing bishops attacking public schools, with connivance of Harper's Weekly, September 30, 1871. , a cartoon by Thomas Nast showing bishops attacking public schools, with connivance of "Boss" Tweed , September 30, 1871. The Usual Irish Way of Doing Things, a cartoon by Thomas Nast depicting a drunken Irishman lighting a powder keg. Published in Harper's Weekly, September 2, 1871. , a cartoon by Thomas Nast depicting a drunken Irishman lighting a powder keg. Published in, September 2, 1871. 1871 Cartoon: Move on!" Has the Native American no rights that the naturalized American is bound to respect?" An ironic Nast Cartoon pointing out that while naturalized Foreigners had the vote, native born Native Americans had no vote as they were not considered United States Citizens {which was only remedied in 1924} Nast's cartoons frequently had numerous sidebars and panels with intricate subplots to the main cartoon. A Sunday feature could provide hours of entertainment and highlight social causes. After 1870, Nast favored simpler compositions featuring a strong central image.[7] He based his likenesses on photographs.[7] In the early part of his career, Nast used a brush and ink wash technique to draw tonal renderings onto the wood blocks that would be carved into printing blocks by staff engravers. The bold cross-hatching that characterized Nast's mature style resulted from a change in his method that began with a cartoon of June 26, 1869, which Nast drew onto the wood block using a pencil, so that the engraver was guided by Nast's linework. This change of style was influenced by the work of the English illustrator John Tenniel.[18] A recurring theme in Nast's cartoons is racism and anti-Catholicism. Nast was baptized a Catholic at the Sankt Maria Catholic Church in Landau,[19] and for a time received Catholic education in New York City.[20] When Nast converted to Protestantism remains unclear, but his conversion was likely formalized upon his marriage in 1861. (The family were practicing Episcopalians at St. Peter's in Morristown.) Nast considered the Catholic Church to be a threat to American values. According to his biographer, Fiona Deans Halloran, Nast was "intensely opposed to the encroachment of Catholic ideas into public education".[21] When Tammany Hall proposed a new tax to support parochial Catholic schools, he was outraged. His savage 1871 cartoon "The American River Ganges", depicts Catholic bishops, guided by Rome, as crocodiles moving in to attack American school children as Irish politicians prevent their escape. He portrayed public support for religious education as a threat to democratic government. The authoritarian papacy in Rome, ignorant Irish Americans, and corrupt politicians at Tammany Hall figured prominently in his work. Nast favored nonsectarian public education that mitigated differences of religion and ethnicity. However, in 1871 Nast and Harper's Weekly supported the Republican-dominated board of education in Long Island in requiring students to hear passages from the King James Bible, and his educational cartoons sought to raise anti-Catholic and anti-Irish fervor among Republicans and independents.[22] Nast expressed anti-Irish sentiment by depicting them as violent drunks. He used Irish people as a symbol of mob violence, machine politics, and the exploitation of immigrants by political bosses.[23] Nast's emphasis on Irish violence may have originated in scenes he witnessed in his youth. Nast was physically small and had experienced bullying as a child.[24] In the neighborhood in which he grew up, acts of violence by the Irish against black Americans were commonplace.[25] In 1863, he witnessed the New York City draft riots in which a mob composed mainly of Irish immigrants burned the Colored Orphan Asylum to the ground. His experiences may explain his sympathy for black Americans and his "antipathy to what he perceived as the brutish, uncontrollable Irish thug".[24] An 1876 Nast cartoon combined a caricature of Charles Francis Adams Sr with anti-Irish sentiment and anti-Fenianship.[26] October 26, 1874, Nast cartoon "The Union as it was...This is a White Mans Government.... the Lost cause ...Worse than Slavery" Thomas Nast's cartoon "Third Term Panic" {Inspired by the tale of a The Ass in the Lion's Skin } and a rumor of President Grant seeking a third term, the Democratic donkey aka "Caesarism" panics the other political animals-including a Republican Party elephant at the left 1879 Nast cartoon: "Red gentleman (Indian) to yellow gentleman (Chinese) "Pale face 'fraid you crowd him out, as he did me." In the left background an African American remarks "My day is coming". In general, his political cartoons supported American Indians and Chinese Americans. He advocated the abolition of slavery, opposed racial segregation, and deplored the violence of the Ku Klux Klan. In one of his more famous cartoons, the phrase "Worse than Slavery" is printed on a coat of arms depicting a despondent black family holding their dead child; in the background is a lynching and a schoolhouse destroyed by arson. Two members of the Ku Klux Klan and White League, paramilitary insurgent groups in the Reconstruction-era South, shake hands in their mutually destructive work against black Americans. Despite Nast's championing of minorities, Morton Keller writes that later in his career "racist stereotypy of blacks began to appear: comparable to those of the Irish—though in contrast with the presumably more highly civilized Chinese."[27] Nast introduced into American cartoons the practice of modernizing scenes from Shakespeare for a political purpose. Nast also brought his approach to bear on the usually prosaic almanac business, publishing an annual Nast's Illustrated Almanac from 1871 to 1875. The Green Bag republished all five of Nast's almanacs in the 2011 edition of its Almanac & Reader.[28] Campaign against the Tweed Ring [ edit ] The "Brains" depicted by Thomas Nast in a wood engraving published in Harper's Weekly, October 21, 1871 Boss Tweed depicted by Thomas Nast in a wood engraving published in, October 21, 1871 A Group of Vultures Waiting for the Storm to "Blow Over" – "Let Us Prey." The Tweed Ring depicted by Nast in a wood engraving published in Harper's Weekly, September 23, 1871 The Tammany Tiger Loose—"What are you going to do about it?", published in Harper's Weekly in November 1871, just before , published inin November 1871, just before election day . "Boss" Tweed is depicted in the audience as the Emperor. The 1876 cartoon that helped identify Boss Tweed in Spain. Nast's drawings were instrumental in the downfall of Boss Tweed, the powerful Tammany Hall leader. As commissioner of public works for New York City, Tweed led a ring that by 1870 had gained total control of the city's government, and controlled "a working majority in the State Legislature".[29] Tweed and his associates—Peter Barr Sweeny (park commissioner), Richard B. Connolly (controller of public expenditures), and Mayor A. Oakey Hall—defrauded the city of many millions of dollars by grossly inflating expenses paid to contractors connected to the Ring. Nast, whose cartoons attacking Tammany corruption had appeared occasionally since 1867, intensified his focus on the four principal players in 1870 and especially in 1871. Tweed so feared Nast's campaign that he sent an emissary to offer the artist a bribe of $100,000, which was represented as a gift from a group of wealthy benefactors to enable Nast to study art in Europe.[30] Feigning interest, Nast negotiated for more before finally refusing an offer of $500,000 with the words, "Well, I don't think I'll do it. I made up my mind not long ago to put some of those fellows behind the bars".[31] Nast pressed his attack in the pages of Harper's, and the Ring was removed from power in the election of November 7, 1871. Tweed was arrested in 1873 and convicted of fraud. When Tweed attempted to escape justice in December 1875 by fleeing to Cuba and from there to Spain, officials in Vigo were able to identify the fugitive by using one of Nast's cartoons.[32] Party politics [ edit ] Compromise With the South (1864) by Thomas Nast, urging the U.S. not to capitulate to the Confederacy in the American Civil War [33][34] An 1869 Nast cartoon supporting the Fifteenth Amendment Harper's Weekly, January 26, 1878 Interior Secretary Schurz cleaning house,, January 26, 1878 Senatorial Round House, from Harper's Weekly, July 10, 1886 Harper's Weekly, and Nast, played an important role in the election of Abraham Lincoln in 1864, and Ulysses S. Grant in 1868 and 1872. In September 1864, when Lincoln was running for re-election against Democratic candidate George B. McClellan, who positioned himself as the "peace candidate", Harper's Weekly published Nast's cartoon "Compromise with the South – Dedicated to the Chicago Convention", which criticized McClellan's peace platform as pro-South. Millions of copies were made and distributed nationwide, and Nast was later credited with aiding Lincoln's campaign in a critical moment.[35] Nast played important role during the presidential election in 1868, and Ulysses S. Grant attributed his victory to "the sword of Sheridan and the pencil of Thomas Nast."[36] In the 1872 presidential campaign, Nast's ridicule of Horace Greeley's candidacy was especially merciless.[37] After Grant's victory in 1872, Mark Twain wrote the artist a letter saying: "Nast, you more than any other man have won a prodigious victory for Grant—I mean, rather, for Civilization and Progress."[38] Nast became a close friend of President Grant and the two families shared regular dinners until Grant's death in 1885. Nast and his wife moved to Morristown, New Jersey in 1872 and there they raised a family that eventually numbered five children. In 1873, Nast toured the United States as a lecturer and a sketch-artist.[39] His activity on the lecture circuit made him wealthy.[40] Nast was for many years a staunch Republican.[41] Nast opposed inflation of the currency, notably with his famous rag-baby cartoons, and he played an important part in securing Rutherford B. Hayes' presidential election in 1876. Hayes later remarked that Nast was "the most powerful, single-handed aid [he] had",[42] but Nast quickly became disillusioned with President Hayes, whose policy of Southern pacification he opposed. The death of the Weekly's publisher, Fletcher Harper, in 1877 resulted in a changed relationship between Nast and his editor George William Curtis. His cartoons appeared less frequently, and he was not given free rein to criticize Hayes or his policies.[43] Beginning in the late 1860s, Nast and Curtis had frequently differed on political matters and particularly on the role of cartoons in political discourse.[44] Curtis believed that the powerful weapon of caricature should be reserved for "the Ku-Klux Democracy" of the opposition party, and did not approve of Nast's cartoons assailing Republicans such as Carl Schurz and Charles Sumner who opposed policies of the Grant administration.[45] Nast said of Curtis: "When he attacks a man with his pen it seems as if he were apologizing for the act. I try to hit the enemy between the eyes and knock him down."[27] Fletcher Harper consistently supported Nast in his disputes with Curtis.[44] After his death, his nephews, Joseph W. Harper Jr. and John Henry Harper, assumed control of the magazine and were more sympathetic to Curtis's arguments for rejecting cartoons that contradicted his editorial positions.[46] Between 1877 and 1884, Nast's work appeared only sporadically in Harper's, which began publishing the milder political cartoons of William Allen Rogers. Although his sphere of influence was diminishing, from this period date dozens of his pro-Chinese immigration drawings, often implicating the Irish as instigators. Nast blamed U.S. Senator James G. Blaine (R-Maine) for his support of the Chinese Exclusion Act and depicted Blaine with the same zeal used against Tweed. Nast was one of the few editorial artists who took up for the cause of the Chinese in America.[47] Harper's Weekly, 1867 Portrait of Thomas Nast from, 1867 During the presidential election of 1880, Nast felt that he could not support the Republican candidate, James A. Garfield, because of Garfield's involvement in the Crédit Mobilier scandal; and did not wish to attack the Democratic candidate, Winfield Scott Hancock, his personal friend and a Union general whose integrity commanded respect. As a result, "Nast's commentary on the 1880 campaign lacked passion", according to Halloran.[48] He submitted no cartoons to Harper's between the end of March 1883 and March 1, 1884, partly because of illness.[49] In 1884, Curtis and Nast agreed that they could not support the Republican candidate James G. Blaine, a proponent of high tariffs and the spoils system whom they perceived as personally corrupt.[50] Instead, they became Mugwumps by supporting the Democratic candidate, Grover Cleveland, whose platform of civil service reform appealed to them. Nast's cartoons helped Cleveland become the first Democrat to be elected President since 1856. In the words of the artist's grandson, Thomas Nast St Hill, "it was generally conceded that Nast's support won Cleveland the small margin by which he was elected. In this his last national political campaign, Nast had, in fact, 'made a president'."[51] Nast's tenure at Harper's Weekly ended with his Christmas illustration of December 1886. It was said by the journalist Henry Watterson that "in quitting Harper's Weekly, Nast lost his forum: in losing him, Harper's Weekly lost its political importance."[52] Fiona Deans Halloran says "the former is true to a certain extent, the latter unlikely."[53] Nast lost most of his fortune in 1884 after investing in a banking and brokerage firm operated by the swindler Ferdinand Ward. In need of income, Nast returned to the lecture circuit in 1884 and 1887.[54] Although these tours were successful, they were less remunerative than the lecture series of 1873.[55] After Harper's Weekly [ edit ] In 1890, Nast published Thomas Nast's Christmas Drawings for the Human Race.[7] He contributed cartoons in various publications, notably the Illustrated American, but was unable to regain his earlier popularity. His mode of cartooning had come to be seen as outdated, and a more relaxed style exemplified by the work of Joseph Keppler was in vogue.[56] Health problems, which included pain in his hands which had troubled him since the 1870s, affected his ability to work. In 1892, he took control of a failing magazine, the New York Gazette, and renamed it Nast's Weekly. Now returned to the Republican fold, Nast used the Weekly as a vehicle for his cartoons supporting Benjamin Harrison for president. The magazine had little impact and ceased publication seven months after it began, shortly after Harrison's defeat.[57] The failure of Nast's Weekly left Nast with few financial resources. He received a few commissions for oil paintings and drew book illustrations. In 1902, he applied for a job in the State Department, hoping to secure a consular position in western Europe.[58] Although no such position was available, President Theodore Roosevelt was an admirer of the artist and offered him an appointment as the United States' Consul General to Guayaquil, Ecuador in South America.[58] Nast accepted the position and traveled to Ecuador on July 1, 1902.[58] During a subsequent yellow fever outbreak, Nast remained on the job, helping numerous diplomatic missions and businesses escape the contagion. He contracted the disease and died on December 7 of that year.[7] His body was returned to the United States, where he was interred in the Woodlawn Cemetery in The Bronx, New York City. Legacy [ edit ] Nast's depictions of iconic characters, such as Santa Claus[59] and Uncle Sam, are widely credited as forming the basis of popular depictions used today. Additional contributions by Nast include: In December 2011, a proposal to include Nast in the New Jersey Hall of Fame in 2012 caused controversy. The Wall Street Journal reported that because of his stereotypical cartoons of the Irish, a number of objections were raised about Nast's work. For example, "The Usual Irish Way of Doing Things" portrays an Irishman as being sub-human, drunk, and violent.[62] Thomas Nast Award [ edit ] The Thomas Nast Award[63] has been presented each year since 1968 by the Overseas Press Club[64] to an editorial cartoonist for the "best cartoons on international affairs." Past winners include Signe Wilkinson, Kevin (KAL) Kallaugher, Mike Peters, Clay Bennett, Mike Luckovich, Tom Toles, Herbert Block, Tony Auth, Jeff MacNelly, Dick Locher, Jim Morin, Warren King, Tom Darcy, Don Wright and Patrick Chappatte.[63][64] In December 2018, The OPC Board of Governors decided to remove Nast’s name from the award noting that Nast “ exhibited an ugly bias against immigrants, the Irish and Catholics”. OPC President Pancho Bernasconi stated “Once we became aware of how some groups and ethnicities were portrayed in a manner that is not consistent with how journalists work and view their role today, we voted to remove his name from the award.”[65] Thomas Nast Prize [ edit ] The Thomas Nast Prize for editorial cartooning has been awarded by the Thomas Nast Foundation (located in Nast's birthplace of Landau, Germany) since 1978 when it was first given to Jeff MacNelly.[66] The prize is awarded periodically to one German cartoonist and one North American cartoonist. Winners receive 1,300 Euros, a trip to Landau, and the Thomas Nast medal. The American advisory committee includes Nast's descendant Thomas Nast III of Fort Worth, Texas.[66] Other winners of the Thomas Nast Prize include Jim Borgman, Paul Szep, Pat Oliphant, David Levine, Jim Morin, and Tony Auth.[67] A popular urban legend claims that the word "nasty" originates from Thomas Nast's last name, due to the tone of his cartoons.[68] In reality, the word "nasty" has origins in Old French and Dutch hundreds of years before Nast was born.[69] Notes [ edit ] References [ edit ]
import java.util.Scanner; public class Main { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int t = scanner.nextInt(); scanner.nextLine(); for (int i = 0; i < t; ++i) { solve(); } } public static void solve() { int n = scanner.nextInt(); scanner.nextLine(); int minOrages = Integer.MAX_VALUE; int minCandies = Integer.MAX_VALUE; int[] candies = new int[n]; int[] oranges = new int[n]; for (int i = 0; i < n; ++i) { candies[i] = scanner.nextInt(); if (candies[i] < minCandies) minCandies = candies[i]; } scanner.nextLine(); for (int i = 0; i < n; ++i) { oranges[i] = scanner.nextInt(); if (oranges[i] < minOrages) minOrages = oranges[i]; } scanner.nextLine(); long cnt = 0; for (int i = 0; i < n; ++i) { int ors = oranges[i]; int cns = candies[i]; int reqOrange = ors - minOrages; int reqCandies = cns - minCandies; int min = Math.min(reqCandies, reqOrange); cnt += (long) reqCandies + (long) reqOrange - min; } System.out.println(cnt); } }
<gh_stars>0 package net.onrc.openvirtex.util; public class OVXUtil { public static int NUMBITSNEEDED(int x) { int counter = 0; while (x !=0) { x >>= 1; counter++; } return counter; } }
// New creates a new hyperloglog counter with the specified precision. p must be in the range [4,18] func New(p uint8) Counter { if p < 4 || p > 18 { panic("hll: precision p must be in range [4,18]") } m := int(1 << uint(p)) c := Counter{ p: p, bits: bitbucket.New(m, 6), } c.initParams() return c }
<reponame>ghh0000/testTs<filename>node_modules/typeorm/decorator/options/EntityOptions.d.ts import { OrderByCondition } from "../../find-options/OrderByCondition"; /** * Describes all entity's options. */ export interface EntityOptions { /** * Specifies a default order by used for queries from this table when no explicit order by is specified. */ orderBy?: OrderByCondition | ((object: any) => OrderByCondition | any); /** * Table's database engine type (like "InnoDB", "MyISAM", etc). * It is used only during table creation. * If you update this value and table is already created, it will not change table's engine type. * Note that not all databases support this option. */ engine?: string; /** * Specifies if this table will be skipped during schema synchronization. */ skipSync?: boolean; }
import java.util.*; public class test { public static void main(String args[]) { //declare a scanner to take input Scanner scan = new Scanner(System.in); //take input of the number of numbers and number of operations long n = scan.nextInt(), q = scan.nextInt(); //declare a prefix sum array long pre[] = new long[(int)n+2]; //Idea here is that if we are given l, r, val then we will add val to pre[l] and subtract val from pre[r+1]; //At the end, we will run a loop and find the prefix sums, and that will actually be the final array for(int i = 0; i < q; i++) { int l, r, val; //take input of l, r, val; l = scan.nextInt(); r = scan.nextInt(); val = scan.nextInt(); //add val to pre[l]; pre[l] += val; //subtract val from pre[r+1]; pre[r+1] -= val; } //find prefix sum of this array for(int i = 2; i <= n; i++) { pre[i] += pre[i-1]; } //initialise answer to 0 long ans = 0; //iterate over the array and keep updating answer for(int i = 1; i <= n; i++) { ans = Math.max(ans, pre[i]); } //print the answer System.out.println(ans); } }
Associations Between Patient-Provider Secure Message Content and Patients' Health Care Visits. Background: Between-visit communications can play a vital role in improving intermediate patient outcomes such as access to care and satisfaction. Secure messaging is a growing modality for these communications, but research is limited about the influence of message content on those intermediate outcomes. We examined associations between secure message content and patients' number of health care visits. Methods: Our study included 2,111 adult patients with hypertension and/or diabetes and 18,309 patient- and staff-generated messages. We estimated incident rate ratios (IRRs) for associations between taxonomic codes assigned to message content, and the number of office, emergency department, and inpatient visits. Results: Patients who initiated message threads in 2017 had higher numbers of outpatient visits (p < 0.001) compared with patients who did not initiate threads. Among patients who initiated threads, we identified an inverse relationship between outpatient visits and preventive care scheduling requests (IRR = 0.92; 95% confidence interval : 0.86-0.98) and requests for appointments for new conditions (IRR = 0.95; 95% CI: 0.92-0.99). Patients with higher proportions of request denials or more follow-up appointment requests had more emergency department visits compared with patients who received or sent other content (IRR = 1.18; 95% CI: 1.03-1.34 and IRR = 1.14; 95% CI: 1.07-1.23, respectively). We identified a positive association between outpatient visits and the proportion of threads that lacked a clinic response (IRR = 1.02; 95% CI: 1.00-1.03). Discussion: We report on the first analyses to examine associations between message content and health care visits. Conclusions: Our findings are relevant to understanding how to better use secure messaging to support patients and their care.
N,A,B = map(int,input().split()) if A>B or (N==1 and A!=B): print(0) elif A==B or N==2: print(1) else: N-=2 print(B*N-A*N+1)
package org.swiftboot.demo.model.dao; /** * 订单数据查询接口 * * @author swiftech 2019-04-07 **/ public interface OrderCustomizeDao { }
<reponame>thinktkj/simple-cms<filename>src/main/java/vip/toby/cms/core/service/IDataBaseService.java<gh_stars>1-10 package vip.toby.cms.core.service; import java.beans.IntrospectionException; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; /** * 数据操作业务逻辑接口(增删改查) */ public interface IDataBaseService { /** * 新增特殊数据,不需要指定起草人id * * @param entity 实体类 * @param entityType 实体类型 * @return * @throws NoSuchFieldException * @throws SecurityException * @throws InvocationTargetException * @throws IntrospectionException * @throws InstantiationException * @throws IllegalAccessException * @throws NoSuchMethodException */ Object add(Object entity, Class<?> entityType) throws NoSuchFieldException, SecurityException, InvocationTargetException, IntrospectionException, InstantiationException, IllegalAccessException, NoSuchMethodException; /** * 删除数据 * * @param id id * @param entityType 实体类型 * @return 被删除的实体的id * @throws Exception */ <T> T delete(T id, Class<?> entityType) throws Exception; /** * 更新数据 * * @param entity 实体类 * @param entityType 实体类型 * @return 修改后的数据 * @throws SecurityException * @throws NoSuchFieldException * @throws IntrospectionException * @throws InvocationTargetException * @throws IllegalAccessException * @throws InstantiationException */ <T> T save(T entity, Class<?> entityType) throws NoSuchFieldException, SecurityException, InvocationTargetException, IntrospectionException, InstantiationException, IllegalAccessException; /** * 查询所有数据 * * @param query 查询条件 * @param sort 排序条件 * @param entityType 实体类型 * @return 实体对象集合 * @throws IntrospectionException * @throws SecurityException * @throws NoSuchFieldException * @throws InvocationTargetException */ <T> List<T> list(String query, String sort, Class<T> entityType) throws InvocationTargetException, NoSuchFieldException, SecurityException, IntrospectionException; /** * 分页查询数据 * * @param start 分页开始位置 * @param offset 分页偏移量 * @param query 查询条件 * @param sort 排序条件 * @param entityType 实体类型 * @return 实体对象集合 * @throws SecurityException * @throws NoSuchFieldException * @throws IntrospectionException * @throws InvocationTargetException */ <T> List<T> list(Integer start, Integer offset, String query, String sort, Class<T> entityType) throws NoSuchFieldException, SecurityException, InvocationTargetException, IntrospectionException; /** * 获取单个实体 * * @param id id * @param entityType 实体类型 * @return 实体对象 * @throws IntrospectionException * @throws SecurityException * @throws NoSuchFieldException * @throws InvocationTargetException */ <T> T getEntity(Object id, Class<T> entityType) throws InvocationTargetException, NoSuchFieldException, SecurityException, IntrospectionException; /** * 获取总记录数 * * @param entityType 实体类型 * @param query 查询条件 * @return 总记录数 */ Integer getTotal(Class<?> entityType, String query); /** * 自定义查询 * * @param querySql sql语句 * @return 结果集 */ List<Map<String, Object>> query(String querySql); /** * 自定义更新或删除 * * @param updateSql sql语句 */ void update(String updateSql); /** * 调用存储过程 * * @param procName 存储过程名称 * @param inParams 输入参数,格式:Map<参数位置(从1开始),参数值> * @param outParams 输出参数,格式:Map<参数位置(从1开始),参数值> * @return 返回结果,格式:Map<参数位置(从1开始),返回值> */ Map<Integer, Object> execute(String procName, Map<Integer, Object> inParams, Map<Integer, Integer> outParams); }
<reponame>mpolanec/Master-thesis package si.um.feri.mag.polanec.data; import si.um.feri.mag.polanec.enums.DataSource; import si.um.feri.mag.polanec.enums.MetricsType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; /** * Paths to known data files. Data-sets contains data from open-source projects. */ public class DataFiles { private static final ArrayList<IDataFile> files = new ArrayList<IDataFile>() {{ // data_raw/run_combiner.ps1 <- convert data from csv to arff // use: // data_raw/datafiles_helper.ps1 <- links to files (without correct versions). // teraPROMISE repo // combined data add(new DataFile("all.arff", "All", MetricsType.CLASSIC_METRICS, 1.0, DataSource.PROMISE)); // single data add(new DataFile("ant-1.3_prepared.arff", "ant", MetricsType.CLASSIC_METRICS, 1.3, DataSource.PROMISE)); add(new DataFile("ant-1.4_prepared.arff", "ant", MetricsType.CLASSIC_METRICS, 1.4, DataSource.PROMISE)); add(new DataFile("ant-1.5_prepared.arff", "ant", MetricsType.CLASSIC_METRICS, 1.5, DataSource.PROMISE)); add(new DataFile("ant-1.6_prepared.arff", "ant", MetricsType.CLASSIC_METRICS, 1.6, DataSource.PROMISE)); add(new DataFile("ant-1.7_prepared.arff", "ant", MetricsType.CLASSIC_METRICS, 1.7, DataSource.PROMISE)); add(new DataFile("camel-1.0_prepared.arff", "camel", MetricsType.CLASSIC_METRICS, 1.0, DataSource.PROMISE)); add(new DataFile("camel-1.2_prepared.arff", "camel", MetricsType.CLASSIC_METRICS, 1.2, DataSource.PROMISE)); add(new DataFile("camel-1.4_prepared.arff", "camel", MetricsType.CLASSIC_METRICS, 1.4, DataSource.PROMISE)); add(new DataFile("camel-1.6_prepared.arff", "camel", MetricsType.CLASSIC_METRICS, 1.6, DataSource.PROMISE)); add(new DataFile("forrest-0.6_prepared.arff", "forrest", MetricsType.CLASSIC_METRICS, 0.6, DataSource.PROMISE)); add(new DataFile("forrest-0.7_prepared.arff", "forrest", MetricsType.CLASSIC_METRICS, 0.7, DataSource.PROMISE)); add(new DataFile("forrest-0.8_prepared.arff", "forrest", MetricsType.CLASSIC_METRICS, 0.8, DataSource.PROMISE)); add(new DataFile("ivy-1.1_prepared.arff", "ivy", MetricsType.CLASSIC_METRICS, 1.1, DataSource.PROMISE)); add(new DataFile("ivy-1.4_prepared.arff", "ivy", MetricsType.CLASSIC_METRICS, 1.4, DataSource.PROMISE)); add(new DataFile("ivy-2.0_prepared.arff", "ivy", MetricsType.CLASSIC_METRICS, 2.0, DataSource.PROMISE)); add(new DataFile("jedit-3.2_prepared.arff", "jedit", MetricsType.CLASSIC_METRICS, 3.2, DataSource.PROMISE)); add(new DataFile("jedit-4.0_prepared.arff", "jedit", MetricsType.CLASSIC_METRICS, 4.0, DataSource.PROMISE)); add(new DataFile("jedit-4.1_prepared.arff", "jedit", MetricsType.CLASSIC_METRICS, 4.1, DataSource.PROMISE)); add(new DataFile("jedit-4.2_prepared.arff", "jedit", MetricsType.CLASSIC_METRICS, 4.2, DataSource.PROMISE)); add(new DataFile("jedit-4.3_prepared.arff", "jedit", MetricsType.CLASSIC_METRICS, 4.3, DataSource.PROMISE)); add(new DataFile("log4j-1.0_prepared.arff", "log4j", MetricsType.CLASSIC_METRICS, 1.0, DataSource.PROMISE)); add(new DataFile("log4j-1.1_prepared.arff", "log4j", MetricsType.CLASSIC_METRICS, 1.1, DataSource.PROMISE)); add(new DataFile("log4j-1.2_prepared.arff", "log4j", MetricsType.CLASSIC_METRICS, 1.2, DataSource.PROMISE)); add(new DataFile("lucene-2.0_prepared.arff", "lucene", MetricsType.CLASSIC_METRICS, 2.0, DataSource.PROMISE)); add(new DataFile("lucene-2.2_prepared.arff", "lucene", MetricsType.CLASSIC_METRICS, 2.2, DataSource.PROMISE)); add(new DataFile("lucene-2.4_prepared.arff", "lucene", MetricsType.CLASSIC_METRICS, 2.4, DataSource.PROMISE)); add(new DataFile("poi-1.5_prepared.arff", "poi", MetricsType.CLASSIC_METRICS, 1.5, DataSource.PROMISE)); add(new DataFile("poi-2.0_prepared.arff", "poi", MetricsType.CLASSIC_METRICS, 2.0, DataSource.PROMISE)); add(new DataFile("poi-2.5_prepared.arff", "poi", MetricsType.CLASSIC_METRICS, 2.5, DataSource.PROMISE)); add(new DataFile("poi-3.0_prepared.arff", "poi", MetricsType.CLASSIC_METRICS, 3.0, DataSource.PROMISE)); add(new DataFile("synapse-1.0_prepared.arff", "synapse", MetricsType.CLASSIC_METRICS, 1.0, DataSource.PROMISE)); add(new DataFile("synapse-1.1_prepared.arff", "synapse", MetricsType.CLASSIC_METRICS, 1.1, DataSource.PROMISE)); add(new DataFile("synapse-1.2_prepared.arff", "synapse", MetricsType.CLASSIC_METRICS, 1.2, DataSource.PROMISE)); add(new DataFile("tomcat_prepared.arff", "tomcat", MetricsType.CLASSIC_METRICS, 1.0, DataSource.PROMISE)); add(new DataFile("velocity-1.4_prepared.arff", "velocity", MetricsType.CLASSIC_METRICS, 1.4, DataSource.PROMISE)); add(new DataFile("velocity-1.5_prepared.arff", "velocity", MetricsType.CLASSIC_METRICS, 1.5, DataSource.PROMISE)); add(new DataFile("velocity-1.6_prepared.arff", "velocity", MetricsType.CLASSIC_METRICS, 1.6, DataSource.PROMISE)); add(new DataFile("xalan-2.5_prepared.arff", "xalan", MetricsType.CLASSIC_METRICS, 2.5, DataSource.PROMISE)); add(new DataFile("xalan-2.6_prepared.arff", "xalan", MetricsType.CLASSIC_METRICS, 2.6, DataSource.PROMISE)); add(new DataFile("xalan-2.4_prepared.arff", "xalan", MetricsType.CLASSIC_METRICS, 2.4, DataSource.PROMISE)); add(new DataFile("xalan-2.7_prepared.arff", "xalan", MetricsType.CLASSIC_METRICS, 2.7, DataSource.PROMISE)); add(new DataFile("xerces-1.2_prepared.arff", "xerces", MetricsType.CLASSIC_METRICS, 1.2, DataSource.PROMISE)); add(new DataFile("xerces-1.3_prepared.arff", "xerces", MetricsType.CLASSIC_METRICS, 1.3, DataSource.PROMISE)); add(new DataFile("xerces-1.4_prepared.arff", "xerces", MetricsType.CLASSIC_METRICS, 1.4, DataSource.PROMISE)); add(new DataFile("xerces-init_prepared.arff", "xerces", MetricsType.CLASSIC_METRICS, 1.0, DataSource.PROMISE)); // bug prediction dataset // all data combined add(new DataFile("allchange-metrics.arff", "All", MetricsType.CHANGE_METRICS, 1.0, DataSource.BUG_INF)); add(new DataFile("all_combined.arff", "All", MetricsType.COMBINED_METRICS, 1.0, DataSource.BUG_INF)); add(new DataFile("allsingle-version-ck-oo.arff", "All", MetricsType.CLASSIC_METRICS, 1.0, DataSource.BUG_INF)); // single files add(new DataFile("change-metrics_prepared.arff", "eclipse-jdt", MetricsType.CHANGE_METRICS, 1.0, DataSource.BUG_INF)); add(new DataFile("single-version-ck-oo_prepared.arff", "eclipse-jdt", MetricsType.CLASSIC_METRICS, 1.0, DataSource.BUG_INF)); add(new DataFile("change-metrics_prepared.arff", "eclipse-pde", MetricsType.CHANGE_METRICS, 1.0, DataSource.BUG_INF)); add(new DataFile("single-version-ck-oo_prepared.arff", "eclipse-pde", MetricsType.CLASSIC_METRICS, 1.0, DataSource.BUG_INF)); add(new DataFile("change-metrics_prepared.arff", "equinox-framework", MetricsType.CHANGE_METRICS, 1.0, DataSource.BUG_INF)); add(new DataFile("single-version-ck-oo_prepared.arff", "equinox-framework", MetricsType.CLASSIC_METRICS, 1.0, DataSource.BUG_INF)); add(new DataFile("change-metrics_prepared.arff", "lucene", MetricsType.CHANGE_METRICS, 1.0, DataSource.BUG_INF)); add(new DataFile("single-version-ck-oo_prepared.arff", "lucene", MetricsType.CLASSIC_METRICS, 1.0, DataSource.BUG_INF)); add(new DataFile("change-metrics_prepared.arff", "mylyn", MetricsType.CHANGE_METRICS, 1.0, DataSource.BUG_INF)); add(new DataFile("single-version-ck-oo_prepared.arff", "mylyn", MetricsType.CLASSIC_METRICS, 1.0, DataSource.BUG_INF)); }}; /** * @param name the file we want * @return the file object */ public static IDataFile getFile(String name) { return findFileByCondition(file -> file.getName().equals(name)); } public static HashMap<String, List<IDataFile>> getProjects() throws Exception { List<String> projectNames = files.stream() .filter(iDataFile -> iDataFile.getDataSource() == DataSource.PROMISE && !iDataFile.getProjectName().equals("All")) .map(IDataFile::getProjectName).collect(Collectors.toList()); if (projectNames == null || projectNames.size() == 0) { throw new Exception("No projects found"); } final HashMap<String, List<IDataFile>> projects = new HashMap<>(); projectNames.forEach(s -> { List<IDataFile> projectFiles = files.stream().filter(f -> f.getDataSource() == DataSource.PROMISE && f.getProjectName().equals(s)).collect(Collectors.toList()); if (projectFiles.size() > 1) { projects.put(s, projectFiles); } }); return projects; } /** * Find a file by a certain criteria. * * @param condition criteria to be met * @return file object or {@code null} */ private static IDataFile findFileByCondition(ICondition condition) { for (IDataFile f : files) { if (condition.callback(f)) { return f; } } return null; } public interface ICondition { boolean callback(IDataFile file); } public static ArrayList<IDataFile> getFiles() { return files; } // public static void main(String[] args) { // // test file paths // for (IDataFile file : files) { // System.out.println(FileUtils.checkIfFileExists(file.getPath()) + " <= " + file.getPath()); // } // } }
<gh_stars>10-100 module Writer.Formats.Example where --- ^^^ CHANGE THIS TO THE NAME OF THE FILE / YOUR FORMAT ----------------------------------------------------------------------------- {- This is an example file, which explains the basics to add a new - writer to the tool. Basically, a writer is a function that turns the - internal representation of the specification into a string that - represents the specification in the desired format. Additionally, a - parition file can be created, as it is needed for some formats. In - addition to creating this file the following files need to be changed: - - Writer/Formats.hs: - - Add an internal name for your format here and the string which - specifies the format on the command line. If your format only - supports lower case signal names, you can also enable an - automatic conversion here. Finally, if you use an operator - config, link it here. - - Writer.hs: - - Add a link here to call your writer procedure. - - Info.hs: (optional) - - Add your format with a short description to the '--help' command - line output. - -} import Config import Simplify import Data.Error import Data.Specification import Writer.Eval import Writer.Data import Writer.Utils ----------------------------------------------------------------------------- {- The easies way to create a new format is to take this file as it is - and just change the names of the operators below, their precedence - and their associativity. Thereby, for the precedence a lower value - means higher precedence, where two operators with the same precedence - value are threated equally. The associativity is either: 'AssocLeft' - or 'AssocRight'. If an operator can be derived from the others, then - it can be disabled by using 'UnaryOpUnsupported' or - 'binaryOpUnsupported', respectively. - - The writer then provieds the LTL expression using your operator names - and also already supports pretty printing. -} opConfig :: OperatorConfig opConfig = OperatorConfig { tTrue = "<fancy true symbol>" , fFalse = "<fancy false symbol>" , opNot = UnaryOp "<fancy not symbol>" 1 , opAnd = BinaryOp "<fancy and symbol>" 6 AssocLeft , opOr = BinaryOp "<fancy or symbol>" 7 AssocLeft , opImplies = BinaryOp "<fancy implication symbol>" 8 AssocRight , opEquiv = BinaryOp "<fancy equivalence symbol>" 8 AssocLeft , opNext = UnaryOp "<fancy next symbol>" 2 , opFinally = UnaryOp "<fancy finally symbol>" 3 , opGlobally = UnaryOp "<fancy globally symbol>" 4 , opUntil = BinaryOp "<fancy until symbol>" 5 AssocRight , opRelease = BinaryOp "<fancy release symbol>" 9 AssocLeft , opWeak = BinaryOpUnsupported } ----------------------------------------------------------------------------- {- The core of each writer is the writing function, which turns the - internal format into the desired format. Thereby consider that the - internal representation still allows sets and functions which are not - resolved yet. The writer gets as input the configuration, which - contains all settings passed via the command line (see Config.hs for - more info), and the specification that contains the internal - representation. The writer returns a String, which contains the - respecitve content of the main file. - - Feel free to adapt this function according to you needs. However, - the following functions may be useful to simplify you life: - - (es,ss,rs,as,is,gs) <- eval c s - - The function gets the configuration and the specification s and - returns six lists of LTL formulas: the initial configuration of - the environment, the initial configuration of the system, the - requirements, the assumptions, the invariants, and the guarantees. - - fml <- merge es ss rs as is gs - - To combine the lists returned by 'eval' you can use the function - merge, which composes them to one formula in the predefined way. - Thereby, the function already takes care that no unneccessary - constructs are introduced, in case one or multiple of the lists - are empty. - - fml' <- simplify (adjust c opConfig) fml - - This function applies all simplifications to the formula fml, - that are enabled via the command line. It is recommended to call - this functions to support these simplifiactions in you format. - If you have unsupported operators you have to adjust the - configuration such that they can be removed by 'simplify'. - - str <- printformula opConfig mode fml - - A simple printer (supporting pretty printing) to move from the - internal representation to the desired string representation. - Thereby mode selects whether pretty printing or fully - parenthesized printing should be used. It is recommended to use - the passed value stored in 'outputMode c' here. Finally, the - opConfig structure, which may be define as above, fixes the - names of the operators used here. The function uses the standard - operator precedence for pretty printing. - - These constructs mostly should suffice to create a writer for simple - output formats. However, surely also more advanced stuff can be done - (this is haskell ;-). To get further information into this direction - it is recommended to first have a look at the other already existing - formats. For even more detailed information you may have a look at - "Config.hs", "Data.LTL.hs", or "Data.Specification". - - Finally: Have fun :-) - -} writeFormat :: Configuration -> Specification -> Either Error String writeFormat c s = do (es,ss,rs,as,is,gs) <- eval c s fml0 <- merge es ss rs as is gs fml1 <- simplify (adjust c opConfig) fml0 printFormula opConfig (outputMode c) (quoteMode c) fml1 -----------------------------------------------------------------------------
/** * @author denghuabing * @version V1.0 * @description: TODO * @date 2020/9/8 **/ @Data public class DeviceImportForm extends ImportErrorData { @ExcelField(title = "终端号", required = true, repeatable = false) private String deviceNumber; // 终端编号 /** * 所属企业名称 */ @ExcelField(title = "所属企业", required = true) private String groupNameImport; private String groupName; private String groupId; @ExcelField(title = "通讯类型", required = true) private String deviceType; // 通讯类型 /** * 终端厂商 */ @ExcelField(title = "终端厂商", required = true) private String terminalManufacturer; /** * 终端型号id */ private String terminalTypeId; /** * 终端型号 */ @ExcelField(title = "终端型号", required = true) private String terminalType; private Integer channelNumber; // 通道数 private String isVideos; // 是否视频 private Integer isVideo; @ExcelField(title = "功能类型", required = true) private String functionalType; // 功能类型 @ExcelField(title = "终端名称") private String deviceName; // 终端名称 /** * 注册信息-制造商ID */ @ExcelField(title = "制造商ID") private String manufacturerId; /** * 注册信息-终端型号 */ @ExcelField(title = "终端型号(注册)") private String deviceModelNumber; @ExcelField(title = "MAC地址") private String macAddress; @ExcelField(title = "制造商") private String manuFacturer; // 制造商 @ExcelField(title = "条码") private String barCode; // 条码 @ExcelField(title = "启停状态") private String isStarts; // 启停状态 @DateTimeFormat(pattern = "yyyy-MM-dd") private Date installTime; //安装时间 @ExcelField(title = "安装日期") private String installTimeStr; // 安装时间Str @DateTimeFormat(pattern = "yyyy-MM-dd") private Date procurementTime;//采购时间 @ExcelField(title = "采购日期") private String procurementTimeStr;//采购时间 /** * 安装单位 */ @ExcelField(title = "安装单位") private String installCompany; /** * 联系人 */ @ExcelField(title = "联系人") private String contacts; /** * 联系方式 */ @ExcelField(title = "联系方式") private String telephone; /** * 是否符合要求,用于报表导入导出。 * 1:是 * 0:否 */ @ExcelField(title = "是否符合要求") private String complianceRequirementsStr; @ExcelField(title = "备注") private String remark; @ExcelField(title = "错误信息", type = 1) private String errorMsg; }
Review of Pain and Prejudice One of the most urgent issues confronting science these days is identifying ways to do research that will increase its impact on pressing problems. While this concern is hardly new, the pronounced current interest is reflected in the large number of approaches being explored to address this problem. They include work on science to action, engaged research, community-based participatory research, participatory action research, citizen science, and the democratization of science. All reflect efforts to take on the problematic nature of science as it has come to be practiced. Karen Messing’s book, Pain and Prejudice: What Science Can Learn about Work from the People Who Do It, is a must read on this theme of the obstacles to science being effective in addressing workplace issues.
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { LugaresController } from './controller/lugares.controller'; import { Lugares } from './models/lugares.entity'; import { LugaresService } from './service/lugares.service'; @Module({ imports: [TypeOrmModule.forFeature([Lugares])], controllers: [LugaresController], providers: [LugaresService] }) export class LugaresModule {}
Get the biggest Weekday Swansea City FC stories by email Subscribe Thank you for subscribing We have more newsletters Show me See our privacy notice Could not subscribe, try again later Invalid Email Swansea City have offered a cut-price deal to Athletic Bilbao for versatile defender Jon Aurtenetxe – according to reports in Spain. The left back, turned centre back is available for around £150,000 after a season of struggle in La Liga. Aurtenetxe only made seven league appearances as Los Leones missed out on a Europa League spot behind Villarreal and Sevilla but could interest Garry Monk if he can get him for next to nothing - even though most of the Swans' summer business is done. How Swansea go about signing players In an article titled “Swansea return to bid for Aurtenetxe” Basque news outlet El Correo say the Swans, who made a January bid for the 23-year-old defender, have come back for more. The player, who was told he's surplus to requirements at the club he progressed through the youth ranks of in June, has several options on the table, including Athletic's Spanish rivals Levante and Espanyol. Watch: The Swans will hoping to improve his timing! Video Loading Video Unavailable Click to play Tap to play The video will start in 8 Cancel Play now He enjoyed a spell on loan at Celta Vigo the season before last but found first team football hard to come by on his return, even though the Swans' January advances were turned down flat. The full list of Swansea City ins and outs so far this summer Now El Correo reporter Juanma Mallo says: “The Welsh outfit knocked on the door in the winter market and offered to pay 200,000 euros but directors rejected the plan. “It now emerges the player, who has interested Levante and Espanyol due to his versatility, has the option of turning to Swansea too.”
Characterization and exposure measurement for indium oxide nanofibers generated as byproducts in the LED manufacturing environment ABSTRACT This article aimed to elucidate the physicochemical characteristics and exposure concentration of powder and airborne particles as byproducts generated from indium tin oxide thin film process by an electron beam evaporation method during maintenance in light-emitting diode manufacturing environment. The chemical composition, size, shape, and crystal structure of powder and airborne particles as byproducts were investigated using a scanning electron microscope equipped with energy dispersive spectrometer, and an X-ray diffractometer. The number and mass concentration measurements of airborne particles were performed by using an optical particle counter of direct-reading aerosol monitor and an inductively coupled plasma-mass spectrometry after sampling, respectively. The airborne particles are composed of oxygen and indium. On the other hand, the powder byproducts consist mostly of oxygen and indium, but tin was found as a minor component. The shapes of the airborne and powder byproducts were fiber type. The length and diameter of fibrous particles were approximately 500–2,000 nm and 30–50 nm, respectively. The powder byproducts indicated indium oxide nanofibers with a rhombohedral structure. On the other hand, the indium oxide used as a source material in the preparation of ITO target showed spherical morphology with a body-centered cubic structure, and it was the same as that of the pure crystalline indium oxide powder. During maintenance, the number concentrations ranged from 350–75,693 particles/ft3, and arithmetic mean±standard deviation and geometric mean±geometric standard deviation were 11,624±15,547 and 4,846±4.12 particles/ft3, respectively. Meanwhile, under the same conditions, the airborne mass concentrations of the indium based on respirable particle size (3.5 µm cut-point 50%) were 0.09–0.19 µg/m3. Physicochemical characteristics of nanoparticle can affect toxicity so the fact that shape and crystal structure have changed is important. Thus, nanoparticle occupational toxicology greatly needs observations like this.
// Day 8: Memory Maneuver // #[derive(Default, Debug, PartialEq)] pub struct Node { children: Vec<Node>, metadata: Vec<usize>, length: usize, // Total count of numbers in this node. For root, this is the total count of the tree } impl std::convert::AsRef<Node> for Node { fn as_ref(&self) -> &Node { &self } } impl Node { fn construct(stream: &[usize]) -> Node { let (num_children, num_metadata) = (stream[0], stream[1]); let mut node = Node { length: 2, ..Node::default() }; for _ in 0..num_children { let child = Node::construct(&stream[node.length..]); node.length += child.length; node.children.push(child); } for _ in 0..num_metadata { let meta = stream[node.length]; node.metadata.push(meta); node.length += 1; } node } fn sum_metadata(&self) -> usize { let sum: usize = self.children.iter().map(|c| c.sum_metadata()).sum(); // Sum of children sum + self.metadata.iter().sum::<usize>() // Sum of self } fn sum_complex(&self) -> usize { if self.children.is_empty() { return self.metadata.iter().sum::<usize>(); } // Get all children that can be indexed by the metadata (accounting for indexing starting at 1) let sum_iter = self .metadata .iter() .filter(|&&m| m < self.children.len() + 1 && m != 0) .map(|&m| &self.children[m - 1]); sum_iter.map(|c| c.sum_complex()).sum() } } #[aoc_generator(day8)] pub fn input_tree(input: &str) -> Node { let stream: Vec<usize> = input .split_whitespace() .map(|n| n.parse().unwrap()) .collect(); Node::construct(&stream) } #[aoc(day8, part1)] pub fn part1(root: &Node) -> usize { root.sum_metadata() } #[aoc(day8, part2)] pub fn part2(root: &Node) -> usize { root.sum_complex() } #[cfg(test)] mod tests { use super::*; static TEST_STR: &str = "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2"; #[test] fn sample1() { assert_eq!(part1(&input_tree(TEST_STR)), 138); } #[test] fn sample2() { assert_eq!(part2(&input_tree(TEST_STR)), 66); } }
package main import ( "database/sql" cdns "github.com/mosajjal/dnszeppelin" mkdns "github.com/miekg/dns" "github.com/stretchr/testify/assert" "net" "sync" "testing" "time" ) func TestSendData(t *testing.T) { resultChannel := make(chan cdns.DNSResult, 1) done := make(chan bool) var wg sync.WaitGroup go output(resultChannel, done, &wg, "localhost:9000", 10, 1, 10, "default") defer close(done) res := cdns.DNSResult{ Timestamp: time.Now(), IPVersion: 4, Protocol: "udp", SrcIP: net.IPv4(127, 0, 0, 1), DstIP: net.IPv4(10, 0, 0, 1), PacketLength: 128, } res.DNS.SetQuestion("example.com.", mkdns.TypeA) resultChannel <- res // Wait for the insert time.Sleep(10 * time.Second) // Check the data was inserted connect, err := sql.Open("clickhouse", "tcp://127.0.0.1:9000?debug=false") if err != nil { t.Fatal(err) } rows, err := connect.Query("SELECT Server, IPVersion FROM DNS_LOG LIMIT 1") if err != nil { t.Fatal(err) } for rows.Next() { var ( Server string IPVersion uint8 ) if err := rows.Scan(&Server, &IPVersion); err != nil { t.Fatal(err) } assert.Equal(t, "default", Server) assert.Equal(t, res.IPVersion, IPVersion) } }
/* * Copyright (C)2016 - SMBJ Contributors * * 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. */ package com.hierynomus.spnego; import com.hierynomus.asn1.ASN1InputStream; import com.hierynomus.asn1.ASN1OutputStream; import com.hierynomus.asn1.encodingrules.der.DERDecoder; import com.hierynomus.asn1.encodingrules.der.DEREncoder; import com.hierynomus.asn1.types.ASN1Object; import com.hierynomus.asn1.types.ASN1Tag; import com.hierynomus.asn1.types.constructed.ASN1Sequence; import com.hierynomus.asn1.types.constructed.ASN1TaggedObject; import com.hierynomus.asn1.types.primitive.ASN1Enumerated; import com.hierynomus.asn1.types.primitive.ASN1ObjectIdentifier; import com.hierynomus.asn1.types.string.ASN1OctetString; import com.hierynomus.protocol.commons.buffer.Buffer; import com.hierynomus.protocol.commons.buffer.Endian; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; /** * This class can encode and decode the SPNEGO negTokenInit Token. * <p/> * The entire token is an ASN.1 DER encoded sequence of bytes in little endian byte encoding. * <p/> * The following if the ASN.1 specification of the full structure of the token: * <p/> * <pre> * NegotiationToken ::= CHOICE { * negTokenInit [0] NegTokenInit, * negTokenTarg [1] NegTokenTarg * } * * NegTokenTarg ::= SEQUENCE { * negResult [0] ENUMERATED { * accept_completed (0), * accept_incomplete (1), * rejected (2) } OPTIONAL, * supportedMech [1] MechType OPTIONAL, * responseToken [2] OCTET STRING OPTIONAL, * mechListMIC [3] OCTET STRING OPTIONAL * } * * MechType ::= OBJECT IDENTIFIER * </pre> * <p/> * In the context of this class only the <em>NegTokenTarg</em> is covered. */ public class NegTokenTarg extends SpnegoToken { private BigInteger negotiationResult; private ASN1ObjectIdentifier supportedMech; private byte[] responseToken; private byte[] mechListMic; public NegTokenTarg() { super(0x01, "NegTokenTarg"); } // Override writeGss for NTLMSSP_AUTH since Samba does not like putting the OID for SPNEGO protected void writeGss(Buffer<?> buffer, ASN1Object negToken) throws IOException { ASN1TaggedObject negotiationToken = new ASN1TaggedObject(ASN1Tag.contextSpecific(0x01).constructed(), negToken, true); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ASN1OutputStream out = new ASN1OutputStream(new DEREncoder(), baos)) { out.writeObject(negotiationToken); } buffer.putRawBytes(baos.toByteArray()); } public void write(Buffer<?> buffer) throws SpnegoException { List<ASN1Object> negTokenTarg = new ArrayList<>(); try { if (negotiationResult != null) { negTokenTarg.add(new ASN1TaggedObject(ASN1Tag.contextSpecific(0x0).constructed(), new ASN1Enumerated(negotiationResult))); } if (supportedMech != null) { negTokenTarg.add(new ASN1TaggedObject(ASN1Tag.contextSpecific(0x01).constructed(), supportedMech)); } if (responseToken != null && responseToken.length > 0) { negTokenTarg.add(new ASN1TaggedObject(ASN1Tag.contextSpecific(0x02).constructed(), new ASN1OctetString(responseToken))); } if (mechListMic != null && mechListMic.length > 0) { negTokenTarg.add(new ASN1TaggedObject(ASN1Tag.contextSpecific(0x03).constructed(), new ASN1OctetString(mechListMic))); } writeGss(buffer, new ASN1Sequence(negTokenTarg)); } catch (IOException e) { throw new SpnegoException("Could not write NegTokenTarg to buffer", e); } } public NegTokenTarg read(byte[] bytes) throws SpnegoException { return read(new Buffer.PlainBuffer(bytes, Endian.LE)); } private NegTokenTarg read(Buffer<?> buffer) throws SpnegoException { try (ASN1InputStream is = new ASN1InputStream(new DERDecoder(), buffer.asInputStream())) { ASN1Object instance = is.readObject(); parseSpnegoToken(instance); } catch (IOException e) { throw new SpnegoException("Could not read NegTokenTarg from buffer", e); } return this; } @Override protected void parseTagged(ASN1TaggedObject asn1TaggedObject) throws SpnegoException { switch (asn1TaggedObject.getTagNo()) { case 0: readNegResult(asn1TaggedObject.getObject()); break; case 1: readSupportedMech(asn1TaggedObject.getObject()); break; case 2: readResponseToken(asn1TaggedObject.getObject()); break; case 3: readMechListMIC(asn1TaggedObject.getObject()); break; default: throw new SpnegoException("Unknown Object Tag " + asn1TaggedObject.getTagNo() + " encountered."); } } private void readResponseToken(ASN1Object responseToken) throws SpnegoException { if (!(responseToken instanceof ASN1OctetString)) { throw new SpnegoException("Expected the responseToken (OCTET_STRING) contents, not: " + responseToken); } this.responseToken = ((ASN1OctetString) responseToken).getValue(); } private void readMechListMIC(ASN1Object mic) throws SpnegoException { if (!(mic instanceof ASN1OctetString)) { throw new SpnegoException("Expected the responseToken (OCTET_STRING) contents, not: " + mic); } this.mechListMic = ((ASN1OctetString) mic).getValue(); } private void readSupportedMech(ASN1Object supportedMech) throws SpnegoException { if (!(supportedMech instanceof ASN1ObjectIdentifier)) { throw new SpnegoException("Expected the supportedMech (OBJECT IDENTIFIER) contents, not: " + supportedMech); } this.supportedMech = (ASN1ObjectIdentifier) supportedMech; } private void readNegResult(ASN1Object object) throws SpnegoException { if (!(object instanceof ASN1Enumerated)) { throw new SpnegoException("Expected the negResult (ENUMERATED) contents, not: " + supportedMech); } this.negotiationResult = ((ASN1Enumerated) object).getValue(); } public BigInteger getNegotiationResult() { return negotiationResult; } public void setNegotiationResult(BigInteger negotiationResult) { this.negotiationResult = negotiationResult; } public ASN1ObjectIdentifier getSupportedMech() { return supportedMech; } public void setSupportedMech(ASN1ObjectIdentifier supportedMech) { this.supportedMech = supportedMech; } public byte[] getResponseToken() { return responseToken; } public void setResponseToken(byte[] responseToken) { this.responseToken = responseToken; } public byte[] getMechListMic() { return mechListMic; } public void setMechListMic(byte[] mechListMic) { this.mechListMic = mechListMic; } }
package aesf_test import ( . "github.com/vitas/artemis/aesf" "testing" ) type MockWorld struct{} func (mw MockWorld) GetName() string { return "MockWorld" } func (mw *MockWorld) Initialize() {} func (mw MockWorld) GetEntityManager() *EntityManager { return nil } func (mw MockWorld) GetSystemManager() *SystemManager { return nil } func (mw MockWorld) GetTagManager() *TagManager { return nil } func (mw MockWorld) GetGroupManager() *GroupManager { return nil } func (mw *MockWorld) CreateEntity() *Entity { return nil } func (mw *MockWorld) DeleteEntity(e *Entity) {} func (mw *MockWorld) RefreshEntity(e *Entity) {} func (mw MockWorld) GetEntity(id int) *Entity { return nil } func (mw MockWorld) GetManagers() []Manager { return []Manager{} } func (mw MockWorld) GetDelta() int64 { return 0 } func (mw *MockWorld) SetDelta(delta int64) {} func (mw MockWorld) LoopStart() {} func TestTagManager(t *testing.T) { var ( w World tm *TagManager ) w = &MockWorld{} tm = NewTagManager(w) e1, e2, e3, e4 := NewEntity(w, 1), NewEntity(w, 2), NewEntity(w, 3), NewEntity(w, 4) tm.Register("tag1", e1) tm.Register("tag2", e2) tm.Register("tag3", e3) tm.Register("tag4", e4) if len(tm.GetTags()) != 4 { t.Errorf("Register failed, expected 4 was %d", len(tm.GetTags())) } tm.Unregister("tag2") if len(tm.GetTags()) != 3 { t.Errorf("Unregister failed, expected 3 was %d", len(tm.GetTags())) } tm.Remove(e3) if len(tm.GetTags()) != 2 { t.Errorf("Remove failed, expected 2 was %d", len(tm.GetTags())) } //t.Errorf("%#v", tm.GetTags()) }
<gh_stars>0 package pl.patryk.wine.model; import pl.patryk.wine.model.enums.WineColor; import pl.patryk.wine.model.enums.WineType; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.util.Objects; @Entity(name = "twine") public class Wine { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @NotEmpty private String name; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "producerId") @NotNull @NotEmpty private Producer producer; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "countryId") @NotNull @NotEmpty private Country country; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "regionId") @NotNull @NotEmpty private Region region; @NotNull @NotEmpty private Integer vintage; @Enumerated(EnumType.STRING) @NotNull @NotEmpty private WineType type; @Enumerated(EnumType.STRING) @NotNull @NotEmpty private WineColor color; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Producer getProducer() { return producer; } public void setProducer(Producer producer) { this.producer = producer; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getVintage() { return vintage; } public void setVintage(int vintage) { this.vintage = vintage; } public WineType getType() { return type; } public void setType(WineType type) { this.type = type; } public WineColor getColor() { return color; } public void setColor(WineColor color) { this.color = color; } public Wine(String name, Producer producer, Country country, Region region, Integer vintage, WineType type, WineColor color) { this.name = name; this.producer = producer; this.country = country; this.region = region; this.vintage = vintage; this.type = type; this.color = color; } public Wine() { } @Override public String toString() { return "Wine{" + "id=" + id + ", name='" + name + '\'' + ", producer='" + producer.getName() + '\'' + ", vintage=" + vintage + ", type=" + type.getDisplayValue() + ", color=" + color.getDisplayValue() + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Wine wine = (Wine) o; return name.equals(wine.name) && producer.equals(wine.producer) && country.equals(wine.country) && region.equals(wine.region) && vintage.equals(wine.vintage) && type == wine.type && color == wine.color; } @Override public int hashCode() { return Objects.hash(name, producer, country, region, vintage, type, color); } public static String getNameVintageProducerCountry(Wine wine) { StringBuilder sb = new StringBuilder(); sb.append(wine.getName()).append(" (").append(wine.getColor().getDisplayValue()) .append(", ").append(wine.getVintage()).append(", ") .append(wine.getProducer().getName()).append(", ").append(wine.getCountry().getCountryName()) .append(", ").append(wine.getRegion().getRegionName()).append(")"); return sb.toString(); } }
class QuizUserScores: scores: List[QuizUserScore] """ first has largest score """ count: Dict[int, int] """ id → answers """ questions: Dict[int, QuizQuestion]
// ApplyQueries sends the list of Queries to be applied (upserted) to the // Fleet instance. func (c *Client) ApplyQueries(specs []*fleet.QuerySpec) error { req := applyQuerySpecsRequest{Specs: specs} verb, path := "POST", "/api/latest/fleet/spec/queries" var responseBody applyQuerySpecsResponse return c.authenticatedRequest(req, verb, path, &responseBody) }
/* * Encodes an Asn1Object into a Open type field (X.691-0207, 10.2), used * mostly for encoding Sequence and SetOf extension additions. A decode method * hasn't been added as the extension additions should decoded * by their relevent Asn1Object decoders. */ public static Iterable<BitStream> encodeOpenTypeField( Asn1Object object){ PacketBuilder packetBuilder = new PacketBuilder(); packetBuilder.appendAll(object.encodePerAligned()); return encodeSemiConstrainedLengthOfBytes(packetBuilder.getPaddedBytes()); }
// LaunchFromShelf launches lacros-chrome via shelf. func LaunchFromShelf(ctx context.Context, tconn *chrome.TestConn, lacrosPath string) (*launcher.LacrosChrome, error) { const newTabTitle = "New Tab" if err := ash.ShowHotseat(ctx, tconn); err != nil { return nil, errors.Wrap(err, "failed to show hot seat") } testing.ContextLog(ctx, "Launch lacros via Shelf") if err := ash.LaunchAppFromShelf(ctx, tconn, apps.Lacros.Name, apps.Lacros.ID); err != nil { return nil, errors.Wrap(err, "failed to launch lacros via shelf") } testing.ContextLog(ctx, "Wait for Lacros window") if err := launcher.WaitForLacrosWindow(ctx, tconn, newTabTitle); err != nil { return nil, errors.Wrap(err, "failed to wait for lacros") } l, err := launcher.ConnectToLacrosChrome(ctx, lacrosPath, launcher.LacrosUserDataDir) if err != nil { return nil, errors.Wrap(err, "failed to connect to lacros") } return l, nil }
/* Allocate two source registers for three-operand instructions. */ static Reg ra_alloc2(ASMState *as, IRIns *ir, RegSet allow) { IRIns *irl = IR(ir->op1), *irr = IR(ir->op2); Reg left = irl->r, right = irr->r; if (ra_hasreg(left)) { ra_noweak(as, left); if (ra_noreg(right)) right = ra_allocref(as, ir->op2, rset_exclude(allow, left)); else ra_noweak(as, right); } else if (ra_hasreg(right)) { ra_noweak(as, right); left = ra_allocref(as, ir->op1, rset_exclude(allow, right)); } else if (ra_hashint(right)) { right = ra_allocref(as, ir->op2, allow); left = ra_alloc1(as, ir->op1, rset_exclude(allow, right)); } else { left = ra_allocref(as, ir->op1, allow); right = ra_alloc1(as, ir->op2, rset_exclude(allow, left)); } return left | (right << 8); }
export class Survey { name: string; questions: [ { question: string, answers: [ { answer: string, counter: number } ] } ]; public: boolean; author: string; filled: [ { startup: string; answers: Array<string> } ] }
def vstack_img_with_palette(top_img: np.ndarray, palette_img: np.ndarray) -> np.ndarray: img_n_rows = top_img.shape[0] palette_n_rows = palette_img.shape[0] img_n_cols = top_img.shape[1] palette_n_cols = palette_img.shape[1] fx = img_n_cols / palette_n_cols fy = fx rsz_cols = int(np.round(fx * palette_n_cols)) rsz_rows = int(np.round(fy * palette_n_rows)) rsz_palette_img = cv2.resize(palette_img, dsize=(rsz_cols, rsz_rows), interpolation=cv2.INTER_NEAREST) concat_rows = img_n_rows + rsz_rows vstack_img = np.zeros((concat_rows, img_n_cols, 3), dtype=np.uint8) vstack_img[:img_n_rows, :, :] = top_img vstack_img[img_n_rows:, :, :] = rsz_palette_img return vstack_img
def combine_s3_datasets(keys, dropnans=1): F = pd.read_csv(keys[0], index_col="ipst") T = pd.read_csv(keys[1], index_col="ipst") P = pd.read_csv(keys[2], index_col="ipst") print("Features: ", len(F)) print("Targets: ", len(T)) print("Preds: ", len(P)) data = F.join(T, how="left") if dropnans == 1: df0 = data.dropna(axis=0, inplace=False) print(f"NaNs Removed: {len(data) - len(df0)}") df1 = df0.join(P, how="left") elif dropnans == 2: df0 = data.join(P, how="left") df1 = df0.dropna(axis=0, inplace=False) print(f"NaNs Removed: {len(df0) - len(data)}") else: df1 = data.join(P, how="left") print(df1.isna().sum()) df1["ipst"] = df1.index df1.set_index("ipst", inplace=True, drop=False) df = df1.drop_duplicates(subset="ipst", keep="last", inplace=False) print("Final: ", len(df)) io.save_dataframe(df, "batch.csv") return df
import PersistencePointTuple from '../persistence-point-tuple'; import Bounds from '../bounds'; /** * The data returned by the loader */ export interface ILoaderData { readonly points: PersistencePointTuple[]; readonly bounds: number[]; readonly persistenceBounds: Bounds; } export interface ILoader { load(T: any): Promise<ILoaderData>; }
<reponame>planaria/rewin<filename>include/rewin/button_view.hpp #pragma once #include "view.hpp" #include "view_impl.hpp" #include "command.hpp" #include "margin_view.hpp" #include "view_messages.hpp" #include "win32_exception.hpp" namespace rewin { class button_view : public detail::view_impl<button_view, view> { protected: button_view() { } virtual void initialize() override { view::initialize(); *this += combine( rect_arranged_vertical().as_reactive(), is_hovered(), is_focused(), pressing().as_reactive()) .subscribe([&](const auto&) { auto window = owner_window().value().lock(); if (window) window->Invalidate(); }); int margin_x = GetSystemMetrics(SM_CXEDGE) + GetSystemMetrics(SM_CXFOCUSBORDER); int margin_y = GetSystemMetrics(SM_CYEDGE) + GetSystemMetrics(SM_CYFOCUSBORDER); margin_view_->margin() = margin(margin_x, margin_y); minimized_width() = margin_view_->minimized_width().as_reactive(); minimized_height() = margin_view_->minimized_height().as_reactive(); margin_view_->rect_arranged_horizontal() = rect_arranged_horizontal().as_reactive(); margin_view_->rect_arranged_vertical() = rect_arranged_vertical().as_reactive(); add_child(*margin_view_); enable() = click_command().as_reactive() .map([&](const auto& command) -> reactive<bool> { if (!command) return false; return command->can_execute(view_message(this->shared_from_this())); }).switch_on_next(); } public: virtual reactive<bool> is_hover_target() override { return enable_actual().as_reactive(); } virtual reactive<bool> is_focus_target() override { return enable_actual().as_reactive(); } virtual void on_paint(WTL::CDCHandle dc) override { WTL::CRect rect = rect_arranged_vertical().value(); UINT edge = pressing().value() ? EDGE_SUNKEN : EDGE_RAISED; REWIN_CHECK_WIN32(dc.DrawEdge(&rect, edge, BF_ADJUST | BF_MIDDLE | BF_RECT)); if (is_focused().value()) dc.DrawFocusRect(&rect); margin_view_->on_paint(dc); } virtual bool on_key_down(UINT nChar, UINT nRepCnt, UINT nFlags) override { if (!enable_actual().value()) return false; switch (nChar) { case VK_SPACE: if (nRepCnt == 1 && !pressing().value()) on_press(); return true; case VK_RETURN: on_click(); return true; case VK_ESCAPE: if (pressing().value()) on_release(); return true; } return false; } virtual bool on_key_up(UINT nChar, UINT nRepCnt, UINT nFlags) override { if (!enable_actual().value()) return false; switch (nChar) { case VK_SPACE: if (pressing().value()) { on_click(); on_release(); } return true; } return false; } virtual bool on_mouse_button(mouse_button button, mouse_action action, UINT nFlags, WTL::CPoint point) override { if (!enable_actual().value()) return false; if (button == mouse_button::left) { switch (action) { case mouse_action::down: case mouse_action::double_click: on_press(); break; case mouse_action::up: if (pressing().value()) { if (contains(rect_arranged_vertical().value(), point)) on_click(); on_release(); } break; } } return false; } reactive_property<std::vector<std::shared_ptr<view>>>& contents() { return margin_view_->contents(); } const reactive_property<bool>& pressing() { return pressing_; } reactive_property<std::shared_ptr<command<view_message>>>& click_command() { return click_command_; } private: void on_press() { auto w = owner_window().value().lock(); if (!w) return; w->capture_view() = this->shared_from_this(); w->focused_view() = this->shared_from_this(); pressing_ = true; } void on_release() { auto w = owner_window().value().lock(); if (!w) return; w->capture_view() = std::weak_ptr<view>(); pressing_ = false; } void on_click() { auto cmd = click_command_.value(); if (cmd) cmd->execute(view_message(this->shared_from_this())); } std::shared_ptr<margin_view> margin_view_ = margin_view::create(); reactive_property<bool> pressing_; reactive_property<std::shared_ptr<command<view_message>>> click_command_; }; }
import numpy as np def log_loss(M): return # Here you need to return a pair of vectors: # the logarithmic loss function from the task description # and its derivative. np.log2 and np.exp could be useful. def sigmoid_loss(M): return # Here you need to return a pair of vectors: # the sigmoid loss function from the task description # and its derivative. np.log2 and np.exp could be useful.
def send(self, msg, title=""): pass
#pragma once #include "GraphicsConstance.h" namespace Coocoo3DGraphics { using namespace Windows::Storage::Streams; public ref class ReadBackTexture2D sealed { public: void Reload(int width, int height, int bytesPerPixel); void GetDataTolocal(int index); Platform::Array<byte>^ GetRaw(int index); void GetRaw(int index, const Platform::Array<byte>^ bitmapData); int GetWidth() { return m_width; } int GetHeight() { return m_height; } virtual ~ReadBackTexture2D(); internal: Microsoft::WRL::ComPtr<ID3D12Resource> m_textureReadBack[c_frameCount] = {}; byte* m_mappedData = nullptr; byte* m_localData = nullptr; UINT m_width; UINT m_height; UINT m_bytesPerPixel; UINT m_rowPitch; }; }
// Makes progress on the puzzle using "simple" methods. // The simple methods are: // 1. If a cell is solved, then no other cell in the same row/column can be that value. // 2. If a row/column only has one cell that can be a certain value, then that cell has to be // that value. // This method will apply these two rules over and over again until no more progress can be // made using these rules. pub fn simple_solve(&mut self) { while self.can_simple_solve() { self.handle_solved_cells(); self.handle_unique_in_row(); self.handle_unique_in_column(); } }
def train_epoch_with_interactions(interaction_batches, params, model, randomize=True): if randomize: random.shuffle(interaction_batches) progbar = get_progressbar("train ", len(interaction_batches)) progbar.start() loss_sum = 0. for i, interaction_batch in enumerate(interaction_batches): assert len(interaction_batch) == 1 interaction = interaction_batch.items[0] if interaction.identifier == "raw/atis2/12-1.1/ATIS2/TEXT/TEST/NOV92/770/5": continue if 'sparc' in params.data_directory and "baseball_1" in interaction.identifier: continue batch_loss = model.train_step(interaction, params.train_maximum_sql_length) loss_sum += batch_loss torch.cuda.empty_cache() progbar.update(i) progbar.finish() total_loss = loss_sum / len(interaction_batches) return total_loss
Gated First Pass Radionuclide Ventriculography Methods, Validation, and Applications Electrocardiographic gating provides an alternative method of acquiring first pass radionuclide ventriculograms from both ventricles. This report details the methods of acquisition and analysis, provides validation and reproducibility data, and describes applications of gated first pass radionuclide ventriculography using a count-based method. Left ventricular ejection fractions measured by gated first pass were correlated quite closely with gated blood pool ventriculography (n=43; r=0.95) but less well with contrast angiography (n=23; r=0.72). The right ventricular ejection fractions measured by gated first pass compared favorably with gated blood pool ventriculography (n=32; r=0.93). When one observer processed the images two times, the reproducibilities of RVEF (n=10; r=0.99) and LVEF (n=10; r=0.88) were excellent. Similarly, when two observers processed the images independently, the reproducibilities of RVEF (n=11; r=0.99) and LVEF (n=11; r=0.98) were excellent. The first pass studies were obtained in a right anterior obliquity, which provided the best atrioventricular chamber separation and provided a different view of global ventricular function and segmental wall motion from that provided by the standard blood pool views.
/** * This class implements an output stream in which the data is written into a * byte array. The buffer automatically grows as data is written to it. The data * can be retrieved using <code>toByteArray()</code> and * <code>toString()</code>. * <p> * Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in this * class can be called after the stream has been closed without generating an * <tt>IOException</tt>. * * @author Arthur van Hoff * @since JDK1.0 */ public class ByteArrayOutputStream extends java.io.ByteArrayOutputStream { /** * Retuen the underlying byte array buffer. * * @return the current contents of this output stream, as a byte array. * @see java.io.ByteArrayOutputStream#size() */ public byte getByteArray()[] { return buf; } }
/** * Description of the Class * *@author jchoyt *@created August 19, 2002 */ public class FormBuilderTag extends BodyTagSupport { String className; String howMany; int number; int thread=1; String other; String title; final static String SECTION_CLOSE = "</td></tr></table></td></tr></table>\n"; final static String SECTION_OPENER_TEMPLATE = "<table summary=\"\" width=\"95%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td class=\"bord\"><table summary=\"\" width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"2\"><tr><th><:title:></th></tr><tr><td>\n"; /** * Constructor for the FormBuilderTag object */ public FormBuilderTag() { super(); } /** * Sets the className attribute of the FormBuilderTag object * *@param className The new className value */ public void setClassName( String className ) { this.className = className; } /** * Sets the howMany attribute of the FormBuilderTag object * *@param howMany The new howMany value */ public void setHowMany( String howMany ) { this.howMany = howMany; } /** * Sets the howMany attribute of the FormBuilderTag object */ public void setNumber() { if(howMany==null) { number=1; return; } number = Integer.parseInt( howMany ); } /** * Sets the howMany attribute of the FormBuilderTag object */ public void setThread(int threadNumber) { thread = threadNumber; } /** * Sets the other attribute of the FormBuilderTag object * *@param other The new other value */ public void setOther( String other ) { this.other = other; } /** * Sets the title attribute of the FormBuilderTag object * *@param title The new title value */ public void setTitle( String title ) { this.title = title; } /** * Gets the title attribute of the FormBuilderTag object * *@return The title value */ public String getTitle() { return title; } /** * Standard entry for the Tag - kinda like main() for stand alone apps * *@return Always 0. *@exception JspException Standard exception - ones not caught will fall * through to the ErrorPage.jsp */ public int doEndTag() throws JspException { DBMetaData md = ( DBMetaData ) pageContext.getAttribute( "DBMetaData" ); StringBuffer ret = new StringBuffer(); /* * add the HTML */ FormBuilderElement thisElement; try { thisElement = castElement(); } catch ( ServletException e ) { throw new MraldError( e ); } setNumber(); // ret.append(MiscUtils.replace(SECTION_OPENER_TEMPLATE, "<:title:>", title)); for ( int i = 0; i < number; i++ ) { ret.append( thisElement.getFBHtml( md, i , thread) ); if ( i < number - 1 ) { ret.append( "<hr width=\"90%\">\n" ); } } ret.append( SECTION_CLOSE ); try { pageContext.getOut().print( ret.toString() ); } catch ( java.io.IOException e ) { throw new JspException( e.getMessage() ); } return 0; } public int doStartTag() throws JspException { try{ pageContext.getOut().print( MiscUtils.replace(SECTION_OPENER_TEMPLATE, "<:title:>", title) ); } catch (Exception e ){ throw new JspException(); } return EVAL_BODY_INCLUDE; } /** * Based on the passed in class name, uses Reflection to create the new * ParserElement objects for inclusion in the MsgObject workingObjects * HashTable. * *@return ParserElement of the class defined by the * input String *@exception ServletException Description of the Exception */ protected FormBuilderElement castElement() throws ServletException { try { if ( className == null ) { return null; } Class classDefinition = Class.forName( className ); FormBuilderElement parserElement = ( FormBuilderElement ) classDefinition.newInstance(); return parserElement; } catch ( InstantiationException wfe ) { ServletException ce = new ServletException( wfe ); throw ce; } catch ( ClassNotFoundException cne ) { ServletException ce = new ServletException( cne ); throw ce; } catch ( IllegalAccessException iae ) { ServletException ce = new ServletException( iae ); throw ce; } } }
<reponame>gcalmettes/AdventOfCode2017<filename>2021/src/day10/main.rs use std::path::Path; use std::fs; use std::collections::HashMap; fn part1(input: &str) -> usize { let points = HashMap::from([ (')', 3), (']', 57), ('}', 1197), ('>', 25137), ]); let score = input.lines() .map(|line| { let mut stack = Vec::new(); for c in line.chars() { match c { // if closing, try to match to its corresponding opening ')' | ']' | '}' | '>' => match stack.pop() { Some(o) => { if o == '(' && c != ')' || o == '[' && c != ']' || o == '{' && c != '}' || o == '<' && c != '>' { // println!("corrupted, opening was {} but encountered {} as closing", o, c); match points.get(&c) { Some(p) => { // println!("-- points {}", p); return *p }, None => { // println!("-- shouldn't be there"); return 0 }, }; } else { // println!("Ok"); } }, None => { // println!("Not possible"); return 0 }, }, // else, it's an opening, add it to stack and continue o => { stack.push(o); }, } } // Everything went well, no penalty point return 0 }).sum(); score } fn part2(input: &str) -> usize { let points = HashMap::from([ ('(', 1), ('[', 2), ('{', 3), ('<', 4), ]); let mut scores = input.lines() .map(|line| { let mut stack = Vec::new(); for c in line.chars() { match c { // if closing, try to match to its corresponding opening ')' | ']' | '}' | '>' => match stack.pop() { Some(o) => { if o == '(' && c != ')' || o == '[' && c != ']' || o == '{' && c != '}' || o == '<' && c != '>' { // println!("corrupted, opening was {} but encountered {} as closing", o, c); return 0 } else { // println!("Ok"); } }, None => { // println!("Not possible"); return 0 }, }, // else, it's an opening, add it to stack and continue o => { stack.push(o); }, } } if stack.len() > 0 { // println!("Incomplete"); return stack.iter() .rev() .fold(0 as usize, |acc, cur| acc * 5 + points.get(cur).unwrap()) } // Everything went well, no penalty point return 0 }) .filter(|v| *v > 0) .collect::<Vec<_>>(); scores.sort(); let mid = scores.len() / 2; scores[mid] } fn main() { let path = Path::new("./inputs/day10.txt"); let input = fs::read_to_string(path).expect("Unable to read file"); let p1 = part1(&input); println!("{}", p1); let p2 = part2(&input); println!("{}", p2); }
def queryObject(uid, default=None):
def command_browse_callback(self): self.command_file.set(tkinter.filedialog.askopenfilename()) self.config['RobotSettings']['command_file'] = self.command_file.get()
/** * Created by chaobin on 1/14/15. */ public class TagFlowLayout extends ViewGroup implements TextWatcher, View.OnKeyListener, View.OnClickListener { private static final int INVALID_VALUE = -1; private SparseIntArray mCachedPosition = new SparseIntArray(); private EditText mInputView; /** * Comma in both English & Chinese */ private char[] mKeyChar = new char[]{',', ','}; /** * Key event of enter, comma */ private int[] mKeyCode = new int[]{ KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_COMMA, KeyEvent.KEYCODE_NUMPAD_COMMA }; private int mCheckIndex = INVALID_VALUE; private Decorator mDecorator; public TagFlowLayout(Context context) { this(context, null); } public TagFlowLayout(Context context, AttributeSet attrs) { super(context, attrs); mInputView = new EditText(context); mInputView.setBackgroundColor(Color.TRANSPARENT); mInputView.addTextChangedListener(this); mInputView.setOnKeyListener(this); mInputView.setPadding(0, 0, 0, 0); mInputView.setMinWidth(20); mInputView.setSingleLine(); mInputView.setGravity(Gravity.CENTER_VERTICAL); setDecorator(new SimpleDecorator(context)); addView(mInputView); setOnClickListener(this); previewInEditMode(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int maxWidth = 0; int maxHeight = 0; int width = 0; int height = 0; mCachedPosition.clear(); final int widthSpace = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); final int count = getChildCount(); int verticalCount = 0; for (int i = 0; i < count; ++i) { final View child = getChildAt(i); if (nullChildView(child)) { continue; } measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0); final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); int childWidthSpace = lp.leftMargin + child.getMeasuredWidth() + lp.rightMargin; int childHeightSpace = lp.topMargin + child.getMeasuredHeight() + lp.bottomMargin; if (maxWidth + childWidthSpace > widthSpace) { maxWidth = childWidthSpace; maxHeight = Math.max(maxHeight, childHeightSpace); height += maxHeight; mCachedPosition.put(i, ++verticalCount); } else { maxWidth += childWidthSpace; maxHeight = childHeightSpace; } width = Math.max(width, maxWidth); } height += maxHeight + getPaddingTop() + getPaddingBottom(); setMeasuredDimension(getImprovedSize(widthMeasureSpec, width), getImprovedSize(heightMeasureSpec, height)); } private boolean nullChildView(View child) { return child == null || child.getVisibility() == GONE; } private int getImprovedSize(int measureSpec, int size) { int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); switch (specMode) { case MeasureSpec.UNSPECIFIED: case MeasureSpec.AT_MOST: return size; case MeasureSpec.EXACTLY: return specSize; } return specSize; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childTop = getPaddingTop(); int childLeft = getPaddingLeft(); final int count = getChildCount(); for (int i = 0; i < count; i++) { View child = getChildAt(i); if (nullChildView(child)) { continue; } final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); if (mCachedPosition.get(i, INVALID_VALUE) != INVALID_VALUE) { childTop += lp.topMargin + childHeight + lp.bottomMargin; childLeft = getPaddingLeft(); } else if (childTop == getPaddingTop()) { childTop += lp.topMargin; } childLeft += lp.leftMargin; setChildFrame(child, childLeft, childTop, childWidth, childHeight); childLeft += childWidth + lp.rightMargin; } } private void setChildFrame(View child, int left, int top, int width, int height) { child.layout(left, top, left + width, top + height); } @Override protected LayoutParams generateLayoutParams(LayoutParams p) { MarginLayoutParams params = new MarginLayoutParams(p); if (mDecorator != null) { params.setMargins(mDecorator.getMargin()[0], mDecorator.getMargin()[1], mDecorator.getMargin()[2], mDecorator.getMargin()[3]); } return params; } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { MarginLayoutParams params = new MarginLayoutParams(getContext(), attrs); if (mDecorator != null) { params.setMargins(mDecorator.getMargin()[0], mDecorator.getMargin()[1], mDecorator.getMargin()[2], mDecorator.getMargin()[3]); } return params; } @Override protected LayoutParams generateDefaultLayoutParams() { MarginLayoutParams params = new MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, mDecorator != null ? mDecorator.getHeight() : ViewGroup.LayoutParams.WRAP_CONTENT); if (mDecorator != null) { params.setMargins(mDecorator.getMargin()[0], mDecorator.getMargin()[1], mDecorator.getMargin()[2], mDecorator.getMargin()[3]); } return params; } /** * set the keyCode list which trigger the TAG generation, the default keyCode are * {@link android.view.KeyEvent#KEYCODE_ENTER},{@link android.view.KeyEvent#KEYCODE_COMMA} * * @param keyChar comma on mobile are not always keyCode, null will be ignored * @param keyCode keyCode defined in {@link android.view.KeyEvent}, null will be ignored */ public void setActionKeyCode(char[] keyChar, int... keyCode) { if (keyChar != null && keyChar.length > 0) { mKeyChar = keyChar; } if (keyCode != null && keyCode.length > 0) { mKeyCode = keyCode; } } @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { if (isKeyCodeHit(keyCode)) { if (!TextUtils.isEmpty(mInputView.getText().toString())) { generateTag(mInputView.getText().toString()); } return true; } else if (KeyEvent.KEYCODE_DEL == keyCode) { if (TextUtils.isEmpty(mInputView.getText().toString())) { deleteTag(); return true; } } } return false; } private boolean isKeyCodeHit(int keyCode) { if (mKeyCode != null && mKeyCode.length > 0) { for (int key : mKeyCode) { if (key == keyCode) { return true; } } } return false; } private boolean isKeyCharHit(char keyChar) { if (mKeyChar != null && mKeyChar.length > 0) { for (char key : mKeyChar) { if (key == keyChar) { return true; } } } return false; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.length() > 0) { if (isKeyCharHit(s.charAt(0))) { mInputView.setText(""); } else if (isKeyCharHit(s.charAt(s.length() - 1))) { mInputView.setText(""); generateTag(s.subSequence(0, s.length() - 1) + ""); } } } @Override public void onClick(View v) { if (v instanceof TagFlowLayout) { mInputView.requestFocus(); InputMethodManager m = (InputMethodManager) getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); m.showSoftInput(mInputView, InputMethodManager.SHOW_FORCED); // clear check status if (mCheckIndex != INVALID_VALUE) { updateCheckStatus(getChildAt(mCheckIndex), false); mCheckIndex = INVALID_VALUE; } return; } final int index = indexOfChild(v); // skip unnecessary setting if (index != mCheckIndex) { mCheckIndex = index; updateCheckStatus(v, true); for (int i = 0; i < index; i++) { updateCheckStatus(getChildAt(i), false); } //skip input box for (int i = index + 1; i < getChildCount() - 1; i++) { updateCheckStatus(getChildAt(i), false); } } } private void deleteTag() { if (getChildCount() > 1) { removeViewAt(mCheckIndex == INVALID_VALUE ? indexOfChild(mInputView) - 1 : mCheckIndex); mCheckIndex = INVALID_VALUE; mInputView.requestFocus(); } } /** * Auto generate the last input content as tag label */ public void autoComplete() { if (!TextUtils.isEmpty(mInputView.getText().toString())) { generateTag(null); } } /** * can be null */ private void generateTag(CharSequence tag) { CharSequence tagString = tag == null ? mInputView.getText().toString() : tag; mInputView.getText().clear(); final int targetIndex = indexOfChild(mInputView); TextView tagLabel; if (mDecorator.getLayout() != INVALID_VALUE) { View view = View.inflate(getContext(), mDecorator.getLayout(), null); if (view instanceof TextView) { tagLabel = (TextView) view; } else { throw new IllegalArgumentException( "The custom layout for tagLabel label must have TextView as root element"); } } else { tagLabel = new TextView(getContext()); tagLabel.setPadding(mDecorator.getPadding()[0], mDecorator.getPadding()[1], mDecorator.getPadding()[2], mDecorator.getPadding()[3]); tagLabel.setTextSize(mDecorator.getTextSize()); } updateCheckStatus(tagLabel, false); tagLabel.setText(tagString); tagLabel.setSingleLine(); tagLabel.setGravity(Gravity.CENTER_VERTICAL); tagLabel.setEllipsize(TextUtils.TruncateAt.END); if (mDecorator.getMaxLength() != INVALID_VALUE) { InputFilter maxLengthFilter = new InputFilter.LengthFilter(mDecorator.getMaxLength()); tagLabel.setFilters(new InputFilter[]{maxLengthFilter}); } tagLabel.setClickable(true); tagLabel.setOnClickListener(this); addView(tagLabel, targetIndex); mInputView.requestFocus(); } private void updateCheckStatus(View view, boolean checked) { if (view == null) { return; } // don't reuse drawable for different tag label Drawable[] drawables = mDecorator.getBackgroundDrawable(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { view.setBackgroundDrawable(drawables[drawables.length > 1 ? (checked ? 1 : 0) : 0]); } else { view.setBackground(drawables[drawables.length > 1 ? (checked ? 1 : 0) : 0]); } final int[] color = mDecorator.getTextColor(); if (color != null && color.length > 0) { ((TextView) view).setTextColor((color[color.length > 1 ? (checked ? 1 : 0) : 0])); } } private void previewInEditMode() { if (isInEditMode()) { generateTag("Hot Tag Ckecked"); generateTag("TAG A"); generateTag("TAG B"); generateTag("TAG C"); updateCheckStatus(getChildAt(0), true); mInputView.setText("Input here..."); } } public void setDecorator(Decorator decorator) { if (decorator != null) { mDecorator = decorator; try { setInnerAttribute(); } catch (Exception e) { e.printStackTrace(); throw new UnknownError(e.getMessage() + "\n unavailable to setDecorator"); } } } /** * Make sure the input EditView looks like TextView label */ private void setInnerAttribute() throws XmlPullParserException, IOException, ClassNotFoundException { mInputView.setTextSize(mDecorator.getTextSize()); if (mDecorator.getMaxLength() != INVALID_VALUE) { InputFilter maxLengthFilter = new InputFilter.LengthFilter(mDecorator.getMaxLength()); mInputView.setFilters(new InputFilter[]{maxLengthFilter}); } if (mDecorator.getTextColor() != null && mDecorator.getTextColor().length > 1) { mInputView.setTextColor(mDecorator.getTextColor()[0]); } if (mDecorator.getLayout() != INVALID_VALUE) { XmlResourceParser parser = getResources().getLayout(mDecorator.getLayout()); final AttributeSet set = Xml.asAttributeSet(parser); int type = 0; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty } if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } final String name = parser.getName(); if ("TextView".equals(name) || Class.forName(name).isInstance(TextView.class)) { int[] attr = new int[]{ android.R.attr.layout_width, android.R.attr.layout_height, }; TypedArray array = getContext().obtainStyledAttributes(set, attr); final int height = array.getDimensionPixelSize(1, 0); if (height != 0) { MarginLayoutParams layoutParams = (MarginLayoutParams) mInputView .getLayoutParams(); layoutParams.height = height; } //TODO other useful attribute array.recycle(); } else { throw new InflateException(parser.getPositionDescription() + ": Only TextView or subclass of TextView is supported!"); } } } public CharSequence[] getTagArray() { final int count = getChildCount(); if (count > 1) { CharSequence[] tags = new CharSequence[count - 1]; for (int i = 0; i < count - 1; i++) { View child = getChildAt(i); if (child instanceof TextView) { tags[i] = ((TextView) child).getText(); } } return tags; } return new CharSequence[]{}; } public void setTagArray(CharSequence... tags) { for (CharSequence tag : tags) { generateTag(tag); } } public void clearTags() { while (getChildCount() > 1) { removeAllViews(); addView(mInputView); } } public void setInputable(boolean enable) { mInputView.setVisibility(enable ? View.VISIBLE : View.GONE); mInputView.setEnabled(enable); } /** * Implements your own Decorator to custom the tag view */ interface Decorator { /** * Size in unit of sp */ public int getTextSize(); /** * Padding on mLeftView, top, right, bottom in unit of dip */ public int[] getPadding(); /** * Margin on mLeftView, top, right, bottom in unit of dip */ public int[] getMargin(); /** * Color in format of AARRGGBB */ public int[] getTextColor(); /** * Tag view's background can be satisfied either by color or drawable resources, */ public Drawable[] getBackgroundDrawable(); /** * Size in unit of dip, if you provide custom layout by {@link #getLayout()}, it must have * the same height value */ public int getHeight(); /** * Provide your own layout id so you can custom the tag view what ever you like, * keep in mind the layout must have TextView as root element * * @return -1 will be ignored */ public int getLayout(); /** * @return */ public int getMaxLength(); } /** * Default decorator which will set on the TAG view */ public static class SimpleDecorator implements Decorator { protected int textSize; protected int[] textColor; protected int[] padding; protected int[] margin; protected int mTagHeight; protected int mRadius; public SimpleDecorator(Context context) { textSize = 14; final int p = getPixelSize(context, TypedValue.COMPLEX_UNIT_DIP, 5); padding = new int[]{p, p, p, p}; final int m = getPixelSize(context, TypedValue.COMPLEX_UNIT_DIP, 2); margin = new int[]{m, m, m, m}; mRadius = getPixelSize(context, TypedValue.COMPLEX_UNIT_DIP, 5); mTagHeight = getPixelSize(context, TypedValue.COMPLEX_UNIT_DIP, 30); textColor = new int[]{0xFF000000, 0xFFFFFFFF}; } private int getPixelSize(Context context, int unit, int size) { return (int) TypedValue .applyDimension(unit, size, context.getResources().getDisplayMetrics()); } @Override public int getTextSize() { return textSize; } @Override public int[] getPadding() { return padding; } @Override public int[] getMargin() { return margin; } @Override public int[] getTextColor() { return textColor; } public int getHeight() { return mTagHeight; } public Drawable[] getBackgroundDrawable() { return new Drawable[]{ newRoundRectShape(0xFF4285f4, mRadius), newRoundRectShape(0xFF3f51b5, mRadius) }; } @Override public int getLayout() { return INVALID_VALUE; } @Override public int getMaxLength() { return 20; } protected Drawable newRoundRectShape(int color, int radius) { ShapeDrawable shape = new ShapeDrawable(new RoundRectShape(new float[]{radius, radius, radius, radius, radius, radius, radius, radius}, null, null)); shape.getPaint().setStyle(Paint.Style.FILL); shape.getPaint().setColor(color); shape.getPaint().setAntiAlias(true); return shape; } } }
/** * Release any expired encumbrances on this account. */ void releaseExpiredEncumbrances() { while (!myEncumbrancesByExpiration.isEmpty()) { Encumbrance first = myEncumbrancesByExpiration.first(); if (first.isExpired()) { first.release(); } else { break; } } }
<reponame>rosm-project/rosm_geo<filename>src/rect.rs use bitflags::bitflags; use crate::coord::GeoCoord; use std::error; use std::fmt; #[derive(Debug, Clone, PartialEq)] pub struct GeoRect { top_left: GeoCoord, bottom_right: GeoCoord, } impl GeoRect { pub fn new(top_left: GeoCoord, bottom_right: GeoCoord) -> Result<Self, InvalidGeoRect> { if top_left.lat() < bottom_right.lat() { Err(InvalidGeoRect) } else { Ok(GeoRect { top_left, bottom_right }) } } pub fn top_left(&self) -> GeoCoord { self.top_left } pub fn bottom_right(&self) -> GeoCoord { self.bottom_right } pub fn center(&self) -> GeoCoord { let lat = (self.top_left.lat() + self.bottom_right.lat()) / 2.0; let lon = if self.crosses_dateline() { let a = 180.0 - self.top_left.lon(); let b = (-180.0 - self.bottom_right.lon()).abs(); (a + b) / 2.0 + self.top_left.lon() } else { (self.top_left.lon() + self.bottom_right.lon()) / 2.0 }; GeoCoord::from_degrees(lon, lat).unwrap() } pub fn crosses_dateline(&self) -> bool { self.top_left.lon() > self.bottom_right.lon() } fn contains_lon(&self, lon: f64) -> bool { if !self.crosses_dateline() { lon >= self.top_left.lon() && lon <= self.bottom_right.lon() } else { lon >= self.top_left.lon() || lon <= self.bottom_right.lon() } } pub fn contains_coord(&self, coord: &GeoCoord) -> bool { if coord.lat() <= self.top_left.lat() && coord.lat() >= self.bottom_right.lat() { self.contains_lon(coord.lon()) } else { false } } pub fn contains_rect(&self, rect: &GeoRect) -> bool { if !self.crosses_dateline() && rect.crosses_dateline() { if self.top_left.lon() > -180.0 || self.bottom_right.lon() < 180.0 { return false; } } self.contains_coord(&rect.top_left) && self.contains_coord(&rect.bottom_right) } pub fn intersects(&self, rect: &GeoRect) -> bool { let tl_lat = self.top_left.lat(); let br_lat = self.bottom_right.lat(); if rect.top_left.lat() < br_lat || rect.bottom_right.lat() > tl_lat { false } else if (tl_lat.abs() == 90.0 && tl_lat == rect.top_left.lat()) || (br_lat.abs() == 90.0 && br_lat == rect.bottom_right.lat()) { true } else { self.contains_lon(rect.top_left.lon()) || self.contains_lon(rect.bottom_right.lon()) } } } bitflags! { pub struct Edge: u32 { const LEFT = 0b00000001; const RIGHT = 0b00000010; const BOTTOM = 0b00000100; const TOP = 0b00001000; } } #[derive(Debug, Clone, PartialEq)] pub struct InvalidGeoRect; impl fmt::Display for InvalidGeoRect { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "invalid rectangle given") } } impl error::Error for InvalidGeoRect { fn source(&self) -> Option<&(dyn error::Error + 'static)> { None } } #[cfg(test)] mod geo_rect_tests { use super::*; fn coord(lon: f64, lat: f64) -> GeoCoord { GeoCoord::from_degrees(lon, lat).unwrap() } fn rect(tl: (f64, f64), br: (f64, f64)) -> GeoRect { GeoRect::new(coord(tl.0, tl.1), coord(br.0, br.1)).unwrap() } #[test] fn construction() { let normal_rect = GeoRect::new(coord(-10.0, 20.0), coord(10.0, -20.0)); assert!(normal_rect.is_ok()); let crossing_rect = GeoRect::new(coord(10.0, 20.0), coord(-10.0, -20.0)); assert!(crossing_rect.is_ok()); let invalid_rect = GeoRect::new(coord(-10.0, -20.0), coord(10.0, 20.0)); assert!(invalid_rect.is_err()); } #[test] fn center() { let normal_rect = rect((-10.0, 20.0), (10.0, -20.0)); assert_eq!(normal_rect.center(), coord(0.0, 0.0)); let normal_rect = rect((10.0, 20.0), (20.0, -20.0)); assert_eq!(normal_rect.center(), coord(15.0, 0.0)); let crossing_rect = rect((10.0, 20.0), (-10.0, -20.0)); assert_eq!(crossing_rect.center(), coord(180.0, 0.0)); let crossing_rect = rect((-10.0, 20.0), (-20.0, -20.0)); assert_eq!(crossing_rect.center(), coord(165.0, 0.0)); } #[test] fn crosses_dateline() { let normal_rect = rect((-10.0, 20.0), (10.0, -20.0)); assert!(!normal_rect.crosses_dateline()); let crossing_rect = rect((10.0, 20.0), (-10.0, -20.0)); assert!(crossing_rect.crosses_dateline()); } #[test] fn contains_coord() { let normal_rect = rect((-10.0, 20.0), (10.0, -20.0)); assert!(normal_rect.contains_coord(&coord(0.0, 0.0))); assert!(!normal_rect.contains_coord(&coord(-20.0, 0.0))); assert!(!normal_rect.contains_coord(&coord(0.0, 30.0))); let crossing_rect = rect((10.0, 20.0), (-10.0, -20.0)); assert!(crossing_rect.contains_coord(&coord(20.0, 0.0))); assert!(!crossing_rect.contains_coord(&coord(0.0, 0.0))); } #[test] fn contains_rect() { let normal_rect_1 = rect((-10.0, 20.0), (10.0, -20.0)); assert!(normal_rect_1.contains_rect(&normal_rect_1)); let normal_rect_2 = rect((-5.0, 20.0), (5.0, -20.0)); assert!(normal_rect_1.contains_rect(&normal_rect_2)); let normal_rect_3 = rect((10.0, 25.0), (20.0, -15.0)); assert!(!normal_rect_1.contains_rect(&normal_rect_3)); let crossing_rect_1 = rect((10.0, 20.0), (-10.0, -20.0)); assert!(!normal_rect_1.contains_rect(&crossing_rect_1)); let crossing_rect_2 = rect((20.0, 20.0), (-20.0, -20.0)); assert!(crossing_rect_1.contains_rect(&crossing_rect_2)); let normal_rect_4 = rect((-10.0, 15.0), (10.0, -15.0)); assert!(crossing_rect_1.contains_rect(&normal_rect_4)); let normal_rect_5 = rect((-180.0, 40.0), (180.0, -40.0)); assert!(normal_rect_5.contains_rect(&crossing_rect_1)); } #[test] fn intersects() { let normal_rect_1 = rect((-10.0, 20.0), (10.0, -20.0)); assert!(normal_rect_1.intersects(&normal_rect_1)); let normal_rect_2 = rect((-5.0, 20.0), (5.0, -20.0)); assert!(normal_rect_1.intersects(&normal_rect_2)); let normal_rect_3 = rect((10.0, 25.0), (20.0, -15.0)); assert!(normal_rect_1.intersects(&normal_rect_3)); let crossing_rect_1 = rect((10.0, 20.0), (-10.0, -20.0)); assert!(normal_rect_1.intersects(&crossing_rect_1)); let crossing_rect_2 = rect((5.0, 20.0), (-20.0, -20.0)); assert!(crossing_rect_1.intersects(&crossing_rect_2)); let normal_rect_4 = rect((-15.0, 15.0), (5.0, -15.0)); assert!(crossing_rect_1.intersects(&normal_rect_4)); let normal_rect_5 = rect((-175.0, 40.0), (-170.0, -40.0)); assert!(!normal_rect_5.intersects(&crossing_rect_1)); // GeoRects trivially intersect on the poles let north_pole_rect_1 = rect((-10.0, 90.0), (10.0, -20.0)); let north_pole_rect_2 = rect((20.0, 90.0), (30.0, -20.0)); assert!(north_pole_rect_1.intersects(&north_pole_rect_2)); let south_pole_rect_1 = rect((-10.0, 20.0), (10.0, -90.0)); let south_pole_rect_2 = rect((20.0, 20.0), (30.0, -90.0)); assert!(south_pole_rect_1.intersects(&south_pole_rect_2)); } }
/** * if the service is suspended and the user's organization is not the * marketplaceOwner the service is not visible to the user hence * OperationNotPermittedException is thrown * * @param service * @param marketplaceId * @throws OperationNotPermittedException */ void checkActiveOrSuspendedWithMarketplaceOwner(VOServiceEntry service, String marketplaceId) throws OperationNotPermittedException { if (service.getStatus() == ServiceStatus.ACTIVE) { return; } if (service.getStatus() == ServiceStatus.SUSPENDED) { if (!isMarketplaceOwnedByCurrentUser(marketplaceId)) { throw new OperationNotPermittedException(); } } }
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2015, Linaro Limited */ #include <linux/arm-smccc.h> #include <linux/device.h> #include <linux/err.h> #include <linux/errno.h> #include <linux/mm.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/tee_drv.h> #include <linux/types.h> #include <linux/uaccess.h> #include "optee_private.h" #include "optee_smc.h" #define CREATE_TRACE_POINTS #include "optee_trace.h" struct optee_call_waiter { struct list_head list_node; struct completion c; }; static void optee_cq_wait_init(struct optee_call_queue *cq, struct optee_call_waiter *w) { /* * We're preparing to make a call to secure world. In case we can't * allocate a thread in secure world we'll end up waiting in * optee_cq_wait_for_completion(). * * Normally if there's no contention in secure world the call will * complete and we can cleanup directly with optee_cq_wait_final(). */ mutex_lock(&cq->mutex); /* * We add ourselves to the queue, but we don't wait. This * guarantees that we don't lose a completion if secure world * returns busy and another thread just exited and try to complete * someone. */ init_completion(&w->c); list_add_tail(&w->list_node, &cq->waiters); mutex_unlock(&cq->mutex); } static void optee_cq_wait_for_completion(struct optee_call_queue *cq, struct optee_call_waiter *w) { wait_for_completion(&w->c); mutex_lock(&cq->mutex); /* Move to end of list to get out of the way for other waiters */ list_del(&w->list_node); reinit_completion(&w->c); list_add_tail(&w->list_node, &cq->waiters); mutex_unlock(&cq->mutex); } static void optee_cq_complete_one(struct optee_call_queue *cq) { struct optee_call_waiter *w; list_for_each_entry(w, &cq->waiters, list_node) { if (!completion_done(&w->c)) { complete(&w->c); break; } } } static void optee_cq_wait_final(struct optee_call_queue *cq, struct optee_call_waiter *w) { /* * We're done with the call to secure world. The thread in secure * world that was used for this call is now available for some * other task to use. */ mutex_lock(&cq->mutex); /* Get out of the list */ list_del(&w->list_node); /* Wake up one eventual waiting task */ optee_cq_complete_one(cq); /* * If we're completed we've got a completion from another task that * was just done with its call to secure world. Since yet another * thread now is available in secure world wake up another eventual * waiting task. */ if (completion_done(&w->c)) optee_cq_complete_one(cq); mutex_unlock(&cq->mutex); } /* Requires the filpstate mutex to be held */ static struct optee_session *find_session(struct optee_context_data *ctxdata, u32 session_id) { struct optee_session *sess; list_for_each_entry(sess, &ctxdata->sess_list, list_node) if (sess->session_id == session_id) return sess; return NULL; } /** * optee_do_call_with_arg() - Do an SMC to OP-TEE in secure world * @ctx: calling context * @parg: physical address of message to pass to secure world * * Does and SMC to OP-TEE in secure world and handles eventual resulting * Remote Procedure Calls (RPC) from OP-TEE. * * Returns return code from secure world, 0 is OK */ u32 optee_do_call_with_arg(struct tee_context *ctx, phys_addr_t parg) { struct optee *optee = tee_get_drvdata(ctx->teedev); struct optee_call_waiter w; struct optee_rpc_param param = { }; struct optee_call_ctx call_ctx = { }; u32 ret; param.a0 = OPTEE_SMC_CALL_WITH_ARG; reg_pair_from_64(&param.a1, &param.a2, parg); /* Initialize waiter */ optee_cq_wait_init(&optee->call_queue, &w); while (true) { struct arm_smccc_res res; trace_optee_invoke_fn_begin(&param); optee->invoke_fn(param.a0, param.a1, param.a2, param.a3, param.a4, param.a5, param.a6, param.a7, &res); trace_optee_invoke_fn_end(&param, &res); if (res.a0 == OPTEE_SMC_RETURN_ETHREAD_LIMIT) { /* * Out of threads in secure world, wait for a thread * become available. */ optee_cq_wait_for_completion(&optee->call_queue, &w); } else if (OPTEE_SMC_RETURN_IS_RPC(res.a0)) { cond_resched(); param.a0 = res.a0; param.a1 = res.a1; param.a2 = res.a2; param.a3 = res.a3; optee_handle_rpc(ctx, &param, &call_ctx); } else { ret = res.a0; break; } } optee_rpc_finalize_call(&call_ctx); /* * We're done with our thread in secure world, if there's any * thread waiters wake up one. */ optee_cq_wait_final(&optee->call_queue, &w); return ret; } static struct tee_shm *get_msg_arg(struct tee_context *ctx, size_t num_params, struct optee_msg_arg **msg_arg, phys_addr_t *msg_parg) { int rc; struct tee_shm *shm; struct optee_msg_arg *ma; shm = tee_shm_alloc(ctx, OPTEE_MSG_GET_ARG_SIZE(num_params), TEE_SHM_MAPPED); if (IS_ERR(shm)) return shm; ma = tee_shm_get_va(shm, 0); if (IS_ERR(ma)) { rc = PTR_ERR(ma); goto out; } rc = tee_shm_get_pa(shm, 0, msg_parg); if (rc) goto out; memset(ma, 0, OPTEE_MSG_GET_ARG_SIZE(num_params)); ma->num_params = num_params; *msg_arg = ma; out: if (rc) { tee_shm_free(shm); return ERR_PTR(rc); } return shm; } int optee_open_session(struct tee_context *ctx, struct tee_ioctl_open_session_arg *arg, struct tee_param *param) { struct optee_context_data *ctxdata = ctx->data; int rc; struct tee_shm *shm; struct optee_msg_arg *msg_arg; phys_addr_t msg_parg; struct optee_session *sess = NULL; uuid_t client_uuid; /* +2 for the meta parameters added below */ shm = get_msg_arg(ctx, arg->num_params + 2, &msg_arg, &msg_parg); if (IS_ERR(shm)) return PTR_ERR(shm); msg_arg->cmd = OPTEE_MSG_CMD_OPEN_SESSION; msg_arg->cancel_id = arg->cancel_id; /* * Initialize and add the meta parameters needed when opening a * session. */ msg_arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT | OPTEE_MSG_ATTR_META; msg_arg->params[1].attr = OPTEE_MSG_ATTR_TYPE_VALUE_INPUT | OPTEE_MSG_ATTR_META; memcpy(&msg_arg->params[0].u.value, arg->uuid, sizeof(arg->uuid)); msg_arg->params[1].u.value.c = arg->clnt_login; rc = tee_session_calc_client_uuid(&client_uuid, arg->clnt_login, arg->clnt_uuid); if (rc) goto out; export_uuid(msg_arg->params[1].u.octets, &client_uuid); rc = optee_to_msg_param(msg_arg->params + 2, arg->num_params, param); if (rc) goto out; sess = kzalloc(sizeof(*sess), GFP_KERNEL); if (!sess) { rc = -ENOMEM; goto out; } if (optee_do_call_with_arg(ctx, msg_parg)) { msg_arg->ret = TEEC_ERROR_COMMUNICATION; msg_arg->ret_origin = TEEC_ORIGIN_COMMS; } if (msg_arg->ret == TEEC_SUCCESS) { /* A new session has been created, add it to the list. */ sess->session_id = msg_arg->session; mutex_lock(&ctxdata->mutex); list_add(&sess->list_node, &ctxdata->sess_list); mutex_unlock(&ctxdata->mutex); } else { kfree(sess); } if (optee_from_msg_param(param, arg->num_params, msg_arg->params + 2)) { arg->ret = TEEC_ERROR_COMMUNICATION; arg->ret_origin = TEEC_ORIGIN_COMMS; /* Close session again to avoid leakage */ optee_close_session(ctx, msg_arg->session); } else { arg->session = msg_arg->session; arg->ret = msg_arg->ret; arg->ret_origin = msg_arg->ret_origin; } out: tee_shm_free(shm); return rc; } int optee_close_session(struct tee_context *ctx, u32 session) { struct optee_context_data *ctxdata = ctx->data; struct tee_shm *shm; struct optee_msg_arg *msg_arg; phys_addr_t msg_parg; struct optee_session *sess; /* Check that the session is valid and remove it from the list */ mutex_lock(&ctxdata->mutex); sess = find_session(ctxdata, session); if (sess) list_del(&sess->list_node); mutex_unlock(&ctxdata->mutex); if (!sess) return -EINVAL; kfree(sess); shm = get_msg_arg(ctx, 0, &msg_arg, &msg_parg); if (IS_ERR(shm)) return PTR_ERR(shm); msg_arg->cmd = OPTEE_MSG_CMD_CLOSE_SESSION; msg_arg->session = session; optee_do_call_with_arg(ctx, msg_parg); tee_shm_free(shm); return 0; } int optee_invoke_func(struct tee_context *ctx, struct tee_ioctl_invoke_arg *arg, struct tee_param *param) { struct optee_context_data *ctxdata = ctx->data; struct tee_shm *shm; struct optee_msg_arg *msg_arg; phys_addr_t msg_parg; struct optee_session *sess; int rc; /* Check that the session is valid */ mutex_lock(&ctxdata->mutex); sess = find_session(ctxdata, arg->session); mutex_unlock(&ctxdata->mutex); if (!sess) return -EINVAL; shm = get_msg_arg(ctx, arg->num_params, &msg_arg, &msg_parg); if (IS_ERR(shm)) return PTR_ERR(shm); msg_arg->cmd = OPTEE_MSG_CMD_INVOKE_COMMAND; msg_arg->func = arg->func; msg_arg->session = arg->session; msg_arg->cancel_id = arg->cancel_id; rc = optee_to_msg_param(msg_arg->params, arg->num_params, param); if (rc) goto out; if (optee_do_call_with_arg(ctx, msg_parg)) { msg_arg->ret = TEEC_ERROR_COMMUNICATION; msg_arg->ret_origin = TEEC_ORIGIN_COMMS; } if (optee_from_msg_param(param, arg->num_params, msg_arg->params)) { msg_arg->ret = TEEC_ERROR_COMMUNICATION; msg_arg->ret_origin = TEEC_ORIGIN_COMMS; } arg->ret = msg_arg->ret; arg->ret_origin = msg_arg->ret_origin; out: tee_shm_free(shm); return rc; } int optee_cancel_req(struct tee_context *ctx, u32 cancel_id, u32 session) { struct optee_context_data *ctxdata = ctx->data; struct tee_shm *shm; struct optee_msg_arg *msg_arg; phys_addr_t msg_parg; struct optee_session *sess; /* Check that the session is valid */ mutex_lock(&ctxdata->mutex); sess = find_session(ctxdata, session); mutex_unlock(&ctxdata->mutex); if (!sess) return -EINVAL; shm = get_msg_arg(ctx, 0, &msg_arg, &msg_parg); if (IS_ERR(shm)) return PTR_ERR(shm); msg_arg->cmd = OPTEE_MSG_CMD_CANCEL; msg_arg->session = session; msg_arg->cancel_id = cancel_id; optee_do_call_with_arg(ctx, msg_parg); tee_shm_free(shm); return 0; } /** * optee_enable_shm_cache() - Enables caching of some shared memory allocation * in OP-TEE * @optee: main service struct */ void optee_enable_shm_cache(struct optee *optee) { struct optee_call_waiter w; /* We need to retry until secure world isn't busy. */ optee_cq_wait_init(&optee->call_queue, &w); while (true) { struct arm_smccc_res res; optee->invoke_fn(OPTEE_SMC_ENABLE_SHM_CACHE, 0, 0, 0, 0, 0, 0, 0, &res); if (res.a0 == OPTEE_SMC_RETURN_OK) break; optee_cq_wait_for_completion(&optee->call_queue, &w); } optee_cq_wait_final(&optee->call_queue, &w); } /** * optee_disable_shm_cache() - Disables caching of some shared memory allocation * in OP-TEE * @optee: main service struct */ void optee_disable_shm_cache(struct optee *optee) { struct optee_call_waiter w; /* We need to retry until secure world isn't busy. */ optee_cq_wait_init(&optee->call_queue, &w); while (true) { union { struct arm_smccc_res smccc; struct optee_smc_disable_shm_cache_result result; } res; optee->invoke_fn(OPTEE_SMC_DISABLE_SHM_CACHE, 0, 0, 0, 0, 0, 0, 0, &res.smccc); if (res.result.status == OPTEE_SMC_RETURN_ENOTAVAIL) break; /* All shm's freed */ if (res.result.status == OPTEE_SMC_RETURN_OK) { struct tee_shm *shm; shm = reg_pair_to_ptr(res.result.shm_upper32, res.result.shm_lower32); tee_shm_free(shm); } else { optee_cq_wait_for_completion(&optee->call_queue, &w); } } optee_cq_wait_final(&optee->call_queue, &w); } #define PAGELIST_ENTRIES_PER_PAGE \ ((OPTEE_MSG_NONCONTIG_PAGE_SIZE / sizeof(u64)) - 1) /** * optee_fill_pages_list() - write list of user pages to given shared * buffer. * * @dst: page-aligned buffer where list of pages will be stored * @pages: array of pages that represents shared buffer * @num_pages: number of entries in @pages * @page_offset: offset of user buffer from page start * * @dst should be big enough to hold list of user page addresses and * links to the next pages of buffer */ void optee_fill_pages_list(u64 *dst, struct page **pages, int num_pages, size_t page_offset) { int n = 0; phys_addr_t optee_page; /* * Refer to OPTEE_MSG_ATTR_NONCONTIG description in optee_msg.h * for details. */ struct { u64 pages_list[PAGELIST_ENTRIES_PER_PAGE]; u64 next_page_data; } *pages_data; /* * Currently OP-TEE uses 4k page size and it does not looks * like this will change in the future. On other hand, there are * no know ARM architectures with page size < 4k. * Thus the next built assert looks redundant. But the following * code heavily relies on this assumption, so it is better be * safe than sorry. */ BUILD_BUG_ON(PAGE_SIZE < OPTEE_MSG_NONCONTIG_PAGE_SIZE); pages_data = (void *)dst; /* * If linux page is bigger than 4k, and user buffer offset is * larger than 4k/8k/12k/etc this will skip first 4k pages, * because they bear no value data for OP-TEE. */ optee_page = page_to_phys(*pages) + round_down(page_offset, OPTEE_MSG_NONCONTIG_PAGE_SIZE); while (true) { pages_data->pages_list[n++] = optee_page; if (n == PAGELIST_ENTRIES_PER_PAGE) { pages_data->next_page_data = virt_to_phys(pages_data + 1); pages_data++; n = 0; } optee_page += OPTEE_MSG_NONCONTIG_PAGE_SIZE; if (!(optee_page & ~PAGE_MASK)) { if (!--num_pages) break; pages++; optee_page = page_to_phys(*pages); } } } /* * The final entry in each pagelist page is a pointer to the next * pagelist page. */ static size_t get_pages_list_size(size_t num_entries) { int pages = DIV_ROUND_UP(num_entries, PAGELIST_ENTRIES_PER_PAGE); return pages * OPTEE_MSG_NONCONTIG_PAGE_SIZE; } u64 *optee_allocate_pages_list(size_t num_entries) { return alloc_pages_exact(get_pages_list_size(num_entries), GFP_KERNEL); } void optee_free_pages_list(void *list, size_t num_entries) { free_pages_exact(list, get_pages_list_size(num_entries)); } static bool is_normal_memory(pgprot_t p) { #if defined(CONFIG_ARM) return (((pgprot_val(p) & L_PTE_MT_MASK) == L_PTE_MT_WRITEALLOC) || ((pgprot_val(p) & L_PTE_MT_MASK) == L_PTE_MT_WRITEBACK)); #elif defined(CONFIG_ARM64) return (pgprot_val(p) & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL); #else #error "Unuspported architecture" #endif } static int __check_mem_type(struct vm_area_struct *vma, unsigned long end) { while (vma && is_normal_memory(vma->vm_page_prot)) { if (vma->vm_end >= end) return 0; vma = vma->vm_next; } return -EINVAL; } static int check_mem_type(unsigned long start, size_t num_pages) { struct mm_struct *mm = current->mm; int rc; /* * Allow kernel address to register with OP-TEE as kernel * pages are configured as normal memory only. */ if (virt_addr_valid(start)) return 0; mmap_read_lock(mm); rc = __check_mem_type(find_vma(mm, start), start + num_pages * PAGE_SIZE); mmap_read_unlock(mm); return rc; } int optee_shm_register(struct tee_context *ctx, struct tee_shm *shm, struct page **pages, size_t num_pages, unsigned long start) { struct tee_shm *shm_arg = NULL; struct optee_msg_arg *msg_arg; u64 *pages_list; phys_addr_t msg_parg; int rc; if (!num_pages) return -EINVAL; rc = check_mem_type(start, num_pages); if (rc) return rc; pages_list = optee_allocate_pages_list(num_pages); if (!pages_list) return -ENOMEM; shm_arg = get_msg_arg(ctx, 1, &msg_arg, &msg_parg); if (IS_ERR(shm_arg)) { rc = PTR_ERR(shm_arg); goto out; } optee_fill_pages_list(pages_list, pages, num_pages, tee_shm_get_page_offset(shm)); msg_arg->cmd = OPTEE_MSG_CMD_REGISTER_SHM; msg_arg->params->attr = OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT | OPTEE_MSG_ATTR_NONCONTIG; msg_arg->params->u.tmem.shm_ref = (unsigned long)shm; msg_arg->params->u.tmem.size = tee_shm_get_size(shm); /* * In the least bits of msg_arg->params->u.tmem.buf_ptr we * store buffer offset from 4k page, as described in OP-TEE ABI. */ msg_arg->params->u.tmem.buf_ptr = virt_to_phys(pages_list) | (tee_shm_get_page_offset(shm) & (OPTEE_MSG_NONCONTIG_PAGE_SIZE - 1)); if (optee_do_call_with_arg(ctx, msg_parg) || msg_arg->ret != TEEC_SUCCESS) rc = -EINVAL; tee_shm_free(shm_arg); out: optee_free_pages_list(pages_list, num_pages); return rc; } int optee_shm_unregister(struct tee_context *ctx, struct tee_shm *shm) { struct tee_shm *shm_arg; struct optee_msg_arg *msg_arg; phys_addr_t msg_parg; int rc = 0; shm_arg = get_msg_arg(ctx, 1, &msg_arg, &msg_parg); if (IS_ERR(shm_arg)) return PTR_ERR(shm_arg); msg_arg->cmd = OPTEE_MSG_CMD_UNREGISTER_SHM; msg_arg->params[0].attr = OPTEE_MSG_ATTR_TYPE_RMEM_INPUT; msg_arg->params[0].u.rmem.shm_ref = (unsigned long)shm; if (optee_do_call_with_arg(ctx, msg_parg) || msg_arg->ret != TEEC_SUCCESS) rc = -EINVAL; tee_shm_free(shm_arg); return rc; } int optee_shm_register_supp(struct tee_context *ctx, struct tee_shm *shm, struct page **pages, size_t num_pages, unsigned long start) { /* * We don't want to register supplicant memory in OP-TEE. * Instead information about it will be passed in RPC code. */ return check_mem_type(start, num_pages); } int optee_shm_unregister_supp(struct tee_context *ctx, struct tee_shm *shm) { return 0; }
// Get the priority for a particular device type. The priority returned // will be between 0 to 3, the higher number meaning a higher priority. uint8 GetDevicePriority(chromeos::AudioDeviceType type) { switch (type) { case chromeos::AUDIO_TYPE_HEADPHONE: case chromeos::AUDIO_TYPE_MIC: case chromeos::AUDIO_TYPE_USB: case chromeos::AUDIO_TYPE_BLUETOOTH: return 3; case chromeos::AUDIO_TYPE_HDMI: return 2; case chromeos::AUDIO_TYPE_INTERNAL_SPEAKER: case chromeos::AUDIO_TYPE_INTERNAL_MIC: return 1; case chromeos::AUDIO_TYPE_OTHER: default: return 0; } }
""" Functions for DB initialization """ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from app import app from app.data.data_model import BASE from app.data.data_access_layer import init_db def get_db_engine(db_uri): """ Creates and returns a db engine """ db_engine = create_engine(db_uri, echo=False) return db_engine def initialize_db(): """ Initializes the database """ db_path = app.config['SQLALCHEMY_DATABASE_PATH'] db_uri = "sqlite:///" + db_path db_engine = get_db_engine(db_uri) init_db(db_engine, db_path, BASE) def get_db_session(): """ Returns a DB session """ db_path = app.config['SQLALCHEMY_DATABASE_PATH'] db_uri = "sqlite:///" + db_path db_engine = get_db_engine(db_uri) db_session = scoped_session( sessionmaker(autocommit=False, autoflush=False, bind=db_engine)) return db_session()
#include<stdio.h> int main() { long long x; int n; scanf("%I64d",&x); for(n=0;x>0;n+=(x%2==1)?1:0,x/=2) ; printf("%d",n); }
<reponame>anthill-docker/anthill<filename>internal/pkg/context/context.go // Package context is a solution for gathering all required data of the application. package context import ( "os" "runtime" "strings" "unicode" "unicode/utf8" "github.com/aenthill/aenthill/internal/pkg/errors" ) const ( // IDEnvVar is the name of the environment variable which contains the current aent ID from the manifest if the aent is a registred instance. IDEnvVar = "PHEROMONE_ID" // ImageEnvVar is the name of the environment variable which contains the current aent image name. ImageEnvVar = "PHEROMONE_IMAGE_NAME" // FromContainerIDEnvVar is the name of the environment variable which contains the sender container ID which has started the recipient image. FromContainerIDEnvVar = "PHEROMONE_FROM_CONTAINER_ID" // HostnameEnvVar is the name of the environment variable which contains the recipient container id. It is populated by Docker. HostnameEnvVar = "HOSTNAME" // HostProjectDirEnvVar is the name of the environment variable which contains the host project directory path. HostProjectDirEnvVar = "PHEROMONE_HOST_PROJECT_DIR" // ContainerProjectDirEnvVar is the name of the environment variable which contains the mounted path of the host project directory. ContainerProjectDirEnvVar = "PHEROMONE_CONTAINER_PROJECT_DIR" // LogLevelEnvVar is the name of the environment variable which contains the log level. LogLevelEnvVar = "PHEROMONE_LOG_LEVEL" ) // Context is our working struct. type Context struct { Image string ID string FromContainerID string Hostname string HostProjectDir string ProjectDir string LogLevel string isContainer bool } // New creates a Context instance according to where is launched the application // (form a container or from the host). func New() (*Context, error) { v, err := lookupEnv(ImageEnvVar) if err != nil { return makeFromHost() } return makeFromEnv(v) } // IsContainer returns true if the application is launched from a container, false otherwise. func (ctx *Context) IsContainer() bool { return ctx.isContainer } func makeFromHost() (*Context, error) { ctx := &Context{} ctx.isContainer = false ctx.LogLevel = "ERROR" projectDir, err := os.Getwd() if err != nil { return nil, errors.Wrap("context", err) } if runtime.GOOS == "windows" { // replacing paths like "C:/foo" to "//c/foo". replacer := strings.NewReplacer("\\", "/", ":", "") projectDir = replacer.Replace(projectDir) r, n := utf8.DecodeRuneInString(projectDir) projectDir = string(unicode.ToLower(r)) + projectDir[n:] } ctx.HostProjectDir, ctx.ProjectDir = projectDir, "/aenthill" return ctx, nil } func makeFromEnv(image string) (*Context, error) { var ( ctx = &Context{isContainer: true, Image: image} v string err error ) v, err = lookupEnv(IDEnvVar) if err != nil { return nil, err } ctx.ID = v v, err = lookupEnv(FromContainerIDEnvVar) if err != nil { return nil, err } ctx.FromContainerID = v v, err = lookupEnv(HostnameEnvVar) if err != nil { return nil, err } ctx.Hostname = v v, err = lookupEnv(HostProjectDirEnvVar) if err != nil { return nil, err } ctx.HostProjectDir = v v, err = lookupEnv(ContainerProjectDirEnvVar) if err != nil { return nil, err } ctx.ProjectDir = v v, err = lookupEnv(LogLevelEnvVar) if err != nil { return nil, err } ctx.LogLevel = v return ctx, nil } func lookupEnv(key string) (string, error) { v, ok := os.LookupEnv(key) if !ok { return "", errors.Errorf("context", `env key "%s" does not exist`, key) } if key != FromContainerIDEnvVar && key != IDEnvVar && v == "" { return "", errors.Errorf("context", `env key "%s" has an empty value`, key) } return v, nil }
import sys sys.setrecursionlimit(10**6) initial = "What are you doing at the end of the world? Are you busy? Will you save us?" f = 'What are you doing while sending "' s = '"? Are you busy? Will you send "' t = '"?' flen = len(f) slen = len(s) tlen = len(t) l = [] l.append(len(initial)) tmp = len(initial) add = len(f + s + t) for i in range(55): now = tmp * 2 + add tmp = now l.append(now) for i in range(10**5): l.append(float('inf')) def decide(n, k): while(True): if(k >= l[n]):return "." if(n == 0):return initial[k] if(k <= flen - 1):return f[k] k -= flen if(k <= l[n - 1] - 1): n -= 1 continue k -= l[n - 1] if(k <= slen - 1):return s[k] k -= slen if(k <= l[n - 1] - 1): n -= 1 continue k -= l[n - 1] return t[k] for i in range(int(input())): n, k = map(int, input().split()) k -= 1 print(decide(n,k),end='')
Access to Justice The author explores how Aboriginality, racialization, gender, disability, class, and sexual identity may affect one's ability to obtain justice in the Canadian legal system. The Canadian justice system has historically given disproportionate access to white, non-immigrant, able-bodied, affluent men while marginalizing others. Today, Canadians would prefer to forget our history of discriminatory laws and practices, impeding compensation and change that would benefit marginalized groups. As a result, historically marginalized groups have less access to knowledge and power in our justice system, and continue to be underrepresented in politics, in the legal profession, and in the judiciary. The article suggests mechanisms to make our legal system more representative of Canada's population.
<filename>ac.go package main type ac struct { Group string State bool Mode string Speed string Direction string TargetTemp float64 TargetTemp1 float64 TargetTemp2 float64 CurrentTemp float64 UseTemp bool }
Apple has been catching a lot of flack for their draconian app approval process, and for the most part, it's a well-deserved takedown. On our grass is greener side, Google has been looking pretty nice throughout the whole he-said, she-said battle between the FCC, Google, Apple, and AT&T and it's looking even better now that details about how Google deals with Android apps in Android Market have been revealed. To date, Android Market has only banned 1% of the applications from its virtual shelves and none of those banned applications have their blood on Google's hands. Namely, the banning process begins with users flagging specific applications and then Google investigating the applications--there is no pre-approval process for developers to jump through. We, the Android users, decide what gets cut. The most common reasons for removal are apps that contain adult content or violate copyright laws. Though not having a pre-approval process can lead to a lot of shoddy and useless applications being passed through, we'd much rather have it the Android way than Apple's. Plus, Apple still has just as many fart apps as we do. [via moconews]
import * as path from "path" import { Cluster } from "@solana/web3.js" // CORS const allowedOriginsRaw: string | undefined = process.env.GRUNTHOS_CORS_ALLOWED_ORIGINS if (!allowedOriginsRaw) { throw new Error( "GRUNTHOS_CORS_ALLOWED_ORIGINS environment variable must be set" ) } export const allowedOrigins: string[] = allowedOriginsRaw.split(",") export const BUGOUT_REPORTER_TOKEN = process.env.BUGOUT_REPORTER_TOKEN export const GRUNTHOS_SERVER_ID = process.env.GRUNTHOS_SERVER_ID export const GRUNTHOS_PORT = process.env.GRUNTHOS_PORT || 5904 export const GRUNTHOS_LOG_LEVEL = ( process.env.GRUNTHOS_LOG_LEVEL || "info" ).toLowerCase() export const BUGOUT_POEMS_JOURNAL_ID: string | undefined = process.env.BUGOUT_POEMS_JOURNAL_ID if (!BUGOUT_POEMS_JOURNAL_ID) { throw new Error("BUGOUT_POEMS_JOURNAL_ID environment variable must be set") } export const BUGOUT_RESOURCE_APPLICATION_ID = process.env.BUGOUT_RESOURCE_APPLICATION_ID if (!BUGOUT_RESOURCE_APPLICATION_ID) { throw new Error( "BUGOUT_RESOURCE_APPLICATION_ID environment variable must be set" ) } // Solana export const SolanaConfigPath: string | undefined = process.env.SOLANA_CONFIG_PATH if (!SolanaConfigPath) { throw new Error("SOLANA_CONFIG_PATH environment variable must be set") } const mainKeypair = "id.json" export const mainKeypairPath = path.resolve(SolanaConfigPath, mainKeypair) function chooseSolanaCluster(): Cluster | undefined { switch (process.env.SOLANA_CLUSTER) { case "devnet": case "testnet": case "mainnet-beta": { return process.env.SOLANA_CLUSTER } } return "devnet" } export const solanaCluster = chooseSolanaCluster()
Greetings Explorers, We always knew we had an amazing community beating at the heart of Worlds Adrift since the very start, but never imagined how amazing your response and support would be as we entered the Closed Beta phase. Our first batch of Founder’s Pack have sold out! Due to overwhelming demand, our first batch went much (MUCH) quicker than we planned for. Not only that, but those who bought the packs also started to play three times as long and as often than during the Alpha tests, showing the huge love for the game. All this success also meant some issues with the game experience, which the very strategy for restricting the number of packs available at sale was supposed to avoid. A solution is now underway, we’re working diligently to prevent this from happening again by significantly increasing our server capacity to tackle it. As always, we really value your opinions, feedback, and reviews (the good, the bad and the ugly – it all helps and is welcome) as together we continue to shape the future of the game for everyone. We understand many of you want to join in this adventure now, and we apologise for any inconvenience, but we won’t keep you waiting long before we release the next batch! To be the first to know when the next batch is available, please follow us on Twitter, Facebook, our Forums and the Steam Community Hub. See you in the skies, The Worlds Adrift team. XOXO
/* * Copyright 2002-2021 the original author or authors. * * 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 * * https://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. */ package org.springframework.security.web.authentication.logout; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * A logout handler which clears either - A defined list of cookie names, using the * context path as the cookie path OR - A given list of Cookies * * @author Luke Taylor * @author Onur Kagan Ozcan * @since 3.1 */ public final class CookieClearingLogoutHandler implements LogoutHandler { private final List<Function<HttpServletRequest, Cookie>> cookiesToClear; public CookieClearingLogoutHandler(String... cookiesToClear) { Assert.notNull(cookiesToClear, "List of cookies cannot be null"); List<Function<HttpServletRequest, Cookie>> cookieList = new ArrayList<>(); for (String cookieName : cookiesToClear) { cookieList.add((request) -> { Cookie cookie = new Cookie(cookieName, null); String contextPath = request.getContextPath(); String cookiePath = StringUtils.hasText(contextPath) ? contextPath : "/"; cookie.setPath(cookiePath); cookie.setMaxAge(0); cookie.setSecure(request.isSecure()); return cookie; }); } this.cookiesToClear = cookieList; } /** * @param cookiesToClear - One or more Cookie objects that must have maxAge of 0 * @since 5.2 */ public CookieClearingLogoutHandler(Cookie... cookiesToClear) { Assert.notNull(cookiesToClear, "List of cookies cannot be null"); List<Function<HttpServletRequest, Cookie>> cookieList = new ArrayList<>(); for (Cookie cookie : cookiesToClear) { Assert.isTrue(cookie.getMaxAge() == 0, "Cookie maxAge must be 0"); cookieList.add((request) -> cookie); } this.cookiesToClear = cookieList; } @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { this.cookiesToClear.forEach((f) -> response.addCookie(f.apply(request))); } }
/*------------------------------------------------------------------------------ * Copyright (C) 2003-2006 <NAME> and the CLucene Team * * Distributable under the terms of either the Apache License (Version 2.0) or * the GNU Lesser General Public License, as specified in the COPYING file. ------------------------------------------------------------------------------*/ #include "CLucene/_ApiHeader.h" #include "BooleanQuery.h" #include "BooleanClause.h" #include "CLucene/index/IndexReader.h" #include "CLucene/util/StringBuffer.h" #include "CLucene/util/_Arrays.h" #include "SearchHeader.h" #include "_BooleanScorer.h" #include "_ConjunctionScorer.h" #include "Similarity.h" #include "Explanation.h" #include "_BooleanScorer2.h" #include "Scorer.h" #include <assert.h> CL_NS_USE(index) CL_NS_USE(util) CL_NS_DEF(search) class BooleanClause_Compare:public CL_NS_STD(binary_function)<const BooleanClause*,const BooleanClause*,bool> { public: bool operator()( const BooleanClause* val1, const BooleanClause* val2 ) const { return val1->equals(val2); } }; class BooleanWeight: public Weight { protected: Searcher* searcher; Similarity* similarity; CL_NS(util)::CLVector<Weight*,CL_NS(util)::Deletor::Object<Weight> > weights; BooleanQuery::ClausesType* clauses; BooleanQuery* parentQuery; public: BooleanWeight(Searcher* searcher, CL_NS(util)::CLVector<BooleanClause*,CL_NS(util)::Deletor::Object<BooleanClause> >* clauses, BooleanQuery* parentQuery); virtual ~BooleanWeight(); Query* getQuery(); float_t getValue(); float_t sumOfSquaredWeights(); void normalize(float_t norm); Scorer* scorer(CL_NS(index)::IndexReader* reader); Explanation* explain(CL_NS(index)::IndexReader* reader, int32_t doc); };// BooleanWeight BooleanQuery::BooleanQuery( bool disableCoord ): clauses(_CLNEW BooleanQuery::ClausesType(true)) { this->minNrShouldMatch = 0; this->disableCoord = disableCoord; } Weight* BooleanQuery::_createWeight(Searcher* searcher) { return _CLNEW BooleanWeight(searcher, clauses,this); } BooleanQuery::BooleanQuery(const BooleanQuery& clone): Query(clone), clauses(_CLNEW ClausesType(true)), disableCoord(clone.disableCoord) { minNrShouldMatch = clone.minNrShouldMatch; for ( uint32_t i=0;i<clone.clauses->size();i++ ){ BooleanClause* clause = (*clone.clauses)[i]->clone(); clause->deleteQuery=true; add(clause); } } BooleanQuery::~BooleanQuery(){ clauses->clear(); _CLDELETE(clauses); } size_t BooleanQuery::hashCode() const { //todo: do cachedHashCode, and invalidate on add/remove clause size_t ret = 0; for (uint32_t i = 0 ; i < clauses->size(); i++) { BooleanClause* c = (*clauses)[i]; ret = 31 * ret + c->hashCode(); } ret = ret ^ Similarity::floatToByte(getBoost()); return ret; } const char* BooleanQuery::getObjectName() const{ return getClassName(); } const char* BooleanQuery::getClassName(){ return "BooleanQuery"; } /** * Default value is 1024. Use <code>org.apache.lucene.maxClauseCount</code> * system property to override. */ size_t BooleanQuery::maxClauseCount = LUCENE_BOOLEANQUERY_MAXCLAUSECOUNT; size_t BooleanQuery::getMaxClauseCount(){ return maxClauseCount; } void BooleanQuery::setMaxClauseCount(const size_t maxClauseCount){ if (maxClauseCount < 1) _CLTHROWA(CL_ERR_IllegalArgument, "maxClauseCount must be >= 1"); BooleanQuery::maxClauseCount = maxClauseCount; } Similarity* BooleanQuery::getSimilarity( Searcher* searcher ) { Similarity* result = Query::getSimilarity( searcher ); return result; } void BooleanQuery::add(Query* query, const bool deleteQuery, const bool required, const bool prohibited) { BooleanClause* bc = _CLNEW BooleanClause(query,deleteQuery,required, prohibited); try{ add(bc); }catch(...){ _CLDELETE(bc); throw; } } void BooleanQuery::add(Query* query, const bool deleteQuery, BooleanClause::Occur occur) { BooleanClause* bc = _CLNEW BooleanClause(query,deleteQuery,occur); try{ add(bc); }catch(...){ _CLDELETE(bc); throw; } } void BooleanQuery::add(BooleanClause* clause) { if (clauses->size() >= getMaxClauseCount()) _CLTHROWA(CL_ERR_TooManyClauses,"Too Many Clauses"); clauses->push_back(clause); } int32_t BooleanQuery::getMinNrShouldMatch(){ return minNrShouldMatch; } bool BooleanQuery::getUseScorer14() { return getAllowDocsOutOfOrder(); } bool BooleanQuery::allowDocsOutOfOrder = false; void BooleanQuery::setUseScorer14( bool use14 ) { setAllowDocsOutOfOrder(use14); } void BooleanQuery::setAllowDocsOutOfOrder(bool allow) { allowDocsOutOfOrder = allow; } bool BooleanQuery::getAllowDocsOutOfOrder() { return allowDocsOutOfOrder; } size_t BooleanQuery::getClauseCount() const { return (int32_t) clauses->size(); } TCHAR* BooleanQuery::toString(const TCHAR* field) const{ StringBuffer buffer; bool needParens=(getBoost() != 1.0) /* TODO: || (getMinimumNumberShouldMatch()>0)*/ ; if (needParens) { buffer.append(_T("(")); } for (uint32_t i = 0 ; i < clauses->size(); i++) { BooleanClause* c = (*clauses)[i]; if (c->prohibited) buffer.append(_T("-")); else if (c->required) buffer.append(_T("+")); if ( c->getQuery()->instanceOf(BooleanQuery::getClassName()) ) { // wrap sub-bools in parens buffer.append(_T("(")); TCHAR* buf = c->getQuery()->toString(field); buffer.append(buf); _CLDELETE_CARRAY( buf ); buffer.append(_T(")")); } else { TCHAR* buf = c->getQuery()->toString(field); buffer.append(buf); _CLDELETE_CARRAY( buf ); } if (i != clauses->size()-1) buffer.append(_T(" ")); } if (needParens) { buffer.append(_T(")")); } if (getBoost() != 1.0) { buffer.appendChar(_T('^')); buffer.appendFloat(getBoost(),1); } return buffer.toString(); } bool BooleanQuery::isCoordDisabled() { return disableCoord; } void BooleanQuery::setCoordDisabled( bool disableCoord ) { this->disableCoord = disableCoord; } BooleanClause** BooleanQuery::getClauses() const { CND_MESSAGE(false, "Warning: BooleanQuery::getClauses() is deprecated") BooleanClause** ret = _CL_NEWARRAY(BooleanClause*, clauses->size()+1); getClauses(ret); return ret; } void BooleanQuery::getClauses(BooleanClause** ret) const { size_t size=clauses->size(); for ( uint32_t i=0;i<size;i++ ) ret[i] = (*clauses)[i]; } Query* BooleanQuery::rewrite(IndexReader* reader) { if (clauses->size() == 1) { // optimize 1-clause queries BooleanClause* c = (*clauses)[0]; if (!c->prohibited) { // just return clause Query* query = c->getQuery()->rewrite(reader); // rewrite first //if the query doesn't actually get re-written, //then return a clone (because the BooleanQuery //will register different to the returned query. if ( query == c->getQuery() ) query = query->clone(); if (getBoost() != 1.0f) { // incorporate boost query->setBoost(getBoost() * query->getBoost()); } return query; } } BooleanQuery* clone = NULL; // recursively rewrite for (uint32_t i = 0 ; i < clauses->size(); i++) { BooleanClause* c = (*clauses)[i]; Query* query = c->getQuery()->rewrite(reader); if (query != c->getQuery()) { // clause rewrote: must clone if (clone == NULL) clone = (BooleanQuery*)this->clone(); clone->clauses->set (i, _CLNEW BooleanClause(query, true, c->getOccur())); } } if (clone != NULL) { return clone; // some clauses rewrote } else return this; // no clauses rewrote } void BooleanQuery::extractTerms( TermSet * termset ) const { for (size_t i = 0 ; i < clauses->size(); i++) { BooleanClause* clause = (*clauses)[i]; clause->getQuery()->extractTerms( termset ); } } Query* BooleanQuery::clone() const{ BooleanQuery* clone = _CLNEW BooleanQuery(*this); return clone; } /** Returns true iff <code>o</code> is equal to this. */ bool BooleanQuery::equals(Query* o)const { if (!(o->instanceOf(BooleanQuery::getClassName()))) return false; const BooleanQuery* other = (BooleanQuery*)o; bool ret = (this->getBoost() == other->getBoost()); if ( ret ){ CLListEquals<BooleanClause,BooleanClause_Compare, const BooleanQuery::ClausesType, const BooleanQuery::ClausesType> comp; ret = comp.equals(this->clauses,other->clauses); } return ret; } float_t BooleanWeight::getValue() { return parentQuery->getBoost(); } Query* BooleanWeight::getQuery() { return (Query*)parentQuery; } BooleanWeight::BooleanWeight(Searcher* searcher, CLVector<BooleanClause*,Deletor::Object<BooleanClause> >* clauses, BooleanQuery* parentQuery) { this->searcher = searcher; this->similarity = parentQuery->getSimilarity( searcher ); this->parentQuery = parentQuery; this->clauses = clauses; for (uint32_t i = 0 ; i < clauses->size(); i++) { weights.push_back((*clauses)[i]->getQuery()->_createWeight(searcher)); } } BooleanWeight::~BooleanWeight(){ this->weights.clear(); } float_t BooleanWeight::sumOfSquaredWeights() { float_t sum = 0.0f; for (uint32_t i = 0 ; i < weights.size(); i++) { BooleanClause* c = (*clauses)[i]; Weight* w = weights[i]; float_t s = w->sumOfSquaredWeights(); // sum sub weights if (!c->isProhibited()) // only add to sum for non-prohibited clauses sum += s; } sum *= parentQuery->getBoost() * parentQuery->getBoost(); // boost each sub-weight return sum ; } void BooleanWeight::normalize(float_t norm) { norm *= parentQuery->getBoost(); // incorporate boost for (uint32_t i = 0 ; i < weights.size(); i++) { Weight* w = weights[i]; // normalize all clauses, (even if prohibited in case of side affects) w->normalize(norm); } } Scorer* BooleanWeight::scorer(IndexReader* reader){ BooleanScorer2* result = _CLNEW BooleanScorer2(similarity, parentQuery->minNrShouldMatch, parentQuery->allowDocsOutOfOrder); for (size_t i = 0 ; i < weights.size(); i++) { BooleanClause* c = (*clauses)[i]; Weight* w = weights[i]; Scorer* subScorer = w->scorer(reader); if (subScorer != NULL) result->add(subScorer, c->isRequired(), c->isProhibited()); else if (c->isRequired()){ _CLDELETE(result); return NULL; } } return result; } Explanation* BooleanWeight::explain(IndexReader* reader, int32_t doc){ const int32_t minShouldMatch = parentQuery->getMinNrShouldMatch(); ComplexExplanation* sumExpl = _CLNEW ComplexExplanation(); sumExpl->setDescription(_T("sum of:")); int32_t coord = 0; int32_t maxCoord = 0; float_t sum = 0.0f; bool fail = false; int32_t shouldMatchCount = 0; for (size_t i = 0 ; i < weights.size(); i++) { BooleanClause* c = (*clauses)[i]; Weight* w = weights[i]; Explanation* e = w->explain(reader, doc); if (!c->isProhibited()) maxCoord++; if (e->isMatch()){ if (!c->isProhibited()) { sumExpl->addDetail(e); sum += e->getValue(); coord++; } else { StringBuffer buf(100); buf.append(_T("match on prohibited clause (")); TCHAR* tmp = c->getQuery()->toString(); buf.append(tmp); _CLDELETE_LCARRAY(tmp); buf.appendChar(_T(')')); Explanation* r = _CLNEW Explanation(0.0f, buf.getBuffer()); r->addDetail(e); sumExpl->addDetail(r); fail = true; } if (c->getOccur() == BooleanClause::SHOULD) shouldMatchCount++; } else if (c->isRequired()) { StringBuffer buf(100); buf.append(_T("no match on required clause (")); TCHAR* tmp = c->getQuery()->toString(); buf.append(tmp); _CLDELETE_LCARRAY(tmp); buf.appendChar(_T(')')); Explanation* r = _CLNEW Explanation(0.0f, buf.getBuffer()); r->addDetail(e); sumExpl->addDetail(r); fail = true; } else { _CLLDELETE(e); } } if (fail) { sumExpl->setMatch(false); sumExpl->setValue(0.0f); sumExpl->setDescription(_T("Failure to meet condition(s) of required/prohibited clause(s)")); return sumExpl; } else if (shouldMatchCount < minShouldMatch) { sumExpl->setMatch(false); sumExpl->setValue(0.0f); StringBuffer buf(60); buf.append(_T("Failure to match minimum number of optional clauses: ")); buf.appendInt(minShouldMatch); sumExpl->setDescription(buf.getBuffer()); return sumExpl; } sumExpl->setMatch(0 < coord ? true : false); sumExpl->setValue(sum); float_t coordFactor = similarity->coord(coord, maxCoord); if (coordFactor == 1.0f) // coord is no-op return sumExpl; // eliminate wrapper else { ComplexExplanation* result = _CLNEW ComplexExplanation(sumExpl->isMatch(), sum*coordFactor, _T("product of:")); result->addDetail(sumExpl); StringBuffer buf(30); buf.append(_T("coord(")); buf.appendInt(coord); buf.appendChar(_T('/')); buf.appendInt(maxCoord); buf.appendChar(_T(')')); result->addDetail(_CLNEW Explanation(coordFactor,buf.getBuffer())); return result; } } BooleanClause::BooleanClause(Query* q, const bool DeleteQuery,const bool req, const bool p): query(q), occur(SHOULD), deleteQuery(DeleteQuery), required(req), prohibited(p) { if (required) { if (prohibited) { // prohibited && required doesn't make sense, but we want the old behaviour: occur = MUST_NOT; } else { occur = MUST; } } else { if (prohibited) { occur = MUST_NOT; } else { occur = SHOULD; } } } BooleanClause::BooleanClause(const BooleanClause& clone): query(clone.query->clone()), occur(clone.occur), deleteQuery(true), required(clone.required), prohibited(clone.prohibited) { } BooleanClause::BooleanClause(Query* q, const bool DeleteQuery, Occur o): query(q), occur(o), deleteQuery(DeleteQuery) { setFields(occur); } BooleanClause* BooleanClause::clone() const { BooleanClause* ret = _CLNEW BooleanClause(*this); return ret; } BooleanClause::~BooleanClause(){ if ( deleteQuery ) _CLDELETE( query ); } /** Returns true if <code>o</code> is equal to this. */ bool BooleanClause::equals(const BooleanClause* other) const { return this->query->equals(other->query) && (this->required == other->required) && (this->prohibited == other->prohibited) // TODO: Remove these && (this->occur == other->getOccur() ); } /** Returns a hash code value for this object.*/ size_t BooleanClause::hashCode() const { return query->hashCode() ^ ( (occur == MUST) ?1:0) ^ ( (occur == MUST_NOT)?2:0); } BooleanClause::Occur BooleanClause::getOccur() const { return occur; } void BooleanClause::setOccur(Occur o) { occur = o; setFields(o); } Query* BooleanClause::getQuery() const { return query; } void BooleanClause::setQuery(Query* q) { if ( deleteQuery ) _CLDELETE( query ); query = q; } bool BooleanClause::isProhibited() const { return prohibited; /* TODO: return (occur == MUST_NOT); */ } bool BooleanClause::isRequired() const { return required; /* TODO: return (occur == MUST); */ } TCHAR* BooleanClause::toString() const { CL_NS(util)::StringBuffer buffer; if (occur == MUST) buffer.append(_T("+")); else if (occur == MUST_NOT) buffer.append(_T("-")); buffer.append( query->toString() ); return buffer.toString(); } void BooleanClause::setFields(Occur occur) { if (occur == MUST) { required = true; prohibited = false; } else if (occur == SHOULD) { required = false; prohibited = false; } else if (occur == MUST_NOT) { required = false; prohibited = true; } else { _CLTHROWT (CL_ERR_UnknownOperator, _T("Unknown operator")); } } CL_NS_END
/* ** Return the cost of substituting cTo in place of cFrom assuming ** the previous character is cPrev. If cPrev==0 then cTo is the first ** character of the word. */ static int substituteCost(char cPrev, char cFrom, char cTo){ char classFrom, classTo; if( cFrom==cTo ){ return 0; } if( cFrom==(cTo^0x20) && ((cTo>='A' && cTo<='Z') || (cTo>='a' && cTo<='z')) ){ return 0; } classFrom = characterClass(cPrev, cFrom); classTo = characterClass(cPrev, cTo); if( classFrom==classTo ){ return classFrom=='A' ? 25 : 40; } if( classFrom>=CCLASS_B && classFrom<=CCLASS_Y && classTo>=CCLASS_B && classTo<=CCLASS_Y ){ return 75; } return 100; }
<gh_stars>1000+ import java.util.Arrays; public class Solution2 { // 贪心算法 public int leastInterval(char[] tasks, int n) { int[] cnt = new int[26]; for (char task : tasks) { cnt[task - 'A']++; } Arrays.sort(cnt); int maxVal = cnt[25] - 1; // idle 空闲 // slots 插槽 // 至少要占用这么多空闲的插槽 int idleSlots = maxVal * n; // 每次减去一个任务 for (int i = 24; i >= 0; i--) { if (cnt[i] <= 0) { break; } idleSlots -= Math.min(cnt[i], maxVal); } // 如果还有剩下,就把原来的不上 if (idleSlots > 0) { idleSlots += tasks.length; } else { // 说明:空闲个数,要讲清楚这里,最好要画图 idleSlots = tasks.length; } return idleSlots; } }
class Individual_Parameters: """Simulation parameters for a single individual in a dual-income simulation.""" @property def age_at_retirement(self): """The age at which this person will retire. (Inclusive, ie this is the first year they will no longer be working.)""" return self._age_at_retirement @age_at_retirement.setter def age_at_retirement(self, value): self._age_at_retirement = value @property def year_of_birth(self): """The year you got born, used to calculate year of retirement.""" return self._year_of_birth @year_of_birth.setter def year_of_birth(self, value): self._year_of_birth = value @property def age_at_death(self): """How old you will be when you die. Morbid, but necessary.""" return self._age_at_death @age_at_death.setter def age_at_death(self, value): self._age_at_death = value @property def initial_salary(self): """This person's yearly salary at the beginning of the simulation (typically, their present salary). """ return self._initial_salary @initial_salary.setter def initial_salary(self, value): self._initial_salary = value @property def initial_savings_rrsp(self): """The amount this person already has saved in a RRSP account (or accounts) at the beginning of the simulation.""" return self._initial_savings_rrsp @initial_savings_rrsp.setter def initial_savings_rrsp(self, value): self._initial_savings_rrsp = value @property def initial_savings_tfsa(self): """The amount this person already has saved in a TFSA account (or accounts) at the beginning of the simulation.""" return self._initial_savings_tfsa @initial_savings_tfsa.setter def initial_savings_tfsa(self, value): self._initial_savings_tfsa = value @property def year_of_retirement(self): return self.year_of_birth + self.age_at_retirement @property def year_of_death(self): return self.year_of_birth + self.age_at_death def is_retired(self, year : int): return year >= self.year_of_retirement
// Copyright 2015 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 expressions import ( "fmt" "github.com/juju/errors" "github.com/pingcap/tidb/context" "github.com/pingcap/tidb/expression" ) // FunctionSubstring returns the substring as specified. // See: https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring type FunctionSubstring struct { StrExpr expression.Expression Pos expression.Expression Len expression.Expression } // Clone implements the Expression Clone interface. func (f *FunctionSubstring) Clone() (expression.Expression, error) { expr, err := f.StrExpr.Clone() if err != nil { return nil, err } nf := &FunctionSubstring{ StrExpr: expr, Pos: f.Pos, Len: f.Len, } return nf, nil } // IsStatic implements the Expression IsStatic interface. func (f *FunctionSubstring) IsStatic() bool { return f.StrExpr.IsStatic() } // String implements the Expression String interface. func (f *FunctionSubstring) String() string { if f.Len != nil { return fmt.Sprintf("SUBSTRING(%s, %s, %s)", f.StrExpr.String(), f.Pos.String(), f.Len.String()) } return fmt.Sprintf("SUBSTRING(%s, %s)", f.StrExpr.String(), f.Pos.String()) } // Eval implements the Expression Eval interface. func (f *FunctionSubstring) Eval(ctx context.Context, args map[interface{}]interface{}) (interface{}, error) { fs, err := f.StrExpr.Eval(ctx, args) if err != nil { return nil, errors.Trace(err) } str, ok := fs.(string) if !ok { return nil, errors.Errorf("Substring invalid args, need string but get %T", fs) } t, err := f.Pos.Eval(ctx, args) if err != nil { return nil, errors.Trace(err) } p, ok := t.(int64) if !ok { return nil, errors.Errorf("Substring invalid pos args, need int but get %T", t) } pos := int(p) length := -1 if f.Len != nil { t, err := f.Len.Eval(ctx, args) if err != nil { return nil, errors.Trace(err) } p, ok := t.(int64) if !ok { return nil, errors.Errorf("Substring invalid len args, need int but get %T", t) } length = int(p) } // The forms without a len argument return a substring from string str starting at position pos. // The forms with a len argument return a substring len characters long from string str, starting at position pos. // The forms that use FROM are standard SQL syntax. It is also possible to use a negative value for pos. // In this case, the beginning of the substring is pos characters from the end of the string, rather than the beginning. // A negative value may be used for pos in any of the forms of this function. if pos < 0 { pos = len(str) + pos } else { pos-- } if pos > len(str) || pos <= 0 { pos = len(str) } end := len(str) if length != -1 { end = pos + length } if end > len(str) { end = len(str) } return str[pos:end], nil }
<filename>src/KdtreeISO/include/RectilinearGrid.h<gh_stars>10-100 // // Created by Danielhu on 2018/5/9. // #ifndef VOXELWORLD_RECTILINEARGRID_H #define VOXELWORLD_RECTILINEARGRID_H #include <vector> #include <map> #include <set> #include "Qef.h" #include "Mesh.h" #include "Topology.h" #include "Utils.h" #include "Vertex.h" #include "Indicators.h" #include "AxisAlignedLine.h" struct RectilinearGrid { PositionCode minCode; PositionCode maxCode; QefSolver allQef; std::vector<QefSolver> components; std::vector<Vertex> vertices; Vertex approximate; uint8_t cornerSigns[8]{0}; int8_t componentIndices[8]{0}; bool isSigned = false; std::map<RectilinearGrid *, Vertex *> faceVertices; explicit RectilinearGrid(PositionCode minCode = PositionCode(0, 0, 0), PositionCode maxCode = PositionCode(0, 0, 0), QefSolver sum = QefSolver()) : minCode(minCode), maxCode(maxCode), allQef(sum) { solve(allQef, approximate); } void solveComponent(int i); void solve(QefSolver &qef, Vertex &v); void assignSign(ScalarField *t); void calCornerComponents(); bool sampleQef(ScalarField *t, bool all); void draw(Mesh *mesh); inline glm::fvec3 cornerPos(int i) { return min_offset_subdivision(i) * codeToPos(maxCode - minCode, RectilinearGrid::getUnitSize()) + codeToPos(minCode, RectilinearGrid::getUnitSize()); } inline int edgeComponentIndex(int corner1, int corner2) { // assert(cornerSigns[corner1] != cornerSigns[corner2]); if (cornerSigns[corner1] != 0) { return componentIndices[corner1]; } return componentIndices[corner2]; } inline int faceComponentIndex(int faceDir, int edgeDir, int faceSide, int edgeSide) { int component = -1; int dir = 3 - faceDir - edgeDir; for (int i = 0; i < 2; ++i) { ivec3 code; code[faceDir] = faceSide; code[edgeDir] = edgeSide; code[dir] = i; int corner = encodeCell(code); if (cornerSigns[corner] > 0) { component = componentIndices[corner]; } } if (component != -1) { return component; } for (int i = 0; i < 2; ++i) { ivec3 code; code[faceDir] = faceSide; code[edgeDir] = 1 - edgeSide; code[dir] = i; int corner = encodeCell(code); if (cornerSigns[corner] > 0) { component = componentIndices[corner]; } } return component; } static void setUnitSize(float size); static float getUnitSize(); static bool calClusterability(RectilinearGrid *left, RectilinearGrid *right, int dir, const PositionCode &minCode, const PositionCode &maxCode, ScalarField *s); static void combineAAGrid(RectilinearGrid *left, RectilinearGrid *right, int dir, RectilinearGrid *out); static bool isInterFreeCondition2Faild(const std::vector<Vertex *> &polygons, const glm::fvec3 &p1, const glm::fvec3 &p2); template <class GridHolder> static bool checkSign(const std::array<GridHolder *, 4> &nodes, int quadDir1, int quadDir2, ScalarField *s, int &side, PositionCode &minEnd, PositionCode &maxEnd); template <class GridHolder> static void generateQuad(const std::array<GridHolder, 4> &nodes, int quadDir1, int quadDir2, Mesh *mesh, ScalarField *t, float threshold); private: static float unitSize; }; template <class GridHolder> bool RectilinearGrid::checkSign(const std::array<GridHolder *, 4> &nodes, int quadDir1, int quadDir2, ScalarField *s, int &side, PositionCode &minEnd, PositionCode &maxEnd) { int dir = 3 - quadDir1 - quadDir2; if (nodes[0] != nodes[1]) { maxEnd = minEnd = nodes[0]->grid.maxCode; } else { maxEnd = minEnd = nodes[3]->grid.minCode; } maxEnd[dir] = std::min( std::min(nodes[0]->grid.maxCode[dir], nodes[1]->grid.maxCode[dir]), std::min(nodes[2]->grid.maxCode[dir], nodes[3]->grid.maxCode[dir])); minEnd[dir] = std::max( std::max(nodes[0]->grid.minCode[dir], nodes[1]->grid.minCode[dir]), std::max(nodes[2]->grid.minCode[dir], nodes[3]->grid.minCode[dir])); if (minEnd[dir] >= maxEnd[dir]) { return false; } float v1 = s->index(minEnd); float v2 = s->index(maxEnd); if ((v1 >= 0 && v2 >= 0) || (v1 < 0 && v2 < 0)) { return false; } if (v2 >= 0 && v1 <= 0) { side = 0; } else { side = 1; } // for (int i = 0; i < 4; ++i) { // if (nodes[i] != nodes[oppositeQuadIndex(i)]) { // minEnd[dir] = nodes[i]->grid.minEnd[dir]; // maxEnd[dir] = nodes[i]->grid.maxEnd[dir]; // v1 = s->index(minEnd); // v2 = s->index(maxEnd); // if ((v1 > 0 && v2 > 0) || (v1 < 0 && v2 < 0)) { // return false; // } // } // } return true; } template <class GridHolder> void RectilinearGrid::generateQuad(const std::array<GridHolder, 4> &nodes, int quadDir1, int quadDir2, Mesh *mesh, ScalarField *t, float) { int edgeSide; PositionCode minEnd, maxEnd; if (!RectilinearGrid::checkSign(nodes, quadDir1, quadDir2, t, edgeSide, minEnd, maxEnd)) { return; } std::vector<Vertex *> polygons; int lineDir = 3 - quadDir1 - quadDir2; int componentIndices[4]; for (int i = 0; i < 4; ++i) { if (nodes[i] != nodes[oppositeQuadIndex(i)]) { int c1, c2; quadIndex(quadDir1, quadDir2, symmetryQuadIndex(i), c1, c2); componentIndices[i] = nodes[i]->grid.edgeComponentIndex(c1, c2); } else { componentIndices[i] = nodes[i]->grid.faceComponentIndex(quadDir2, lineDir, 1 - i / 2, edgeSide); } if (componentIndices[i] == -1) { return; } } polygons.push_back(&nodes[0]->grid.vertices.at(componentIndices[0])); if (nodes[0] != nodes[1]) { polygons.push_back(&nodes[1]->grid.vertices.at(componentIndices[1])); } polygons.push_back(&nodes[3]->grid.vertices.at(componentIndices[3])); if (nodes[2] != nodes[3]) { polygons.push_back(&nodes[2]->grid.vertices.at(componentIndices[2])); } std::set<Vertex *> identicals; for (auto v : polygons) { identicals.insert(v); } if (identicals.size() < 3) { return; } bool condition1Failed = false; int firstConcaveFaceVertex = 0; if (false) { int sameCellIndex[2] = {2, 3}; for (int i = 0; i < 4; ++i) { int testDir = (lineDir + i / 2 + 1) % 3; int edgeAdjacentCellIndexA = edgeTestNodeOrder[i][0]; int edgeAdjacentCellIndexB = edgeTestNodeOrder[i][1]; RectilinearGrid *a = &nodes[edgeAdjacentCellIndexA]->grid; RectilinearGrid *b = &nodes[edgeAdjacentCellIndexB]->grid; if (a != b) { if (a->faceVertices.find(b) != a->faceVertices.end()) { firstConcaveFaceVertex = i; condition1Failed = true; continue; } fvec3 faceMinA = fvec3(std::numeric_limits<float>::max()); fvec3 faceMinB = faceMinA; fvec3 faceMaxA = -fvec3(std::numeric_limits<float>::max()); fvec3 faceMaxB = faceMaxA; for (int j = 0; j < 4; ++j) { int subIndexA = faceProcFaceMask[testDir][j][0]; int subIndexB = faceProcFaceMask[testDir][j][1]; fvec3 cornerA = a->cornerPos(subIndexA); fvec3 cornerB = b->cornerPos(subIndexB); faceMinA = glm::min(cornerA, faceMinA); faceMinB = glm::min(cornerB, faceMinB); faceMaxA = glm::max(cornerA, faceMaxA); faceMaxB = glm::max(cornerB, faceMaxB); } fvec3 faceMin = glm::max(faceMinA, faceMinB); fvec3 faceMax = glm::min(faceMaxA, faceMaxB); if (!segmentFaceIntersection(a->vertices[componentIndices[edgeAdjacentCellIndexA]].hermiteP, b->vertices[componentIndices[edgeAdjacentCellIndexB]].hermiteP, faceMin, faceMax, testDir)) { fvec3 minEndDir = faceMin + directionMap(lineDir) * (faceMax - faceMin); fvec3 maxEndDir = faceMax - directionMap(lineDir) * (faceMax - faceMin); glm::fvec3 points[4] = {faceMin, minEndDir, faceMax, maxEndDir}; fvec3 massPointSum(0.f); int pointCount = 0; for (int k = 0; k < 4; ++k) { float v1 = t->value(points[k]); float v2 = t->value(points[(k + 1) % 4]); if ((v1 >= 0 && v2 < 0) || (v1 < 0 && v2 >= 0)) { fvec3 x; t->solve(points[k], points[(k + 1) % 4], x); massPointSum += x; pointCount++; } } if (pointCount > 0) { firstConcaveFaceVertex = i; auto faceV = new Vertex(massPointSum / (float)pointCount); mesh->addVertex(faceV, t); a->faceVertices[b] = faceV; b->faceVertices[a] = faceV; condition1Failed = true; } } } else { sameCellIndex[0] = edgeAdjacentCellIndexA; sameCellIndex[1] = edgeAdjacentCellIndexB; } } int minCellIndex = 0; for (int i = 0; i < 4; ++i) { int edgeAdjacentCellIndexA = edgeTestNodeOrder[i][0]; int edgeAdjacentCellIndexB = edgeTestNodeOrder[i][1]; if (edgeAdjacentCellIndexA != sameCellIndex[0] && edgeAdjacentCellIndexA != sameCellIndex[1] && edgeAdjacentCellIndexB != sameCellIndex[0] && edgeAdjacentCellIndexB != sameCellIndex[1]) { minCellIndex = edgeAdjacentCellIndexA; } } } fvec3 p1 = codeToPos(minEnd, RectilinearGrid::getUnitSize()); fvec3 p2 = codeToPos(maxEnd, RectilinearGrid::getUnitSize()); bool condition2Failed = isInterFreeCondition2Faild(polygons, p1, p2); if (polygons.size() > 3) { std::vector<Vertex *> reversePolygons = {polygons[1], polygons[2], polygons[3], polygons[0]}; bool reverseCondition2Failed = isInterFreeCondition2Faild(reversePolygons, p1, p2); if (!reverseCondition2Failed) { /// NOTE: the swap here happens whether intersection-free or not polygons.swap(reversePolygons); } condition2Failed = condition2Failed && reverseCondition2Failed; } #ifdef INTERSECTION_FREE if (condition1Failed || condition2Failed) { GridHolder circle[4] = {nodes[0], nodes[1], nodes[3], nodes[2]}; polygons.clear(); if (!condition2Failed) { std::vector<int> concaveFlags; std::vector<Vertex *> convexPart; int concaveCount = 0; for (int i = 0; i < 4; ++i) { int index = (i + firstConcaveFaceVertex) % 4; auto faceIter = circle[index]->grid.faceVertices.find(&circle[(index + 1) % 4]->grid); auto cellVertex = &(circle[(index + 1) % 4]->grid.vertices[componentIndices[(index + 1) % 4]]); if (faceIter != circle[index]->grid.faceVertices.end()) { polygons.push_back(faceIter->second); concaveFlags.push_back(1); convexPart.push_back(faceIter->second); concaveCount++; } polygons.push_back(cellVertex); concaveFlags.push_back(0); } for (int i = 0; i < polygons.size() - 2; ++i) { Vertex *triangle[3] = { polygons[0], polygons[i + 1], polygons[i + 2]}; mesh->addTriangle(triangle, t); } } else { Vertex edgeVertex; t->solve(p1, p2, edgeVertex.hermiteP); mesh->addVertex(&edgeVertex, t); for (int i = 0; i < 4; ++i) { RectilinearGrid *a = &circle[i]->grid; RectilinearGrid *b = &circle[(i + 1) % 4]->grid; if (a != b) { polygons.push_back(&a->vertices[componentIndices[i]]); auto faceVIter = a->faceVertices.find(b); if (faceVIter != a->faceVertices.end()) { polygons.push_back(faceVIter->second); polygons.push_back(faceVIter->second); } polygons.push_back(&b->vertices[componentIndices[(i + 1) % 4]]); } } for (int i = 0; i < polygons.size() / 2; ++i) { Vertex *triangle[3] = { &edgeVertex, polygons[i * 2], polygons[i * 2 + 1]}; mesh->addTriangle(triangle, t); } } } else { #endif for (int i = 2; i < polygons.size(); ++i) { Vertex *triangle[3] = { polygons[0], polygons[i - 1], polygons[i]}; mesh->addTriangle(triangle, t); } #ifdef INTERSECTION_FREE } #endif } #endif //VOXELWORLD_RECTILINEARGRID_H
def predict(self, game, q): a = self.actions[q] return a
<filename>app/src/main/java/cz/damematiku/damematiku/MathApplication.java<gh_stars>1-10 package cz.damematiku.damematiku; import android.app.Application; import android.content.Context; import cz.damematiku.damematiku.depinject.component.ApplicationComponent; import cz.damematiku.damematiku.depinject.component.BaseComponent; import cz.damematiku.damematiku.depinject.component.DaggerApplicationComponent; import cz.damematiku.damematiku.depinject.component.DaggerBaseComponent; import cz.damematiku.damematiku.depinject.module.ApplicationModule; /** * Created by semanticer on 23. 4. 2016. */ public class MathApplication extends Application { private static BaseComponent baseComponent; @Override public void onCreate() { super.onCreate(); ApplicationComponent applicationComponent = DaggerApplicationComponent .builder() .applicationModule(new ApplicationModule(this)) .build(); baseComponent = DaggerBaseComponent.builder() .applicationComponent(applicationComponent) .build(); } public static BaseComponent getBaseComponent(){ return baseComponent; } }
import urllib import json import twitter import sqlite3 import os from HTMLParser import HTMLParser import nltk class Worker(object): def __init__(self, profile_id, oauth, cursor): self.google_api_key = '---' # Google API Key self.profile_id = profile_id self.cursor = cursor self.oauth = oauth def _get_from_gplus(self): if not self.profile_id: return data = urllib.urlopen( 'https://www.googleapis.com/plus/v1/people/{0}/activities/public?key={1}'.format( self.profile_id, self.google_api_key ) ).read() items = json.loads(data).get('items') if not items: return 'exists' the_thing = items[0] try: self.cursor.execute("insert into posts values(?)", (the_thing['url'],)) except sqlite3.IntegrityError: return 'exists' return HTMLParser().unescape(u'G+: '+nltk.clean_html(the_thing['object']['content'])[:64]).replace('\n', ' ')+u' ... '+the_thing['url'] def _post_to_twitter(self, tweet, user): if tweet == 'exists': return twitter.Api(**self.oauth).PostUpdate(tweet) def work(self): self._post_to_twitter(self._get_from_gplus(), 'tim') if __name__ == "__main__": with sqlite3.connect(os.path.join(os.path.dirname(__file__), 'gplustotwitter.db')) as conn: cursor = conn.cursor() # Users -> Twitter OAuth credentials users = {'tim':{'oauth':{'consumer_key':'---', 'consumer_secret':'---', 'access_token_key':'---', 'access_token_secret':'---'}, 'gplus_id':'---' #Google+ account ID }, } for user in users.keys(): Worker(users[user]['gplus_id'], users[user]['oauth'], cursor).work() conn.commit()
<reponame>timmartin19/turbogears<filename>turbogears/visit/api.py<gh_stars>0 import logging import sha import threading import time try: set() except NameError: from sets import Set as set from random import random from datetime import timedelta, datetime import cherrypy import pkg_resources from cherrypy.filters.basefilter import BaseFilter from turbogears import config from psycopg2.extensions import TransactionRollbackError import traceback log = logging.getLogger("turbogears.visit") # Global VisitManager _manager = None # Global list of plugins for the Visit Tracking framework _plugins = list() # Accessor functions for getting and setting the current visit information. def current(): """Retrieve the current visit record from the cherrypy request.""" return getattr(cherrypy.request, "tg_visit", None) def set_current(visit): """Set the current visit record on the cherrypy request being processed.""" cherrypy.request.tg_visit = visit def _create_visit_manager(timeout): """Create a VisitManager based on the plugin specified in the config file.""" plugin_name = config.get("visit.manager", "sqlobject") plugins = pkg_resources.iter_entry_points( "turbogears.visit.manager", plugin_name) log.debug("Loading visit manager from plugin: %s", plugin_name) for entrypoint in plugins: plugin = entrypoint.load() return plugin(timeout) raise RuntimeError("VisitManager plugin missing: %s" % plugin_name) class MonkeyDecodingFilter(BaseFilter): def decode(from_enc): """Recursively decode all values in an iterable from specified encoding.""" def decode_from(value, from_enc): if isinstance(value, dict): for k, v in value.items(): value[k] = decode_from(v, from_enc) elif isinstance(value, list): newlist = list() for item in value: newlist.append(decode_from(item, from_enc)) value = newlist elif isinstance(value, str): return value.decode(from_enc) return value decoded_params = decode_from(cherrypy.request.params, from_enc) # This is done in two steps to make sure the exception in # before_main can retry a decode with another encoding if needed. # DON'T merge those two lines. cherrypy.request.params = decoded_params decode = staticmethod(decode) def before_main(self): """Monkey patch CherryPy's decoding filter.""" conf = cherrypy.config.get if not conf('decoding_filter.on', False): return if getattr(cherrypy.request, "_decoding_attempted", False): return cherrypy.request._decoding_attempted = True enc = conf('decoding_filter.encoding', None) if not enc: ct = cherrypy.request.headers.elements("Content-Type") if ct: ct = ct[0] enc = ct.params.get("charset", None) if not enc and ct.value.lower().startswith("text/"): # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1 # When no explicit charset parameter is provided by the # sender, media subtypes of the "text" type are defined # to have a default charset value of "ISO-8859-1" when # received via HTTP. enc = "ISO-8859-1" if not enc: enc = conf('decoding_filter.default_encoding', "utf-8") try: self.decode(enc) except UnicodeDecodeError: # IE and Firefox don't supply a charset when submitting form # params with a CT of application/x-www-form-urlencoded. # So after all our guessing, it could *still* be wrong. # Start over with ISO-8859-1, since that seems to be preferred. self.decode("ISO-8859-1") # Interface for the TurboGears extension def start_extension(): # TODO: This should alway be active even when visit is not on, # we should find a better place to load this code... # Monkey patch CP Decoding filter # TODO: Is there a better way to inject this? # (maybe earlier than start_extension?) # monkey inject our replacement filter into the CP2 filter chain decoding_filter = MonkeyDecodingFilter() for index, active_filter in enumerate( cherrypy.filters._filterhooks.get('before_main', [])): if active_filter.im_class == \ cherrypy.filters.decodingfilter.DecodingFilter: cherrypy.filters._filterhooks['before_main'].pop(index) cherrypy.filters._filterhooks['before_main'].insert( index, decoding_filter.before_main) # Here is the real visit code. # Bail out if the application hasn't enabled this extension if not config.get("visit.on", False): return # Bail out if this extension is already running global _manager if _manager: return log.info("Visit Tracking starting") # How long may the visit be idle before a new visit ID is assigned? # The default is 20 minutes. timeout = timedelta(minutes=config.get("visit.timeout", 20)) # Create the thread that manages updating the visits _manager = _create_visit_manager(timeout) visit_filter = VisitFilter() # Install Filter into the root filter chain if not hasattr(cherrypy.root, "_cp_filters"): cherrypy.root._cp_filters = list() cherrypy.root._cp_filters.append(visit_filter) def shutdown_extension(): # Bail out if this extension is not running. global _manager if not _manager: return log.info("Visit Tracking shutting down") _manager.shutdown() _manager = None def create_extension_model(): """Create the data model of the VisitManager if one exists.""" if _manager: _manager.create_model() def enable_visit_plugin(plugin): """Register a visit tracking plugin. These plugins will be called for each request. """ _plugins.append(plugin) class Visit(object): """Basic container for visit related data.""" def __init__(self, key, is_new): self.key = key self.is_new = is_new class VisitFilter(BaseFilter): """A filter that automatically tracks visitors.""" def __init__(self): log.info("Visit filter initialized") get = config.get # Where to look for the session key in the request and in which order self.source = [s.strip().lower() for s in get("visit.source", "cookie").split(',')] if set(self.source).difference(('cookie', 'form')): log.warning("Unsupported 'visit.source' '%s' in configuration.") # Get the name to use for the identity cookie. self.cookie_name = get("visit.cookie.name", "tg-visit") # and the name of the request param. MUST NOT contain dashes or dots, # otherwise the NestedVariablesFilter will chocke on it. self.visit_key_param = get("visit.form.name", "tg_visit") # TODO: The path should probably default to whatever # the root is masquerading as in the event of a # virtual path filter. self.cookie_path = get("visit.cookie.path", "/") # The secure bit should be set for HTTPS only sites self.cookie_secure = get("visit.cookie.secure", False) # By default, I don't specify the cookie domain. self.cookie_domain = get("visit.cookie.domain", None) assert self.cookie_domain != "localhost", "localhost" \ " is not a valid value for visit.cookie.domain. Try None instead." # Use max age only if the cookie shall explicitly be permanent self.cookie_max_age = get("visit.cookie.permanent", False) and int(get("visit.timeout", "20")) * 60 or None def before_main(self): """Check whether submitted request belongs to an existing visit.""" if not config.get("visit.on", True): set_current(None) return cpreq = cherrypy.request visit = current() if not visit: visit_key = None for source in self.source: if source == 'cookie': visit_key = cpreq.simple_cookie.get(self.cookie_name) if visit_key: visit_key = visit_key.value log.debug("Retrieved visit key '%s' from cookie '%s'.", visit_key, self.cookie_name) elif source == 'form': visit_key = cpreq.params.pop(self.visit_key_param, None) log.debug( "Retrieved visit key '%s' from request param '%s'.", visit_key, self.visit_key_param) if visit_key: visit = _manager.visit_for_key(visit_key) break if not visit: visit_key = self._generate_key() visit = _manager.new_visit_with_key(visit_key) log.debug("Created new visit with key: %s", visit_key) else: log.debug("Using visit from request with key: %s", visit_key) self.send_cookie(visit_key) set_current(visit) # Inform all the plugins that a request has been made for the current # visit. This gives plugins the opportunity to track click-path or # retrieve the visitor's identity. try: for plugin in _plugins: plugin.record_request(visit) except cherrypy.InternalRedirect, e: # Can't allow an InternalRedirect here because CherryPy is dumb, # instead change cherrypy.request.object_path to the url desired. cherrypy.request.object_path = e.path def _generate_key(): """Return a (pseudo)random hash based on seed.""" # Adding remoteHost and remotePort doesn't make this any more secure, # but it makes people feel secure... It's not like I check to make # certain you're actually making requests from that host and port. So # it's basically more noise. key_string = '%s%s%s%s' % (random(), datetime.now(), cherrypy.request.remote_host, cherrypy.request.remote_port) return sha.new(key_string).hexdigest() _generate_key = staticmethod(_generate_key) def clear_cookie(self): """Clear any existing visit ID cookie.""" cookies = cherrypy.response.simple_cookie # clear the cookie log.debug("Clearing visit ID cookie") cookies[self.cookie_name] = '' cookies[self.cookie_name]['path'] = self.cookie_path cookies[self.cookie_name]['expires'] = '' cookies[self.cookie_name]['max-age'] = 0 def send_cookie(self, visit_key): """Send an visit ID cookie back to the browser.""" cookies = cherrypy.response.simple_cookie cookies[self.cookie_name] = visit_key cookies[self.cookie_name]['path'] = self.cookie_path if self.cookie_secure: cookies[self.cookie_name]['secure'] = True if self.cookie_domain: cookies[self.cookie_name]['domain'] = self.cookie_domain max_age = self.cookie_max_age if max_age: # use 'expires' because MSIE ignores 'max-age' cookies[self.cookie_name]['expires'] = time.strftime( "%a, %d-%b-%Y %H:%M:%S GMT", time.gmtime(time.time() + max_age)) # 'max-age' takes precedence on standard conformant browsers # (this is better because there of no time sync issues here) cookies[self.cookie_name]['max-age'] = max_age log.debug("Sending visit ID cookie: %s", cookies[self.cookie_name].output()) class BaseVisitManager(threading.Thread): def __init__(self, timeout): super(BaseVisitManager, self).__init__(name="VisitManager") self.timeout = timeout self.queue = dict() self.lock = threading.Lock() self._shutdown = threading.Event() self.interval = 30 self.setDaemon(True) # We need to create the visit model before the manager thread is # started. self.create_model() self.start() def create_model(self): pass def new_visit_with_key(self, visit_key): """Return a new Visit object with the given key.""" raise NotImplementedError def visit_for_key(self, visit_key): """Return the visit for this key. Return None if the visit doesn't exist or has expired. """ raise NotImplementedError def update_queued_visits(self, queue): """Extend the expiration of the queued visits.""" raise NotImplementedError def update_visit(self, visit_key, expiry): try: self.lock.acquire() self.queue[visit_key] = expiry finally: self.lock.release() def shutdown(self, timeout=None): self._shutdown.set() self.join(timeout) if self.isAlive(): log.error("Visit Manager thread failed to shutdown.") def run(self): while not self._shutdown.isSet(): self.lock.acquire() queue = None try: # make a copy of the queue and empty the original if self.queue: queue = self.queue.copy() self.queue.clear() finally: self.lock.release() if queue is not None: try: self.update_queued_visits(queue) except TransactionRollbackError: traceback.print_exc() try: self.lock.acquire() self.queue.update(queue) finally: self.lock.release() self._shutdown.wait(self.interval)
/** * Tests for the redirect response. * * @author Luc Everse */ public class RedirectResponseTest { @Test public void test() { final RedirectResponse response = new RedirectResponse("/page/home"); response.prepare(null); assertThat(response.getHeaders()).as("headers") .containsEntry("Location", Collections.singletonList("/page/home")); assertThat(response.getStatus()).as("status").isEqualTo(ResponseCode.FOUND); } }
package main import ( "fmt" ) func main(){ makeRecursiveFunction(); } func makeRecursiveFunction(){ x := func(x,y int) int{ return x + y } fmt.Println(x(4,5)) }
<filename>config.go package main type Config struct { SN string `json:"sn"` Ver uint `json:"ver"` Cfg map[string]string `json:"cfg"` } type Registration struct { Config ID string `json:"id"` TS string `json:"ts"` }
<reponame>MC-JY/azure-sdk-for-java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.datafactory.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** Fail activity properties. */ @Fluent public final class FailActivityTypeProperties { @JsonIgnore private final ClientLogger logger = new ClientLogger(FailActivityTypeProperties.class); /* * The error message that surfaced in the Fail activity. It can be dynamic * content that's evaluated to a non empty/blank string at runtime. Type: * string (or Expression with resultType string). */ @JsonProperty(value = "message", required = true) private Object message; /* * The error code that categorizes the error type of the Fail activity. It * can be dynamic content that's evaluated to a non empty/blank string at * runtime. Type: string (or Expression with resultType string). */ @JsonProperty(value = "errorCode", required = true) private Object errorCode; /** * Get the message property: The error message that surfaced in the Fail activity. It can be dynamic content that's * evaluated to a non empty/blank string at runtime. Type: string (or Expression with resultType string). * * @return the message value. */ public Object message() { return this.message; } /** * Set the message property: The error message that surfaced in the Fail activity. It can be dynamic content that's * evaluated to a non empty/blank string at runtime. Type: string (or Expression with resultType string). * * @param message the message value to set. * @return the FailActivityTypeProperties object itself. */ public FailActivityTypeProperties withMessage(Object message) { this.message = message; return this; } /** * Get the errorCode property: The error code that categorizes the error type of the Fail activity. It can be * dynamic content that's evaluated to a non empty/blank string at runtime. Type: string (or Expression with * resultType string). * * @return the errorCode value. */ public Object errorCode() { return this.errorCode; } /** * Set the errorCode property: The error code that categorizes the error type of the Fail activity. It can be * dynamic content that's evaluated to a non empty/blank string at runtime. Type: string (or Expression with * resultType string). * * @param errorCode the errorCode value to set. * @return the FailActivityTypeProperties object itself. */ public FailActivityTypeProperties withErrorCode(Object errorCode) { this.errorCode = errorCode; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (message() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property message in model FailActivityTypeProperties")); } if (errorCode() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property errorCode in model FailActivityTypeProperties")); } } }
<gh_stars>1000+ // 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. #include <gtest/gtest.h> #include <iostream> #include <string> #include <thread> #include <unordered_map> #include "arrow/testing/util.h" #include "arrow/util/logging.h" #include "parquet/encryption/crypto_factory.h" #include "parquet/encryption/key_toolkit.h" #include "parquet/encryption/test_encryption_util.h" #include "parquet/encryption/test_in_memory_kms.h" #include "parquet/test_util.h" namespace parquet { namespace encryption { namespace test { std::unique_ptr<TemporaryDir> temp_dir; class TestEncryptionKeyManagement : public ::testing::Test { public: void SetUp() { #ifndef ARROW_WITH_SNAPPY GTEST_SKIP() << "Test requires Snappy compression"; #endif key_list_ = BuildKeyMap(kColumnMasterKeyIds, kColumnMasterKeys, kFooterMasterKeyId, kFooterMasterKey); column_key_mapping_ = BuildColumnKeyMapping(); } static void SetUpTestCase(); protected: FileEncryptor encryptor_; FileDecryptor decryptor_; std::unordered_map<std::string, std::string> key_list_; std::string column_key_mapping_; KmsConnectionConfig kms_connection_config_; CryptoFactory crypto_factory_; bool wrap_locally_; void SetupCryptoFactory(bool wrap_locally) { wrap_locally_ = wrap_locally; std::shared_ptr<KmsClientFactory> kms_client_factory = std::make_shared<TestOnlyInMemoryKmsClientFactory>(wrap_locally, key_list_); crypto_factory_.RegisterKmsClientFactory(kms_client_factory); } std::string GetFileName(bool double_wrapping, bool wrap_locally, int encryption_no) { std::string file_name; file_name += double_wrapping ? "double_wrapping" : "no_double_wrapping"; file_name += wrap_locally ? "-wrap_locally" : "-wrap_on_server"; switch (encryption_no) { case 0: file_name += "-encrypt_columns_and_footer_diff_keys"; break; case 1: file_name += "-encrypt_columns_not_footer"; break; case 2: file_name += "-encrypt_columns_and_footer_same_keys"; break; case 3: file_name += "-encrypt_columns_and_footer_ctr"; break; default: file_name += "-no_encrypt"; break; } file_name += encryption_no == 4 ? ".parquet" : ".parquet.encrypted"; return file_name; } EncryptionConfiguration GetEncryptionConfiguration(bool double_wrapping, int encryption_no) { EncryptionConfiguration encryption(kFooterMasterKeyId); encryption.double_wrapping = double_wrapping; switch (encryption_no) { case 0: // encrypt some columns and footer, different keys encryption.column_keys = column_key_mapping_; break; case 1: // encrypt columns, plaintext footer, different keys encryption.column_keys = column_key_mapping_; encryption.plaintext_footer = true; break; case 2: // encrypt some columns and footer, same key encryption.uniform_encryption = true; break; case 3: // Encrypt two columns and the footer, with different keys. // Use AES_GCM_CTR_V1 algorithm. encryption.column_keys = column_key_mapping_; encryption.encryption_algorithm = ParquetCipher::AES_GCM_CTR_V1; break; default: // no encryption ARROW_LOG(FATAL) << "Invalid encryption_no"; } return encryption; } DecryptionConfiguration GetDecryptionConfiguration() { return DecryptionConfiguration(); } void WriteEncryptedParquetFile(bool double_wrapping, int encryption_no) { std::string file_name = GetFileName(double_wrapping, wrap_locally_, encryption_no); auto encryption_config = GetEncryptionConfiguration(double_wrapping, encryption_no); auto file_encryption_properties = crypto_factory_.GetFileEncryptionProperties( kms_connection_config_, encryption_config); std::string file = temp_dir->path().ToString() + file_name; encryptor_.EncryptFile(file, file_encryption_properties); } void ReadEncryptedParquetFile(bool double_wrapping, int encryption_no) { auto decryption_config = GetDecryptionConfiguration(); std::string file_name = GetFileName(double_wrapping, wrap_locally_, encryption_no); auto file_decryption_properties = crypto_factory_.GetFileDecryptionProperties( kms_connection_config_, decryption_config); std::string file = temp_dir->path().ToString() + file_name; decryptor_.DecryptFile(file, file_decryption_properties); } }; class TestEncryptionKeyManagementMultiThread : public TestEncryptionKeyManagement { protected: void WriteEncryptedParquetFiles() { std::vector<std::thread> write_threads; for (const bool double_wrapping : {false, true}) { for (int encryption_no = 0; encryption_no < 4; encryption_no++) { write_threads.push_back(std::thread([this, double_wrapping, encryption_no]() { this->WriteEncryptedParquetFile(double_wrapping, encryption_no); })); } } for (auto& th : write_threads) { th.join(); } } void ReadEncryptedParquetFiles() { std::vector<std::thread> read_threads; for (const bool double_wrapping : {false, true}) { for (int encryption_no = 0; encryption_no < 4; encryption_no++) { read_threads.push_back(std::thread([this, double_wrapping, encryption_no]() { this->ReadEncryptedParquetFile(double_wrapping, encryption_no); })); } } for (auto& th : read_threads) { th.join(); } } }; TEST_F(TestEncryptionKeyManagement, WrapLocally) { this->SetupCryptoFactory(true); for (const bool double_wrapping : {false, true}) { for (int encryption_no = 0; encryption_no < 4; encryption_no++) { this->WriteEncryptedParquetFile(double_wrapping, encryption_no); this->ReadEncryptedParquetFile(double_wrapping, encryption_no); } } } TEST_F(TestEncryptionKeyManagement, WrapOnServer) { this->SetupCryptoFactory(false); for (const bool double_wrapping : {false, true}) { for (int encryption_no = 0; encryption_no < 4; encryption_no++) { this->WriteEncryptedParquetFile(double_wrapping, encryption_no); this->ReadEncryptedParquetFile(double_wrapping, encryption_no); } } } TEST_F(TestEncryptionKeyManagementMultiThread, WrapLocally) { this->SetupCryptoFactory(true); this->WriteEncryptedParquetFiles(); this->ReadEncryptedParquetFiles(); } TEST_F(TestEncryptionKeyManagementMultiThread, WrapOnServer) { this->SetupCryptoFactory(false); this->WriteEncryptedParquetFiles(); this->ReadEncryptedParquetFiles(); } // Set temp_dir before running the write/read tests. The encrypted files will // be written/read from this directory. void TestEncryptionKeyManagement::SetUpTestCase() { temp_dir = *temp_data_dir(); } } // namespace test } // namespace encryption } // namespace parquet
<filename>tibco_core_jms_8/src/main/java/com/newrelic/instrumentation/tibco/jms2/OutboundWrapper.java package com.newrelic.instrumentation.tibco.jms2; import java.util.logging.Level; import javax.jms.JMSException; import javax.jms.Message; import com.newrelic.api.agent.HeaderType; import com.newrelic.api.agent.NewRelic; import com.newrelic.api.agent.OutboundHeaders; public class OutboundWrapper implements OutboundHeaders { private final Message delegate; public OutboundWrapper(Message message) { delegate = message; } @Override public HeaderType getHeaderType() { return HeaderType.MESSAGE; } @Override public void setHeader(String name, String value) { try { delegate.setStringProperty(name, value); } catch (JMSException e) { NewRelic.getAgent().getLogger().log(Level.FINE, e, "Error setting property ({0}) on JMS message.", new Object[] { name }); } } }
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/ManagedConfiguration.framework/ManagedConfiguration */ @interface MCWebClipPayload : MCPayload { NSURL * _URL; bool _fullScreen; NSNumber * _fullScreenNum; NSData * _iconData; bool _isRemovable; NSNumber * _isRemovableNum; NSString * _label; bool _precomposed; NSNumber * _precomposedNum; NSString * _savedIdentifier; } @property (nonatomic, readonly, retain) NSURL *URL; @property (nonatomic, readonly) bool fullScreen; @property (nonatomic, readonly) NSNumber *fullScreenNum; @property (nonatomic, readonly, retain) NSData *iconData; @property (nonatomic, readonly) bool isRemovable; @property (nonatomic, readonly) NSNumber *isRemovableNum; @property (nonatomic, readonly, retain) NSString *label; @property (nonatomic, readonly) bool precomposed; @property (nonatomic, readonly) NSNumber *precomposedNum; @property (nonatomic, retain) NSString *savedIdentifier; + (id)localizedPluralForm; + (id)localizedSingularForm; + (id)typeStrings; - (void).cxx_destruct; - (id)URL; - (id)description; - (bool)fullScreen; - (id)fullScreenNum; - (id)iconData; - (id)initWithDictionary:(id)arg1 profile:(id)arg2 outError:(id*)arg3; - (bool)isRemovable; - (id)isRemovableNum; - (id)label; - (id)payloadDescriptionKeyValueSections; - (bool)precomposed; - (id)precomposedNum; - (id)savedIdentifier; - (void)setSavedIdentifier:(id)arg1; - (id)stubDictionary; - (id)subtitle1Description; - (id)subtitle1Label; - (id)subtitle2Description; - (id)subtitle2Label; - (id)title; @end
Sentiment Analysis of Airport Customer Reviews Customer satisfaction plays an important factor for the business’ success, particularly in aviation industries. One way to measure customer satisfaction level is using customer reviews. This study evaluates and analyzes customer reviews of services and facilities of Soekarno-Hatta Airport as the largest airport in Indonesia using text mining approach of sentimental analysis. Support vector machine and Naïve Bayes classifier are classification techniques used to identify positive or negative sentiments contained in review sentence. The results of classification techniques for sentiment analysis in this study indicate that support vector machine has higher accuracy value than Naïve Bayes Classifier in analyzing sentiments. The output of this study is evaluation in improving the quality of airport services and facilities, identification of service aspect and airport facility which become the strength and weakness as well as improvement prioritization of aspects that still become weakness in achieving desired level of customer satisfaction.
Fatal Frame coming to US PSN next week Sony have announced that the PS2 survival-horror classic, Fatal Frame, will be releasing to the US PSN next week. Starring a young girl named Miku who, along with her brother, can see spirits and otherworldly things that are invisible to normal people. She goes after her now-missing sibling to an abandoned manor that holds a dark curse, and comes in possession with the Camera Obscura, which can capture souls on film. To clear a couple things up, if some are wondering about the ‘co-ownership’ of the Fatal Frame IP with Nintendo, that is a common misunderstanding. What is actually owned by Nintendo are the partial rights to Fatal Frame IV, Project Zero 2: Wii Edition, and Spirit Camera, which they funded and partially helped develop, rather than the whole IP. However, Nintendo and Tecmo have been pretty close recently, so it is not doubtful that future entries in the series will likely be made in partnership with Nintendo. Secondly, even if the game tells you otherwise, Fatal Frame is not actually based on a true story. This was added by American marketing who thought it might help the game’s public image, which is ‘supported’ by the game loosely being based off of a real-world location on the outskirts of Tokyo that has a haunted past. However, none of the events in Fatal Frame are based on any story of the real-world location’s history. It’s nice to see classic survival-horror games from yesteryear receive digital releases, allowing old and new fans alike to experience the bone-chilling horror. If you’re a fan of classic survival-horror, this is definitely something you’ll want to check out. [Source]
def Kgrad_param(self,i): X = self._getX() Xgrad = self._getXgrad(i) import pdb RV = SP.dot(X,Xgrad.T)+SP.dot(Xgrad,X.T) return RV
Asymptomatic Coronavirus Disease 2019 (COVID-19) Carriers: Are They Infectious? Coronavirus disease 2019 (COVID-19) is highly contagious in symptomatic patients as it is thought to be transmitted through respiratory droplets. However, it is debatable whether asymptomatic COVID-19 patients are contagious due to lack of data. From 1 March to 15 April 2020, a total of 247 COVID-19 cases were admitted to Tengku Ampuan Afzan Hospital and 1010 close contacts were identified. We studied the epidemiological and clinical outcomes in asymptomatic subjects, as well as estimated the metrics of disease transmission between asymptomatic, symptomatic, and pneumonia subjects. From a total of 125 asymptomatic subjects, majority (n=116, 92.8%) remained asymptomatic upon discharge. Only 9 (7.2%) subjects developed mild symptoms after admission. Seven subjects had abnormal chest radiograph suggestive of pneumonia, and 22 subjects (17.6%) were found to have mild liver impairment. None of the asymptomatic subjects required oxygen support, inotropic support or ICU care during admission. Fifteen second generation COVID-19 cases were found transmitted from the asymptomatic group, with an attack rate of 3.9%, which was statistically significantly lower compared to the symptomatic (7.6%) or pneumonia groups (25.7%, p<0.001). In conclusion, asymptomatic COVID-19 patients show excellent clinical outcome. They are infectious but had a lower transmission risk compared with symptomatic or pneumonia patients. Introduction Coronavirus disease 2019 (COVID- 19), which was first reported in December 2019 in Wuhan, China, was declared a pandemic disease by the World Health Organization (WHO) on 12 March 2020 . The first COVID-19 case in Malaysia was detected on 25 th January 2020 . Following that, there was a massive spike of cases that emerged in March, which was linked to a religious gathering held in Sri Petaling, Kuala Lumpur . Within one month, Malaysia had recorded the largest cumulative number of confirmed COVID-19 infections in Southeast Asia, breaching over 3000 active cases by 3rd April 2020 . COVID-19 is highly contagious in symptomatic patients as it is thought to be transmitted through respiratory droplets . Zou et al . reported that higher viral loads were detected soon after symptoms onset. On the other hand, it is debatable whether asymptomatic COVID-19 patients are contagious due to a lack of data. To date, there are conflicting data regarding the risk of transmission among asymptomatic patients. In a recent paper, He et al. reported 6 cases that were transmitted from 30 asymptomatic cases in Ningbo, China . Chan et al. reported a case of transmission from an asymptomatic patient to the family members, which led to severe pneumonia . On the other hand, Cheng et al. reported that none of the 9 asymptomatic patients transmitted COVID-19 to others . Prompt public health measures were taken in Malaysia, including intensive surveillance and routine hospitalization for all classes of COVID-19 patients, including asymptomatic individuals . Tengku Ampuan Afzan Hospital (HTAA) is a general hospital and the only hospital designated to treat patients with COVID-19 in Pahang state, with a population of 1.6 million. In this study, we aim to evaluate the outcome of asymptomatic COVID-19 patients. We also want to determine the attack rate of asymptomatic patients compared to patients who are symptomatic with or without pneumonia. These data are important for better disease control measures. Methods This is a retrospective study performed at HTAA, Malaysia, from 1 st March 2020 until 15 th April 2020. A total of 247 adult patients with COVID-19 infection were admitted to HTAA during this period. All patients had tested positive for COVID-19 via laboratory testing with real-time reverse transcriptase polymerase chain reaction (RT-PCR) of respiratory secretions obtained by nasopharyngeal or oropharyngeal swab. All patients had a chest X-ray performed on admission and repeated on a weekly basis as part of the management protocol. Swabs were repeated on day 13 following the last contact and those with negative results were subsequently discharged. We analyzed all asymptomatic patients aged >18 years. Their demographic data, laboratory results, and clinical outcome were reviewed. Those patients who had symptoms after contact but were asymptomatic on admission were excluded ( Figure 1). Thorough contact tracing was implemented by the outbreak investigation team of the Pahang Centers for Disease Control and Prevention (CDC) and District Health Office. Close contacts were identified according to WHO guidelines. The definition involved persons who experienced face-to-face contact within 1 meter and for more than 15 minutes, direct physical contact or direct care for a patient with probable or confirmed COVID-19, without appropriate proper personal protective equipment, in the 2 days before and 14 days after the onset of symptoms . If the first swab was negative, a second swab was taken 13 days after the last close contact with positive subjects. For the analysis of transmission, data from close contacts were obtained from Pahang Disease Control and Prevention. Close contacts who had multiple contacts with confirmed cases were excluded from analysis because we were not able to ascertain the source of infection. This included group travelers who were travelling with asymptomatic patients, students from boarding schools who stayed together and colleagues who work in the same environment. Attack rate was calculated by the total number of infected close contacts divided by close contacts screened. For the purpose of comparison, we also analyzed attack rate among those patients who were symptomatic, as well as in those with pneumonia. The definitions are as follows: (1) Asymptomatic: A person infected with COVID-19 who does not develop symptoms . (2) Symptomatic: a case who had developed signs and symptoms compatible with COVID-19 infection but who does not have clinical or radiological evidence of pneumonia. (3) Pneumonia: a case infected with COVID-19 who has clinical and radiological confirmation of pneumonia. Results A total of 247 cases were admitted and 125 subjects who were asymptomatic during laboratory confirmation for SARS-CoV-2 RT-PCR were identified. These included 88 male and 37 female patients, with a median age of 24 years old (ranging from 18 to 62). Comorbidities were identified in 25 cases (20.0%), with hypertension and diabetes mellitus being the most common (Table 1). Asymptomatic patients were only on supportive treatment. Symptomatic patients were given tablet Chloroquine 500mg BD for 5 days while patients with pneumonia were treated with Lopinavir 200mg /Ritonavir 50mg 2 tablet BD for 7 -10 days. Of the 125 subjects who were asymptomatic at admission, surprisingly, 116 (92.8%) remained asymptomatic throughout the entire admission period. There were only 9 subjects (7.2%) who developed mild symptoms. Cough (33%) was the most common symptom followed by diarrhea (22%). The interval between last contact with positive COVID-19 patients and symptoms onset was 6-14 days. On admission, all asymptomatic patients underwent a routine chest radiograph, which showed pneumonia in 7 asymptomatic subjects. Notably, none of them required oxygen therapy during admission. Twenty-two subjects (17.6%) were found to have mild liver impairment, with alanine aminotransferase (ALT) or aspartate aminotransferase (AST) levels less than 5 times the normal upper limit. None of these individuals developed acute liver failure. There were no cardiac or renal complications in any of the asymptomatic subjects, and none of them required inotropic support or hemodialysis. The majority (92%) of asymptomatic patients exhibited a normal lymphocyte count, with only 8% developing lymphopenia. In addition, 11% had CRP elevated to more than 8mg/L, with the highest CRP level being 31 mg/L. All patients recovered and were discharged from home without requiring oxygen therapy or intensive care. Of the 247 COVID-19 patients who were admitted to HTAA, 89 patients were excluded from analysis for the reasons explained in the methods section. Overall, 388 close contacts were screen after exposure to 71 asymptomatic patients, and 15 secondary cases of COVID-19 infection were detected, with an attack rate of 3.9% (Table 2). Among these 15 secondary cases, 12 were household contacts and another 3 were friends of asymptomatic patients. Notably, the attack rate of pneumonia patients is 25.7%, which is eight times higher compared with asymptomatic patients. The attack rate of pneumonia patient is statistically significantly higher compared to symptomatic or asymptomatic patients (p<0.001). Discussion Our study confirms that asymptomatic adults with COVID-19 have an excellent clinical outcome. None of them required oxygen care, ICU admission or developed organ failure. Among our asymptomatic patients, only 5.6% had abnormal chest radiographs. In comparison with a study performed in Shenzen, China, looking at 55 asymptomatic patients who were admitted to hospital, reported higher incidence (67%) of pneumonia changes on computerized tomography (CT) scan of the thorax . This may due to different modalities used for imaging, as CT scans are more sensitive than chest radiographs to detect pneumonia changes. In their study, two patients older than 60 years with comorbidities developed hypoxia requiring oxygen therapy, but none required intensive care and they were discharged well . In our study, there were three patients older than 60 years with comorbidities, none of which required oxygen therapy. More data are needed on the clinical outcome of asymptomatic patients with co-morbidities, especially in the elderly. Our study confirms that asymptomatic patients can transmit the disease to others, even though the risk of transmission is lower compared to that seen in symptomatic patients as well as in patients with pneumonia. This is consistent with another four case series that reported asymptomatic transmission in China and Germany . In addition, there are a few virological studies that suggest the transmission of COVID-19 from asymptomatic or pre-symptomatic patients . Le et al. reported viral shedding in an asymptomatic patient . However, a positive PCR result reflects only the detection of viral RNA and does not necessarily indicate presence of viable virus . The presence of viable virus is proven by Hoehl et al , who managed to isolate a positive culture of SARS-CoV-2 virus from two asymptomatic patients. Both epidemiological and virological reports further support the risk of transmission during the asymptomatic period and more importantly, among patients who are totally asymptomatic, as shown in our study. This study has several implications for public health disease control measures. One of the most important findings of the current study is that asymptomatic COVID-19 patients contribute to half of the cases in Pahang, and all of them were identified through contact screening. This highlights the fact that comprehensive contact tracing from local health authorities and strict isolation is important to prevent silent transmission from asymptomatic individuals to others. In Malaysia, all COVID-19 confirmed patients are routinely hospitalized, regardless whether they are symptomatic or not. Our study confirmed that asymptomatic COVID-19 patients had an excellent clinical outcome. Therefore, they may not need to be admitted to hospital, especially to a tertiary care hospital. Furthermore, admitting all asymptomatic COVID-19 individuals could expose healthcare workers to the risk of a potential nosocomial outbreak. Since asymptomatic COVID-19 individuals are infectious, they need to be isolated, either at home or in designated dormitory care, but with immediate access to a hospital if patients develop worsening symptoms. Home isolation may raise compliance issues. The strategy of not admitting them to tertiary care hospitals is to prevent overwhelming healthcare facilities, as this may compromise the care of non-COVID-19 patients. We have a relatively large cohort of asymptomatic COVID-19 patients which shows good clinical outcomes. However, larger-scale multicenter studies are needed to verify our findings. Secondly, there is still the possibility of missing carriers when screening contacts using pharyngeal swab specimens. We found that most of the close contacts who were infected by asymptomatic patients were household contacts, where it is quite difficult to avoid transmission. However, a few transmission cases were from friends of patients, so it is important to get details of possible modes of transmission between friends. Studies should investigate whether wearing a mask, physical distancing or hand washing can reduce the risk of transmission. Conclusions In conclusion, asymptomatic COVID-19 patients have excellent clinical outcomes and a lower transmission risk compared to the symptomatic or pneumonia groups. However, the existence of transmission from asymptomatic individuals raises the alarm of prompt public health measures such as comprehensive contact tracing and strict isolation to prevent further spread of the disease.
/** * Generates Banners with a specific pattern in chunks with coordinates divisible by 16. Only generates in dimensions that return true from {@link WorldProvider#isSurfaceWorld}. * <p> * Test for this thread: * http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-mods/modification-development/2535868-banner-nbt-tags * * @author Choonster */ public class WorldGenBanner implements IWorldGenerator { private final ItemStack bannerStack = createBannerStack(); /** * Create the Banner ItemStack used as a template for the generated banners. * * @return A Banner ItemStack with the appropriate NBT data */ protected ItemStack createBannerStack() { final ItemStack bannerStack = new ItemStack(Items.BANNER); final NBTTagCompound bannerData = bannerStack.getOrCreateSubCompound("BlockEntityTag"); final NBTTagList patternsList = new NBTTagList(); bannerData.setTag("Patterns", patternsList); patternsList.appendTag(createPatternTag(BannerPattern.GRADIENT_UP, EnumDyeColor.MAGENTA)); patternsList.appendTag(createPatternTag(BannerPattern.FLOWER, EnumDyeColor.BLACK)); bannerData.setInteger("Base", EnumDyeColor.PINK.getDyeDamage()); return bannerStack; } /** * Create a compound tag for the specified pattern and colour. * * @param pattern The pattern * @param color The colour * @return The compound tag */ protected NBTTagCompound createPatternTag(final BannerPattern pattern, final EnumDyeColor color) { final NBTTagCompound tag = new NBTTagCompound(); tag.setString("Pattern", pattern.getHashname()); tag.setInteger("Color", color.getDyeDamage()); return tag; } /** * Generate a Banner on top of the topmost block at the specified x and z position * * @param world The world * @param pos The position */ private void generateBanner(final World world, final BlockPos pos) { final BlockPos newPos = world.getTopSolidOrLiquidBlock(pos); world.setBlockState(newPos, Blocks.STANDING_BANNER.getDefaultState()); final TileEntity tileEntity = world.getTileEntity(newPos); if (tileEntity instanceof TileEntityBanner) { ((TileEntityBanner) tileEntity).setItemValues(bannerStack, true); // Read the base colour from NBT rather than metadata } } @Override public void generate(final Random random, final int chunkX, final int chunkZ, final World world, final IChunkGenerator chunkGenerator, final IChunkProvider chunkProvider) { if (world.provider.isSurfaceWorld() && chunkX % 16 == 0 && chunkZ % 16 == 0) { final BlockPos basePos = new BlockPos(chunkX * 16, 0, chunkZ * 16); generateBanner(world, basePos); } } }
#include "builtin/channel.hpp" #include "builtin/list.hpp" #include "builtin/thread.hpp" using namespace rubinius; class TestThread : public CxxTest::TestSuite { public: VM *state; void setUp() { state = new VM(); } void tearDown() { delete state; } void test_current() { Object* current_thread = state->globals.current_thread.get(); TS_ASSERT_EQUALS(Thread::current(state), current_thread); } void test_create() { Thread* thr = Thread::create(state); TS_ASSERT_EQUALS(2, thr->priority()->to_native()); TS_ASSERT_DIFFERS(thr, Thread::current(state)); } void test_exited() { Thread* cur = Thread::current(state); Thread* thr = Thread::create(state); Thread* thr2 = Thread::create(state); thr->wakeup(state); thr2->wakeup(state); state->queue_thread(thr); state->activate_thread(thr2); TS_ASSERT_EQUALS(thr2, Thread::current(state)); TS_ASSERT_EQUALS(Qtrue, thr2->alive()); TS_ASSERT_EQUALS(Qtrue, thr->alive()); TS_ASSERT_EQUALS(Qfalse, thr->sleep()); TS_ASSERT_EQUALS(Qtrue, thr->queued()); thr->exited(state); TS_ASSERT_EQUALS(thr2, Thread::current(state)); TS_ASSERT_EQUALS(Qfalse, thr->alive()); TS_ASSERT_EQUALS(Qfalse, thr->queued()); thr2->exited(state); TS_ASSERT_EQUALS(cur, Thread::current(state)); TS_ASSERT_EQUALS(Qfalse, thr->alive()); TS_ASSERT_EQUALS(Qfalse, thr->queued()); } void test_exited_cancels_channel_wait() { Message fake_message(state); Thread* current = Thread::current(state); Channel* channel = Channel::create(state); /* Avoid deadlock-ish */ state->queue_thread(Thread::create(state)); (void) channel->receive_prim(state, NULL, current->task(), fake_message); List* list = as<List>(channel->waiting()); TS_ASSERT_EQUALS(current, as<Thread>(list->locate(state, 0))); current->exited(state); TS_ASSERT_EQUALS(0LL, list->count()->to_long_long()); } void test_pass() { Thread* thr = Thread::create(state); thr->wakeup(state); Object* obj = thr->pass(state); TS_ASSERT_EQUALS(Qnil, obj); TS_ASSERT_EQUALS(thr, Thread::current(state)); } void test_wakeup() { Thread* thr = Thread::create(state); thr->sleep(state, Qtrue); Thread* thr2 = thr->wakeup(state); TS_ASSERT_EQUALS(thr, thr2); TS_ASSERT_EQUALS(thr->sleep(), Qfalse); TS_ASSERT_EQUALS(thr->queued(), Qtrue); } void test_wakeup_cancels_channel_wait() { Message fake_message(state); Thread* current = Thread::current(state); Channel* channel = Channel::create(state); /* Avoid deadlock-ish */ state->queue_thread(Thread::create(state)); (void) channel->receive_prim(state, NULL, current->task(), fake_message); List* list = as<List>(channel->waiting()); TS_ASSERT_EQUALS(current, as<Thread>(list->locate(state, 0))); current->wakeup(state); TS_ASSERT_EQUALS(0LL, list->count()->to_long_long()); } void test_raise_dead() { Thread* thr = Thread::create(state); thr->alive(state, Qfalse); TS_ASSERT_EQUALS(reinterpret_cast<Object*>(kPrimitiveFailed), reinterpret_cast<Object*>(thr->wakeup(state))); } void test_enlarge_for_priority() { std::size_t current_max = state->globals.scheduled_threads->num_fields(); Thread* thread = Thread::create(state); TS_ASSERT_EQUALS(state->globals.scheduled_threads->num_fields(), current_max); thread->priority(state, Fixnum::from(current_max)); TS_ASSERT_EQUALS(state->globals.scheduled_threads->num_fields(), (current_max + 1)); thread->priority(state, Fixnum::from(1)); TS_ASSERT_EQUALS(state->globals.scheduled_threads->num_fields(), (current_max + 1)); thread->priority(state, Fixnum::from(current_max + 10)); TS_ASSERT_EQUALS(state->globals.scheduled_threads->num_fields(), (current_max + 11)); } };
/** * ServiceConnection to process when we bind to our service */ private final class MyServiceConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder binder) { mqttService = ((MqttServiceBinder) binder).getService(); bindedService = true; // now that we have the service available, we can actually // connect... doConnect(); } @Override public void onServiceDisconnected(ComponentName name) { mqttService = null; } }
package com.android.betterway.myview; import android.animation.ObjectAnimator; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import com.android.betterway.other.ButtonSwith; import com.android.betterway.utils.LogUtil; import org.greenrobot.eventbus.EventBus; /** * @author Jackdow * @version 1.0 * 实现一个FloatingActionButton的容器 */ public class FloatingActionButtonMenu extends ViewGroup { private static final int SHOW = 1; //子控件可见时的状态 private static final int HIDE = 2; //子控件不可见时的状态 private static int state = HIDE; //保存状态,默认不可见 private final float rotation = 45f; //点击时旋转角度 private final long duration = 450; //动画事件间隔 private final long otherDuration = 500; //其他动画的间隔 private static final float SCALING = 1.2f; //拉伸比 private static final String TAG = "FloatingButtonMenu"; //打印事件的标签 public FloatingActionButtonMenu(Context context) { super(context); LogUtil.v(TAG, "constructor"); } public FloatingActionButtonMenu(Context context, AttributeSet attrs) { super(context, attrs); LogUtil.v(TAG, "constructor"); } public FloatingActionButtonMenu(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LogUtil.v(TAG, "constructor"); } /** * 实现自带的margin属性 * @param attrs 实现测量margin的接口 * @return 返回测量margin的类 */ @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { LogUtil.d(TAG, "return MarginLayoutParams"); return new MarginLayoutParams(getContext(), attrs); } /** * 测量最终容器的大小 * @param widthMeasureSpec 测量宽度所需 * @param heightMeasureSpec 测量高度所需 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { LogUtil.v(TAG, "onMeasure"); // 获得此ViewGroup上级容器为其推荐的宽和高,以及计算模式 // 所得既为设置match_parent时的大小 int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); int sizeHeight = MeasureSpec.getSize(heightMeasureSpec); // 计算出所有的childView的宽和高 measureChildren(widthMeasureSpec, heightMeasureSpec); // 记录如果是wrap_content是设置的宽和高 int childCount = getChildCount(); MarginLayoutParams layoutParams; //宽为各个子View的最大值,高为总和 int width = 0, height = 0; for (int i = 0; i < childCount; i++) { View childView = getChildAt(i); layoutParams = (MarginLayoutParams) childView.getLayoutParams(); int cWidth = childView.getMeasuredWidth() + layoutParams.rightMargin + layoutParams.leftMargin; int cHeight = childView.getMeasuredHeight(); if (cWidth > width) { width = cWidth; } height += cHeight + layoutParams.bottomMargin + layoutParams.topMargin; } // 若为match_parent则将宽高设置为上级推荐的大小 //否则则设置为计算出的大小,即为wrap_parent setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? sizeWidth : width, (heightMode == MeasureSpec.EXACTLY) ? sizeHeight : height); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { LogUtil.v(TAG, "onLayout"); int cCount = getChildCount(); MarginLayoutParams layoutParams; //遍历所有childView根据其宽和高,指定相应位置 int height = 0; for (int i = 0; i < cCount; i++) { View childView = getChildAt(i); layoutParams = (MarginLayoutParams) childView.getLayoutParams(); int cl = layoutParams.leftMargin; int cr = cl + childView.getMeasuredWidth(); int ct = layoutParams.topMargin + height; int cb = ct + childView.getMeasuredHeight(); childView.layout(cl, ct, cr, cb); height += childView.getMeasuredHeight() + layoutParams.bottomMargin; if (i != cCount - 1) { childView.setAlpha(0f); childView.setClickable(false); } } state = HIDE; setClick(getChildAt(cCount - 1)); } /**设置按钮的点击监听 * @param view 指定监听事件 */ private void setClick(final View view) { LogUtil.d(TAG, "setClick"); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (state == HIDE) { sendMessage(ButtonSwith.OPEN); showOtherView(view); } else { sendMessage(ButtonSwith.CLOSE); hideOtherView(view); } } }); } /** * 发送开关闭合的消息 * @param buttonSwith 开关状态 */ private void sendMessage(ButtonSwith buttonSwith) { EventBus.getDefault().post(buttonSwith); } /** * 显示其他的child view * @param view 按钮 */ private void showOtherView(View view) { LogUtil.d(TAG, "show other views"); //当状态为不可见时,点击按钮弹出所有隐藏view ObjectAnimator animator = ObjectAnimator.ofFloat(view, "rotation", 0f, rotation); animator.setDuration(duration); animator.start(); for (int i = 0; i < getChildCount() - 1; i++) { View childView = getChildAt(i); //简单属性动画 ObjectAnimator childAnimator = ObjectAnimator .ofFloat(childView, "alpha", 0f, 1f); ObjectAnimator otherAnimator = ObjectAnimator .ofFloat(childView, "scaleX", 1.0f, SCALING, 1.0f); otherAnimator.setDuration(otherDuration); childAnimator.setDuration(otherDuration); otherAnimator.start(); childAnimator.start(); childView.setClickable(true); state = SHOW; } } /** * 隐藏其他child view * @param view 按钮 */ private void hideOtherView(View view) { LogUtil.d(TAG, "hide other views"); //当状态为可见时,点击按钮隐藏所有view ObjectAnimator animator = ObjectAnimator.ofFloat(view, "rotation", rotation, 0f); animator.setDuration(duration); animator.start(); for (int i = 0; i < getChildCount() - 1; i++) { View childView = getChildAt(i); ObjectAnimator childAnimator = ObjectAnimator.ofFloat(childView, "alpha", 1f, 0f); childAnimator.setDuration(otherDuration); childAnimator.start(); childView.setClickable(false); state = HIDE; } } /** * 提供外部调用的函数,关闭菜单 */ public void closeMenu() { hideOtherView(getChildAt(getChildCount() - 1)); LogUtil.v(TAG, "closeMenu"); } }
<reponame>mageshwaranr/dynamodb-dal package com.tteky.dynamodb.processor; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import lombok.extern.slf4j.Slf4j; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import javax.lang.model.element.Modifier; import javax.lang.model.util.Types; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import static java.lang.String.format; @Slf4j public class MapperMethodGenerationTemplates { // private Map<String, MethodSpec> templates = new HashMap<>(); private Map<String, Map.Entry<String, String>> supportedScalars = new HashMap<>(); public MapperMethodGenerationTemplates() { this.initialize(); } public void initialize() { // templates.put("float", typeToScalar(TypeName.FLOAT)); // templates.put("int", typeToScalar(TypeName.INT)); // templates.put("double", typeToScalar(TypeName.DOUBLE)); // templates.put("long", typeToScalar(TypeName.LONG)); // templates.put("char", typeToScalar(TypeName.CHAR)); // templates.put("byte", typeToScalar(TypeName.BYTE)); // templates.put("short", typeToScalar(TypeName.SHORT)); // templates.put(Float.class.getCanonicalName(), typeToScalar(TypeName.FLOAT)); // templates.put(Integer.class.getCanonicalName(), typeToScalar(TypeName.INT)); // templates.put(Double.class.getCanonicalName(), typeToScalar(TypeName.DOUBLE)); // templates.put(Long.class.getCanonicalName(), typeToScalar(TypeName.LONG)); // templates.put(Character.class.getCanonicalName(), typeToScalar(TypeName.CHAR.box())); // templates.put(Byte.class.getCanonicalName(), typeToScalar(TypeName.BYTE)); // templates.put(Short.class.getCanonicalName(), typeToScalar(TypeName.SHORT)); supportedScalars.put("byte", Map.entry("byteToAttr", "toByte")); supportedScalars.put("Byte", Map.entry("byteToAttr", "toByte")); supportedScalars.put("short", Map.entry("shortToAttr", "toShort")); supportedScalars.put("Short", Map.entry("shortToAttr", "toShort")); supportedScalars.put("int", Map.entry("intToAttr", "toInt")); supportedScalars.put("Integer", Map.entry("intToAttr", "toInt")); supportedScalars.put("long", Map.entry("longToAttr", "toLong")); supportedScalars.put("Long", Map.entry("longToAttr", "toLong")); supportedScalars.put("double", Map.entry("doubleToAttr", "toDouble")); supportedScalars.put("Double", Map.entry("doubleToAttr", "toDouble")); supportedScalars.put("float", Map.entry("floatToAttr", "toFloat")); supportedScalars.put("Float", Map.entry("floatToAttr", "toFloat")); supportedScalars.put("char", Map.entry("charToAttr", "toChar")); supportedScalars.put("Character", Map.entry("charToAttr", "toChar")); supportedScalars.put("String", Map.entry("stringToAttr", "toString")); supportedScalars.put("Object", Map.entry("objectToAttr", "toObject")); supportedScalars.put("Enum", Map.entry("enumToAttr", "toEnum")); supportedScalars.put("Boolean", Map.entry("booleanToAttr", "toBoolean")); supportedScalars.put("boolean", Map.entry("booleanToAttr", "toBoolean")); supportedScalars.put("BigDecimal", Map.entry("bigDecimalToAttr", "toBigDecimal")); supportedScalars.put("BigInteger", Map.entry("bigIntegerToAttr", "toBigInteger")); supportedScalars.put("Date", Map.entry("dateToAttr", "toDate")); supportedScalars.put("Instance", Map.entry("instantToAttr", "toInstant")); supportedScalars.put("Calendar", Map.entry("calendarToAttr", "toCalendar")); } Collection<MethodSpec> generateTypeConversionMethods(CodeGenerationContext context) { Set<MethodSpec> specs = new HashSet<>(); context.getDynamoFields().forEach((className, annotatedFields) -> { MethodSpec.Builder fromAttributes = MethodSpec.methodBuilder(attrToEntityMethodName(className)) .addModifiers(Modifier.PUBLIC) .addParameter(ParameterizedTypeName.get(Map.class, String.class, AttributeValue.class), "attributes") .addStatement("$T entity = new $T()", className, className)// create new entity .returns(className); MethodSpec.Builder toAttributes = MethodSpec.methodBuilder(entityToAttrMethodName(className)) .addModifiers(Modifier.PUBLIC) .addParameter(className, "entity") .addStatement("$T<String, $T> fields = new $T<>()", Map.class, AttributeValue.class, HashMap.class) // create new attributes values map .returns(ParameterizedTypeName.get(Map.class, String.class, AttributeValue.class)); annotatedFields.forEach(annotatedField -> { log.info(" Processing Field Name: {}; Simple Field Type: {} ; AnnotatedFieldInfo: {}", annotatedField.getCasedFieldName(), annotatedField.getSimpleFieldType(), annotatedField); if (isScalar(annotatedField.getSimpleFieldType())) { var entry = supportedScalars.get(annotatedField.getSimpleFieldType()); fromAttributes.addStatement("entity.set$L(super.$L(attributes,$S))", annotatedField.getCasedFieldName(), entry.getValue(), annotatedField.getElementName()); toAttributes.addStatement("fields.put($S,$L)", annotatedField.getElementName(), String.format("super.%s(entity.get%s())", entry.getKey(), annotatedField.getCasedFieldName())); } else { TypeName typeName = ClassName.get(annotatedField.getElementType()); String name = typeName.toString(); if (typeName instanceof ParameterizedTypeName) { name = ((ParameterizedTypeName) typeName).rawType.toString(); } try { Class<?> type = Class.forName(name); if (Collection.class.isAssignableFrom(type)) { // handle collection Map.Entry<String,String> itemMapperMethodName = supportedScalars.get("Object") ; if(annotatedField.isFieldParameterized() ) { TypeName itemParameterType = annotatedField.fieldParameterInfo().get(0); itemMapperMethodName = mapperMethodFor(itemParameterType); } // handle toAttributes part String conditionStmt = String.format("if(entity.get%s() != null) \n \t",annotatedField.getCasedFieldName()); String collectionTemplate = "super.listAttrToAttr(entity.get%s().stream().map(this::%s).map(this::mapAttrToAttr).collect($T.toList()))"; String stmt = String.format(collectionTemplate,annotatedField.getCasedFieldName(),itemMapperMethodName.getKey()); toAttributes.addStatement(conditionStmt +"fields.put($S,"+stmt + ")", annotatedField.getElementName(),Collectors.class); // handle fromAttributes part collectionTemplate = "super.toListAttr(attributes,$S).stream().map(this::attrToMapAttr).map(this::%s).collect($T.toList())"; stmt = String.format(collectionTemplate,itemMapperMethodName.getValue()); fromAttributes.addStatement("entity.set$L("+stmt+")", annotatedField.getCasedFieldName(), annotatedField.getElementName(),Collectors.class); } else if (Map.class.isAssignableFrom(type)) { // handle map if(annotatedField.isFieldParameterized() && annotatedField.fieldParameterInfo().size() == 2) { TypeName entryKeyParameterType = annotatedField.fieldParameterInfo().get(0); TypeName entryValueParameterType = annotatedField.fieldParameterInfo().get(1) ; String entryKeyType = AnnotatedField.simpleTypeOf(entryKeyParameterType); var entry = mapperMethodFor(entryValueParameterType); if(String.class.getSimpleName().equals(entryKeyType)) { // handle toAttributes part String stmt; String simpleValueType = AnnotatedField.simpleTypeOf(entryValueParameterType); if(isScalar(simpleValueType)) { stmt = String.format("super.mapOfObjToAttr(entity.get%s(),this::%s)",annotatedField.getCasedFieldName(),entry.getKey()); // stmt= String.format("super.mapAttrToAttr(super.mapOfObjToMapOfAttr(entity.get%s(),this::%s))",annotatedField.getCasedFieldName(),entry.getKey()); toAttributes.addStatement("fields.put($S,"+stmt + ")", annotatedField.getElementName()); stmt = String.format("super.toMap(attributes,$S, this::%s)",entry.getValue()); fromAttributes.addStatement("entity.set$L("+stmt + ")", annotatedField.getCasedFieldName(),annotatedField.getElementName()); } else { // Function<Info, Map<String,AttributeValue>> infoToAttributes = this::infoToAttributes; // Function<Info, AttributeValue> infoVFunction = infoToAttributes.andThen(this::mapAttrToAttr); toAttributes.addStatement("$T<$L,Map<String,AttributeValue>> $L = this::$L",Function.class,simpleValueType,entry.getKey(),entry.getKey()); //%s.andThen(this::mapAttrToAttr); stmt= String.format("super.mapAttrToAttr(super.mapOfObjToMapOfAttr(entity.get%s(), %s.andThen(this::mapAttrToAttr)))",annotatedField.getCasedFieldName(),entry.getKey()); toAttributes.addStatement("fields.put($S,"+stmt + ")", annotatedField.getElementName()); stmt = String.format("super.toMap(attributes,$S, this.attrToMapOfAttr().andThen(this::%s))",entry.getValue()); fromAttributes.addStatement("entity.set$L("+stmt + ")", annotatedField.getCasedFieldName(),annotatedField.getElementName()); } } else { context.addWarning(format("Unable to handle field `%s` in class `%s`. Map key should be string.", annotatedField.getElementName(), className)); } } } else { context.addWarning(format("Unable to handle field `%s` in class `%s`", annotatedField.getElementName(), className)); } } catch (ClassNotFoundException e) { throw new RuntimeException("unable to process field " + annotatedField); } } }); fromAttributes.addStatement("return entity"); toAttributes.addStatement("return fields"); specs.add(fromAttributes.build()); specs.add(toAttributes.build()); }); return specs; } private boolean isScalar(String simpleFieldType) { return supportedScalars.containsKey(simpleFieldType); } public Map.Entry<String,String> mapperMethodFor( TypeName type) { String entryValueType = AnnotatedField.simpleTypeOf(type); Map.Entry<String, String> entry = supportedScalars.get("Object") ; if(isScalar(entryValueType)) { entry = supportedScalars.get(entryValueType); } else if(type instanceof ClassName){ ClassName itemParameterClass = (ClassName) type; entry = Map.entry(entityToAttrMethodName(itemParameterClass),attrToEntityMethodName(itemParameterClass)); } return entry; } static String attrToEntityMethodName(ClassName className) { return format("%sFromAttributes", Utils.firstAsSmall(className.simpleName())); } static String entityToAttrMethodName(ClassName className) { return format("%sToAttributes", Utils.firstAsSmall(className.simpleName())); } // private MethodSpec typeToScalar(TypeName typeName) { // String methodName = format("%sToScalarValue", typeName.toString()); // return MethodSpec.methodBuilder(methodName) // .addModifiers(Modifier.PROTECTED) // .addParameter(typeName, "val") // .returns(String.class) // .addStatement(" return $T.valueOf($L)", String.class, "val") // .build(); // } }
<reponame>clayne/DirectXShaderCompiler // RUN: %clang_cc1 -fsyntax-only -verify -ftemplate-depth 128 -ftemplate-backtrace-limit 4 %s template<int N> struct S { typedef typename S<N-1>::type type; static int f(int n = S<N-1>::f()); // \ // expected-error{{recursive template instantiation exceeded maximum depth of 128}} \ // expected-note 3 {{instantiation of default function argument}} \ // expected-note {{skipping 125 contexts in backtrace}} \ // expected-note {{use -ftemplate-depth=N to increase recursive template instantiation depth}} }; template<> struct S<0> { typedef int type; }; // Incrementally instantiate up to S<2048>. template struct S<128>; template struct S<256>; template struct S<384>; template struct S<512>; template struct S<640>; template struct S<768>; template struct S<896>; template struct S<1024>; template struct S<1152>; template struct S<1280>; template struct S<1408>; template struct S<1536>; template struct S<1664>; template struct S<1792>; template struct S<1920>; template struct S<2048>; // Check that we actually bail out when we hit the instantiation depth limit for // the default arguments. void g() { S<2048>::f(); } // expected-note {{required here}}
def before_train(self, logs=None): self.input = None self.flops = None self.params = None self.latency = None self.calc_params_each_epoch = self.trainer.config.calc_params_each_epoch self.calc_latency = self.trainer.config.calc_latency if vega.is_tf_backend(): import tensorflow as tf datasets = self.trainer.valid_input_fn() data_iter = tf.compat.v1.data.make_one_shot_iterator(datasets) input_data, _ = data_iter.get_next() self.input = input_data[:1] elif vega.is_torch_backend(): for batch in self.trainer.valid_loader: batch = self.trainer._set_device(batch) if isinstance(batch, dict): self.input = batch elif isinstance(batch, list) and isinstance(batch[0], dict): self.input = batch[:1] else: self.input = batch[0][:1] break self.update_flops_params(logs=logs)
use llvm::Builder; use llvm::Compile; use llvm::FunctionType; use llvm::PointerType; use llvm::Sub; use crate::wasm::TableInitializer; use crate::codegen::memory::generate_offset_function; use crate::codegen::ModuleCtx; use crate::codegen::runtime_stubs::*; pub fn generate_table_initialization_stub(m_ctx: &ModuleCtx, initializers: Vec<TableInitializer>) { let mut initialization_data: Vec<(&llvm::Function, Vec<u32>)> = Vec::new(); for (n, i) in initializers.into_iter().enumerate() { // We need to translate the offset expression into a usable value // So we compile a function that evaluates the expression, and use that let offset_func = generate_offset_function(m_ctx, "table", n, i.offset_expression); initialization_data.push((&*offset_func, i.function_indexes)); } let setup_function = m_ctx.llvm_module.add_function( "populate_table", FunctionType::new(<()>::get_type(m_ctx.llvm_ctx), &[]).to_super(), ); let bb = setup_function.append("entry"); let b = Builder::new(m_ctx.llvm_ctx); b.position_at_end(bb); for (offset_func, data) in initialization_data { let start_offset = b.build_call(offset_func, &[]); for (n, f_offset) in data.into_iter().enumerate() { let (llvm_f, ref wasm_f) = m_ctx.functions[f_offset as usize]; let table_offset = b.build_add(start_offset, (n as u32).compile(m_ctx.llvm_ctx)); let type_id = wasm_f.get_type_index().compile(m_ctx.llvm_ctx); let f_ptr = llvm_f.to_super(); let f_ptr_as_u8 = b.build_bit_cast(f_ptr, PointerType::new(<u8>::get_type(m_ctx.llvm_ctx))); b.build_call( get_stub_function(m_ctx, TABLE_ADD), &[table_offset, type_id, f_ptr_as_u8], ); } } b.build_ret_void(); }
<reponame>celiakwan/solana-voting use anchor_lang::prelude::*; use vote_count::cpi::accounts::UpdateVoteCount; use vote_count::program::VoteCount; use vote_count::Count; use vote_record::cpi::accounts::UpdateRecord; use vote_record::program::VoteRecord; use vote_record::Record; declare_id!("3yFnjbmi9Fhd999rLMM5hiFen2f1u4LLqTedASi66jx9"); #[program] pub mod solana_voting { use super::*; pub fn create_proposal( ctx: Context<CreateProposal>, bump: u8, description: String, ) -> ProgramResult { ctx.accounts.proposal_account.bump = bump; ctx.accounts.proposal_account.id += 1; ctx.accounts.proposal_account.description = description; Ok(()) } pub fn vote(ctx: Context<Vote>, agree: bool) -> ProgramResult { if ctx .accounts .record_account .voted_proposals .contains(&ctx.accounts.proposal_account.key()) { Err(ErrorCode::ProposalAlreadyVoted.into()) } else { let count_program = ctx.accounts.count_program.to_account_info(); let count_accounts = UpdateVoteCount { count_account: ctx.accounts.count_account.to_account_info(), authority: ctx.accounts.authority.to_account_info(), }; let count_ctx = CpiContext::new(count_program, count_accounts); vote_count::cpi::update_vote_count(count_ctx, agree)?; let record_program = ctx.accounts.record_program.to_account_info(); let record_accounts = UpdateRecord { record_account: ctx.accounts.record_account.to_account_info(), user: ctx.accounts.user.to_account_info(), }; let record_ctx = CpiContext::new(record_program, record_accounts); vote_record::cpi::update_record(record_ctx, ctx.accounts.proposal_account.key(), 10)?; Ok(()) } } } #[derive(Accounts)] #[instruction(bump: u8)] pub struct CreateProposal<'info> { #[account( init, seeds = [b"proposal".as_ref()], bump = bump, payer = authority, space = 500 )] pub proposal_account: Account<'info, Proposal>, #[account(mut)] pub authority: Signer<'info>, pub system_program: Program<'info, System>, } #[derive(Accounts)] pub struct Vote<'info> { pub proposal_account: Account<'info, Proposal>, pub count_program: Program<'info, VoteCount>, #[account(mut, has_one = authority)] pub count_account: Account<'info, Count>, pub authority: Signer<'info>, pub record_program: Program<'info, VoteRecord>, #[account(mut, has_one = user)] pub record_account: Account<'info, Record>, pub user: Signer<'info>, } #[account] #[derive(Default)] pub struct Proposal { pub bump: u8, pub id: u8, pub description: String, } #[error] pub enum ErrorCode { #[msg("Proposal has already been voted")] ProposalAlreadyVoted, }
<reponame>ElLucioVpe/uytube /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package logica.dt; /** * * @author Esteban */ public class ListaDeReproduccionDt { private int id; private String nombre; private boolean privada; private String tipo; private String categoria; private int user_id; public ListaDeReproduccionDt(){ } public ListaDeReproduccionDt(int id, String nombre, String tipo, boolean privada, String categoria, int usuario) { this.id = id; this.nombre = nombre; this.privada = privada; this.tipo = tipo; this.categoria = categoria; this.user_id = usuario; } public int getId() { return id; } public String getNombre() { return nombre; } public boolean getPrivada() { return privada; } public String getTipo() { return tipo; } public String getCategoria() { return categoria; } public int getIdUsuario() { return user_id; } }
NATAL, Brazil -- "We're fucked, dude. We're totally fucked." So said a man from Ohio upon seeing Andre Ayew find the net against Tim Howard on Monday. Four minutes later, he was in tears. So was the man next to him, from Wisconsin. And the man in front of him, from New Jersey. And the woman next to him, from Washington, D.C. John Brooks' goal sent an estimated 20,000 American fans at Arena das Dunas into frenzied ecstasy. One man went flying down three rows, fell, got up and hugged the first person in front of him. Next to him there was a dog pile, a mass hug gone wrong in the best possible way. Turn in any direction and you could see someone yelling "HOLY SHIT." Half of the audience didn't realize when Ghana kicked off again. Fans weren't even facing the field. Overcome by that one exquisite moment, the Americans in the crowd were too busy hugging, jumping, screaming and crying to notice the downcast Black Stars resume the game. ★★★ The night before the match, U.S. Soccer threw a giant party. Hundreds of people packed into a tent in the middle of Natal, eating and drinking while Argentina vs. Bosnia and Herzegovina played on the big screens. When that ended, everyone hit the bar and, before long, the dance floor. The party turned into a makeshift rave, with music blasting and the tent stuffed full of red, white and blue bodies under red and blue strobe lights. An LED globe flashed the U.S. Soccer logo over a giant sign that read "One Nation. One Team." By the time the party was shut down there wasn't a sober person in sight. And yet the next afternoon, no one looked any worse for the wear. Everyone piled into a bar a few blocks from the stadium, beers in hand. The indoor area was full, making it difficult to move. The patio wasn't any better. And outside, the crowd swelled and swelled until it took over the entire parking lot. The closest some people could get was the street, and they stayed in the street, watching, singing and drinking. One man was dressed as Teddy Roosevelt, complete with hat, glasses, mustache, beige hunting suit and boots. Another walked around in nothing but suspenders patterned in stars and stripes, while four Abraham Lincolns, a George Washington, two Elvises, a Duffman and the entire Justice League paraded around. You didn't have to look far to find a girl in an American flag bikini top or a man in U.S. board shorts with no shirt. It was a sea of red, white, blue and skin. The supporters were gathered along a main road where buses passed by every five minutes. And everyone on every bus wanted to see the party that was going on. They stuck their heads out of the windows and took pictures, and when they did the partygoers responded with chants of "U-S-A!" that were joined by the fans on the buses. One Brazilian man jumped off his bus and began jumping up and down while chanting along. By the time the chant ended, he had a beer in each hand. Somehow, a Mexico fan also made his way to the pre-game. He didn't stay long. The U.S. fans screamed at the top of their lungs, booed and chanted "dos a cero" and "forever in our debt." The Mexico fan didn't have enough time to get a drink before he was urged away and down the street. Fans from any other country were welcomed in. A man draped in an England flag bought a round and, immediately, became a fan favorite. A Costa Rican fan was met with cheers of "CON-CA-CAF!", and even though the Ghanaians were jeered, they were eventually given beers. It was a giant party. Every five minutes a new song would break out, from "I Believe," to "God Bless America," to "The Star Spangled Banner." Everyone would join in with every song. Two hours before kickoff, the party moved to the streets of Natal and the stadium, and the singing didn't stop. The mass of Americans marched to the stadium, creating a sea of red, white and blue. You could not see the end of the march from the front -- it stretched at least four, five, six blocks long. Fans from any other country were welcomed in. even though the Ghanaians were jeered, they were eventually given beers. As marchers passed apartment buildings, bystanders would come out to the balconies, wave, take pictures and clap along. Construction workers rushed down to the bottom of the tower they were building and ran into the crowd, posing with fans while their colleagues took pictures. Everyone wanted pictures with or of the Americans, and before long it looked as much like a ticker tape parade as it did a walk to a soccer match. The Americans had to split up when they got to the stadium, forced to enter through assigned gates and go to their respective sections, but as soon as they got into the seating bowl, the chants started again. An hour before game time, with half of the stadium still empty, there were American fans throughout, making the Arena das Dunas echo with chants of "U-S-A!" When Brad Guzan and Nick Rimando walked on the field for warmups, the screaming started. Minutes later, Tim Howard came out of the tunnel and the fans chanted his name. When the rest of the team came out, they clapped for the fans, who returned the love with a three-minute rendition of "I believe that we will win." There were old men and women in the stands with their faces painted. There was a grandfather with his grandson and plenty of fathers with sons. One woman brought her daughter and another brought her two sons. There was an eight-year-old with an American flag painted on his face sitting on his dad's shoulders. Any time the small corner of Ghana fans would start to sing and dance, they were quickly drowned out, and it remained that way until kickoff. The first lull of the match came 20 seconds after it got underway. The roar to start the match died down and the magnitude of the moment -- the World Cup -- set in. That lull didn't last long. When Clint Dempsey took his first touch to turn towards goal, the crowd rose. Then he cut in, leaving a defender in his wake and the crowd screamed. Seconds later, the ball hit the post, then the net, and the noise became deafening. Clint Dempsey brings USA supporters to their feet, Photo credit: Michael Steele/Getty Images Few could believe what they had seen. It took Dempsey all of 29 seconds to put the U.S. in front and score the first goal from an American forward at a World Cup since 2002. The fans responded with cheers of "U-S-A!" It was loud. "I LOOKED AWAY. I DIDN'T SEE IT," one man yelled mid-hug. "JOGA BONITO MOTHERFUCKERS," another screamed. It seemed like a good omen for the Americans. Everyone was saying, "we need another" and "pour it on, get that goal difference up." Little did they know that the rest of the match would be a matter of survival. After 15 minutes, the feeling was that the U.S. "just needed to turn it around." By the 30-minute mark it was "please just let us get to halftime." Every few minutes, the U.S. would get possession and fans would try to get a chant started, but the team would give the ball away within seconds and kill it. By halftime, nobody believed that the U.S. would be able to hold on. People were discussing the group situation and what the U.S. would have to do in their final two matches. They had already conceded, "hopefully we draw this match." By the time Ghana scored to bring the match level, nobody was crushed. The goal felt like it was a long time coming, and with it being so late in the match, it was possible for the U.S. to hold on and nab a point. Any doom and gloom wasn't about the equalizer, but about the Ghanaian winner that was assuredly on the way. And yet Fabian Johnson went scampering down the right. The crowd rose again and faint echoes of "I believe that we will win" could be heard. Johnson earned a corner kick and the entire stadium rose to its feet. "U-S-A!" chants erupted once more, even louder than before. Noise was emanating from every corner of the stadium, a crash of sound that shook the very fabric of das Dunas. It spilled from the top deck and flooded the bottom. Even in the hospitality sections, blocked off from the rest of the crowd by glass walls, the fans stood and a few brave Americans shrugged off the ire of the nearby suits to join their compatriots in song. When Zusi stepped to the ball, everyone went quiet. Be it nervousness, uncertainty or hope, the Americans in the stands had found something that had their throats in their stomachs. There was a hush. Then the ball found its way to the middle. Brooks leapt. He headed the ball down. It hit the ground. It bounced. And somehow, it hit the back of the net. Bedlam. Mosh pits and dog piles broke out. If you could reach somebody, you hugged him or her. Everyone received kisses. The crowd was so loud it didn't sound like anything. It became a din of white noise so loud as to defy coherence. There wasn't a complete sentence to be heard. It was a mix of "OH MY GOD" and a wide array of expletives. It was absolute madness. It was, in other words, World Cup soccer. By the time the match restarted, most people had no idea who scored the goal. They didn't know where or how they had celebrated. They didn't know what minute it was. They had no idea what happened except that they were far from the seats they were in not long ago. They were hugging or being hugged and they could barely see through the tears. The elation from the goal wore off when Ghana went forward again. The Black Stars were dangerous, and despite the injection of adrenaline, few believed that the U.S. would be able to hold off their late surge. The fourth official signaled for five minutes of stoppage time and 30 seconds later fans were yelling at the referee to blow the final whistle. Every clearance was followed by wild cheers and screams. Nobody cared about beautiful soccer. They didn't care about being proactive. Fans were calling for players to dive and waste time, yelling "THEY DOVE FOR 15 MINUTES LAST WORLD CUP, DO IT TO THEM." Finally, the referee blew for full time, which proved to be a good moment to relive the experience of Brooks' goal. Hugs, kisses, tears and people tumbling down rows of seats. The players made their way to the ends and sides of the stadium, applauding for their fans. The fans returned their appreciation with chants of "U-S-A!" The local Brazilians joined the cheers. American fans gave the locals U.S. scarves and shirts on the way out. They all wanted pictures with their new Brazilian friends. The stadium emptied out, but a few thousand Americans stayed. They kept chanting, even as everyone left. The stadium echoed even with the voices of just a few American stragglers. They took pictures and savored the moment. Twenty minutes after the match was over, there was just a handful of fans left, including one woman who was still sitting in her seat, staring at the pitch as the grounds crew went to work on repairing the pitch. She then got up, tears in her eyes and as she walked out, she said just three words. "Oh my god."
Detection versus Estimation in Event-Related fMRI: Choosing the Optimal Stimulus Timing With the advent of event-related paradigms in functional MRI, there has been interest in finding the optimal stimulus timing, especially when the interstimulus interval is varied during the imaging run. Previous works have proposed stimulus timings to optimize either the estimation of the impulse response function (IRF) or the detection of signal changes. The purpose of this paper is to clarify that estimation and detection are fundamentally different goals and to determine the optimal stimulus timing and distribution with respect to both the accuracy of estimating the IRF and the power of detection assuming a particular hemodynamic model. Simulated stimulus distributions are varied systematically, from traditional blocked designs to rapidly varying event related designs. These simulations indicate that estimation of the hemodynamic impulse response function is optimized when stimuli are frequently alternated between task and control states, with shorter interstimulus intervals and stimulus durations, whereas the detection of activated areas is optimized by blocked designs. The stimulus timing for a given experiment should therefore be generated with the required detectability and estimation accuracy.
/** * An instance of this class provides access to all the operations defined in * CertificateRegistrationProviders. */ public final class CertificateRegistrationProvidersInner { /** * The proxy service used to perform REST calls. */ private CertificateRegistrationProvidersService service; /** * The service client containing this operation class. */ private WebSiteManagementClientImpl client; /** * Initializes an instance of CertificateRegistrationProvidersInner. * * @param client the instance of the service client containing this operation class. */ public CertificateRegistrationProvidersInner(WebSiteManagementClientImpl client) { this.service = RestProxy.create(CertificateRegistrationProvidersService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for * WebSiteManagementClientCertificateRegistrationProviders to be used by * the proxy service to perform REST calls. */ @Host("{$host}") @ServiceInterface(name = "WebSiteManagementClientCertificateRegistrationProviders") private interface CertificateRegistrationProvidersService { @Get("/providers/Microsoft.CertificateRegistration/operations") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(DefaultErrorResponseException.class) Mono<SimpleResponse<CsmOperationCollectionInner>> listOperations(@HostParam("$host") String host, @QueryParam("api-version") String apiVersion); @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(DefaultErrorResponseException.class) Mono<SimpleResponse<CsmOperationCollectionInner>> listOperationsNext(@PathParam(value = "nextLink", encoded = true) String nextLink); } /** * Description for Implements Csm operations Api to exposes the list of available Csm Apis under the resource provider. * * @throws DefaultErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PagedResponse<CsmOperationDescriptionInner>> listOperationsSinglePageAsync() { return service.listOperations(this.client.getHost(), this.client.getApiVersion()).map(res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Description for Implements Csm operations Api to exposes the list of available Csm Apis under the resource provider. * * @throws DefaultErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<CsmOperationDescriptionInner> listOperationsAsync() { return new PagedFlux<>( () -> listOperationsSinglePageAsync(), nextLink -> listOperationsNextSinglePageAsync(nextLink)); } /** * Description for Implements Csm operations Api to exposes the list of available Csm Apis under the resource provider. * * @throws DefaultErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<CsmOperationDescriptionInner> listOperations() { return new PagedIterable<>(listOperationsAsync()); } /** * Get the next page of items. * * @param nextLink null * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws DefaultErrorResponseException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<PagedResponse<CsmOperationDescriptionInner>> listOperationsNextSinglePageAsync(String nextLink) { return service.listOperationsNext(nextLink).map(res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } }
Identification of CD4+ T-cell-derived CD161+ CD39+ and CD39+CD73+ microparticles as new biomarkers for rheumatoid arthritis. AIM This study aimed to identify CD4+ T-cell-derived microparticles (MPs) and investigate their roles in rheumatoid arthritis (RA). METHODS Synovial fluids from 34 RA, 33 osteoarthritis patients and 42 healthy individuals were analyzed by flow cytometry. Human fibroblast-like synoviocytes and peripheral blood mononuclear cells were cultured with or without isolated MPs, chemokines and cytokines were measured by ELISA. RESULTS CD4+CD161+CD39+ and CD4+CD39+CD73+ MPs were abundantly present in RA patients, which were positively or negatively correlated with RA features, respectively. Chemokines CCL20, CCL17 and CCL22, and cytokines IL-17 and IL-10 were influenced by these MPs in human fibroblast-like synoviocytes (HFLS) or PMBCs. CONCLUSION CD4+ T-cell-derived CD161+CD39+ and CD39+CD73+ MPs could serve as new reciprocal biomarkers for RA evaluation.