text
stringlengths 1
1.04M
| language
stringclasses 25
values |
|---|---|
Read 2 times. Last read October 17, 2023.
This wonderful and unique story of a couple held my attention. At one level, this is the story of a relationship and marriage. The reader meets Jack and Elizabeth when they have each moved to an “artsy” neighborhood in Chicago. We watch as their relationship grows and as they marry and have a son. Jack is an artist and professor, while Elizabeth is a social scientist and runs a company called “Wellness”. The novel goes very deeply into their emotional lives, which, of course, are complicated and highly affected by their childhoods. We learn that Jack and Elizabeth grew up in emotionally challenging (to say the least) households, however, Jack grew up on the Kansas prairie while Elizabeth grew up with ill-begotten wealth in New England. We watch their resulting adult angst in detail. However, this novel is more than just a story about two rather damaged people (aren’t we all?!) in a relationship. It is also a well-researched tome about many aspects of our society. Hill explains about the effect of Facebook algorithms; we watch as Jack follows a trendy whole-life fitness program; we get a detailed understanding of the real estate market and the Kansas prairie; we learn about this origination of sweet condensed milk; and there are many other fascinating fact/stories. I felt that the most important one was Wellness itself (Elizabeth’s company). The entire business is based upon the effect of placebos and how many people mentally programmed to make them work – i.e. believe that they work. Of course, when the “patients” discover the truth, things go awry. I thoroughly enjoyed this novel which was not only a well done tale of a relationship, but also a textbook and commentary on a number of facets of our modern lives.
Showing 1-5 of 5 (5 new)
A fabulous review, Ann. An interesting premise for a story too. Given the hot market for wellness now.
message 3: by Melissa (new)
Fantastic review, Ann. I don't often enjoy contemporary stories, which is why I've shied away from this one (though I did begin Hill's THE NIX -- and found it very well-written and interesting; I'm not sure why I didn't finish it)... I wonder if I need to give this one a shot. We certainly are destroying ourselves with social media -- so reliant on trends and algorithms that influence many of our daily decisions -Seems as though this book points that out in detail.
Ann--you got to the grit of the novel in your review! Yes, damaged people, for sure (they seem to be more damaged than your average bear) And, yes, it is absolutely a commentary on modern lives!
I just got this one out so hope to get to it over the holidays. Great review, Ann. And if you rated this one a 5 then it's bound to be good!
|
english
|
<gh_stars>0
{
"name": "wp-api-angular",
"version": "3.0.0-beta8",
"description": "WordPress WP-API v2 client for Angular2",
"main": "wp-api-angular.js",
"typings": "wp-api-angular.d.ts",
"scripts": {
"ng": "ng",
"start": "ng serve",
"prebuild": "rm -rf dist",
"build": "ng build",
"postbuild": "cp package.json README.md dist/",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"commit": "git-cz",
"publish": "npm run build && npm publish dist",
"dumpdev": "ENV=dev webpack --progress --colors --config webpack.config.dist.js -d",
"dumpprod": "ENV=prod webpack --progress --colors --config webpack.config.dist.js -p",
"changelog": "node_modules/.bin/conventional-changelog -p angular -i CHANGELOG.md -s -r 0 && git add CHANGELOG.md && git commit -m 'docs(changelog): add new log'"
},
"repository": {
"type": "git",
"url": "https://github.com/ptesser/wp-api-angular"
},
"keywords": [
"wp-api",
"angular",
"angularjs",
"rest",
"restfull",
"client"
],
"author": "ptesser <<EMAIL>>",
"license": "MIT",
"bugs": {
"url": "https://github.com/ptesser/wp-api-angular/issues"
},
"homepage": "https://github.com/ptesser/wp-api-angular",
"peerDependencies": {
"@angular/core": "^8.0.0",
"@angular/http": "^8.0.0"
},
"dependencies": {
"@angular/common": "~8.2.7",
"@angular/compiler": "~8.2.7",
"@angular/platform-browser": "~8.2.7",
"@angular/platform-browser-dynamic": "~8.2.7",
"rxjs": "~6.4.0",
"tslib": "^1.10.0",
"zone.js": "~0.9.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.803.5",
"@angular/cli": "~8.3.5",
"@angular/core": "~8.2.7",
"@angular/compiler-cli": "~8.2.7",
"@angular/language-service": "~8.2.7",
"@commitlint/cli": "^8.0.0",
"@commitlint/config-conventional": "^8.0.0",
"@types/jasmine": "~3.3.8",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "^5.0.0",
"commitizen": "^3.1.1",
"conventional-changelog-cli": "^2.0.23",
"cz-conventional-changelog": "^2.1.0",
"husky": "^2.5.0",
"jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.15.0",
"typescript": "~3.5.3"
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"husky": {
"hooks": {
"commit-msg": "commitlint --edit"
}
}
}
|
json
|
Actor Priyanka Chopra received huge appreciation from her father-in-law Paul Kevin Jonas Sr for her performance in The White Tiger. Sharing a poster on Instagram, Paul Kevin Jonas wrote, “Everyone go see this powerful movie starring our wonderful daughter-in-law @priyankachopra (sic)” Priyanka replied to the post with heart-eyed emoji in the comments section.
The White Tiger, based on the Booker Prize-winning novel of the same name written by Aravind Adiga, stars Priyanka, Rajkummar Rao and newcomer Adarsh Gourav. Priyanka plays an American-Indian, Pinky, and Rajkummar plays her husband.
- Adarsh’s character is called Balram Halwai. It’s based on India’s class struggle and follows the rags-to-riches story of Balram, a poor driver who uses his wit and cunning to break free from servitude to his rich masters and rise to the top of the heap to become a successful entrepreneur. Priyanka has also produced the movie that released on streaming giant Netflix globally a few days ago.
A few days, Priyanka has received a huge shout-out from husband, Nick Jonas, Praising the movie, he posted a long message on his social media accounts. He wrote, “The White Tiger is out now on @netflix! ! ! So incredibly proud of my wife @priyankachopra for her work as both an actor and a producer on this movie. Everyone do yourself a favour and go watch this movie right now! Congrats to the entire cast and crew and creative team. (sic)”.
Priyanka, too, took to Instagram to express gratitude. The actor mentioned in a post: “Ending opening weekend with a full heart. I’m blown away by the love for #TheWhiteTiger’s release on @netflix this weekend. Your support in watching this film has made it trend globally in the top 10 in less than 48 hours + counting. Thank you to every one of you who watched, posted, shared amazing reviews, and held space for this incredible cast & crew. (sic)”.
A recent review in The Guardian praised the “class parable”, stating that it was “one of the more successful literary adaptations of recent years”.
|
english
|
1 Jɨm Cesarea anajty tüg tungmɨɨdpɨ huɨdi anajty yxɨɨ Cornelio, hue' je' anajty capitán'ajtp ma tüg batallón soldado ajcxy yxɨɨjɨp, la Italiana. 2 Je Cornelio ooy anajty ytudägyɨty, etz je' mɨɨd tüg'ócɨy y'ung ytöxyɨjc ooy anajty yajmɨj'ajtcɨxy Dios. Je Cornelio nañ jadu'n ypubety mɨɨd meeñ je judíojäy ayoobtɨjc, e je' Dios ojadajt anajty jabom jabom. 3 Tüg xɨɨ, mɨnacyxɨɨ anajty, Cornelio huin'ijxy janch huädz Dios tüg y'ángel ñigɨdaacɨ, e ñɨmaayɨ:
4 Chi Cornelio huindɨcxpejty je ángel janch tzɨgɨɨyb anajty, e chi yajtɨɨy:
―¿Ti Huindzɨn?
Huin'it je ángel y'adzooy:
―Jadu'n nej mDios'ojadaty etz jadu'n nej mbubety ayoobtɨjc tɨ Dios jäygɨdägy. 5 Quex mjäy jɨm Jope, huen nɨcxy yajtzoñ Simón, huɨdibɨ nañ jadu'n yajtijp Pedro. 6 Jɨm je' yja'ttacy ma jadügpɨ Simón, je cootzpɨ huɨdi ytɨjc mɨhuingon mejypa'. Je Pedro xyajnɨmähuɨpy ti mdunɨpy.
7 Co je ángel ñɨcxnɨ huɨdi anajty tɨ ymɨgapxyii, chi Cornelio yaaxɨ mejtz ytumbɨ, etz tüg soldado huɨdi Dios capxymɨdoob, etz huɨdibɨ je Cornelio ooy ymɨjnɨcxpedyii. 8 Chi yajmɨɨdmɨydactay nej je ángel ñɨmaayɨ, chi ajcxy quejxy jɨm Jope.
9 Com jabom jɨm anajty je quejxyöybɨ ajcxy ñɨcxy mɨhuingon Jope, cujc yxɨɨ anajty, e chi Pedro ypejty ma tɨjcnïcx Dios ojadajtp. 10-11 Ooy Pedro anajty yuubögyii, e ooy jacaya'ñ, jɨmnɨ anajty yjɨɨcxy yaj'oyɨ̈yii. Chi Pedro huin'ixy je tzajp ahuädz, e huin'it ijxy quidägy jadu'n nej poob huit mɨjpɨ yxóchɨty majaty ytaatz. 12 Jiiby ma je poob huit, jiiby anajty canaagnax ɨyujc huɨdijaty mɨdaax ycɨ' ytecy etz tza'ñ etz joon. 13 Huin'it Pedro mɨdoy co anajty ñɨmäyii:
―Pedro, pɨdɨ̈g nɨcxy yaj'ög yɨ ɨyujc etz tzüdz.
14 Chi Pedro y'adzooy:
―Ca', Huindzɨn, camɨnaabɨ ɨɨch tɨ njɨcxy huɨdibɨ jɨbɨ́cɨp etz huɨdibɨ ca' ñigödúcyɨty nɨcxy judíojäy jɨɨcxcɨxy.
15 Huin'it jadüg'oc ayuc mɨdoy ñɨmäyii:
―Huɨdibɨ Dios yajhuäch ca' huaad mdijy co yɨ' yjɨbɨcɨty.
16 Tugɨɨg'oc jadu'n yjajtɨ, chi je poob huit ypättɨgɨɨyñɨ tzajpjoty. 17 Jɨm anajty Pedro tzachhuinmay nej anajty yhuimbɨdzɨmy je tɨɨbɨ ixy co yja'ty ma tɨjc aguu je Cornelio yquexyöybɨ huɨdi ajcxy anajty nidɨɨhuɨp yajtɨɨhuɨp je Simón ytɨjc. 18 Chi ajcxy mɨc ycogapxɨɨy yajtɨɨy pen jɨm anajty yjättägy Simón huɨdibɨ anajty nañ jadu'n yajtijp Pedro. 19 E je Pedro je' anajty chachhuinmaayb tɨɨbɨ ixy, chi je Espíritu Santo Pedro ñɨmaayɨ:
―Tugɨɨg yëydɨjc ji xy'ixtäy. 20 Pɨdɨ̈g e mɨnac, nɨcx mɨɨd je' ajcxy, e ca' ti mhuinmay, com ɨɨch jadu'n tɨ nnɨmäy co huen xy'ixtäy.
21 Huin'it Pedro ymɨnajcy ma je' ajcxy, je Cornelio quexyöybɨ, nɨmay ajcxy:
―Ɨɨch je' huɨdibɨ miich ajcxy m'ixtaayb, ¿ti ycɨxpɨ co tɨ mmiingɨxy?
22 Chi ajcxy y'adzooy:
―Yɨ' ɨɨch ajcxy tɨ xyquexyɨch yɨ Cornelio huɨdibɨ capitán'ajtpɨ, je' tudägy jäy huɨdibɨ Dios yajmɨj'ajtp, je huɨdibɨ tüg'ócɨy judíojäy ooy tzójccɨxy, etz cömaaygɨxy. Huindzɨn Dios tüg y'ángel ñɨmay Cornelio co miich miiñ nyajhuoy, jɨgɨx mnɨ́cxɨp ma yɨ' ytɨjc, e y'amɨdo'ida'ñ ajcxy nej miich myaj'ixpɨga'ñ.
23 Chi Pedro yajtɨjctɨgɨɨy je' ajcxy. Chi ajcxy jɨm ymaahuɨ'my. Com jabom Pedro ñɨcxy mɨɨd je' ajcxy, e chi nijëjɨty ypanɨcxɨ huɨdibɨ mɨjpɨdacp Jesús huɨdi anajty ajcxy tzɨnaayb jɨm Jope.
24 Com jabom ajcxy yja'ty jɨm Cesarea ma Cornelio anajty y'ahuixy tügmucy mɨɨd yjugymɨgüg, etz nijëjɨty pɨn ooy mɨɨd ñaymɨgüg'adyii, huɨdijaty anajty ajcxy jayɨjp tɨ nɨmäy. 25 Co Pedro oyjäty ma je tɨjc, chi Cornelio ytɨjcpɨdzɨmy oy yjɨjpcobadɨ̈y je Pedro, e chi ycoxtɨnay'ahuɨɨy yajmɨj'ada'ñ anajty je Pedro. 26 Chi Pedro huijtztɨnayɨ̈gy je Cornelio, e nɨmay:
―Tɨnayɨ̈g, ca' xyajmɨj'ida'ñɨch, nañ jadu'n ɨɨch njäyɨty nej miich.
27 Mɨɨd anajty ycapxy ymɨydägy co ytɨjctɨgɨy, jiiby anajty mayjäy ni'amugɨ̈'ahuijxcɨxy. 28 Chi Pedro nɨmay ajcxy:
―Miich ajcxy mnejhuɨɨyb co yɨ judíojäy ycostumbre capx'aducy ca' huaad judíojäy yöymucy mɨɨd huɨdibɨ ca' yjudíojäyɨty, ca' huaad ytɨgɨɨygɨxy ma ajcxy ytɨjc. Per Dios tɨ xyajni'ixɨ̈yɨch co ca' huaad nmɨna'ñɨch ca' oyjäyɨty huädzjäyɨty pɨnjaty. 29 Paady co oy tɨ xyajhuoyiijɨch tɨ nmiiñɨch, ni ca' huam tɨ nmɨna'ñɨch. Nnejhuɨ̈huaamyɨch na'amy co oy tɨ xyajhuoyiijɨch.
30 Chi Cornelio y'adzooy:
―Cham ymɨmɨdaaxxɨɨjɨ̈y, jadu'n nej jadachambɨ hora, ya ɨɨch anajty ma ndɨjcɨch, jaygay jay'ügy nDios'ojadatyɨch. Com hue' anajty mɨjmɨnacy xɨɨ mɨna judíojäy ajcxy ycapxtaaccɨxy, co tüg ñayguëxɨ̈cɨ jadu'n nej jäy mɨɨd ypoob huit janch adɨɨcxp. 31 E je ángel xyñɨmaayɨch: “Cornelio, Dios tɨ xymɨdoohuɨ m'oración e tɨ jadu'n jäygɨdägy jadu'n nej mbubety yɨ ayoobtɨjc ajcxy. 32 Quex mdumbɨ jɨm Jope, huen nɨcxy yajtzoñ Simón huɨdi nañ jadu'n yajtijp Pedro. Jɨm Pedro yja'ttägy ma je cotzpɨ ytɨjc huɨdibɨ yxɨɨ Simón, huɨdibɨ tzɨnaayb mɨhuingon mejypa'. Co je' ymiinɨpy, chi xymɨɨdmɨydägɨpy.” 33 Paady nguejxyɨch janch mɨc'amy huen nɨcxy xy'ijxtäy. E tɨ may'ajt mduñ co tɨ mmiiñ. Jadachambɨ cha ɨɨch ajcxy nidüg'ócɨy ma Dios yhuinduu. E n'amɨdo'idáangɨxyɨch tüg'ócɨy je y'ayuc huɨdibɨ je Huindzɨn Dios tɨ xyaj'ane'my jëbɨ xyajnɨmaaygɨxy.
34 Huin'it Pedro ytɨgɨɨy y'ayuccapxhuäcxpɨ, nɨmay ajcxy:
―Jadachambɨ huinjɨhuɨɨybɨch, co yɨ Dios ca' ni tüg ixy'ixy jäy, y'actzojctaayb hueñypɨ́nɨty. 35 Dios ycöbɨjcpy hueñypɨnjäyɨty huɨdibɨ tzɨnaayb huen huɨdibɨ naax huen huɨdibɨ cajpɨty, pen chɨgɨɨyb ajcxy Dios, pen tumyb oybɨ. 36 Dios tɨ quexy yɨ' ytɨy'ajt ma yɨ Israel jäy ajcxy, yajnɨmay co ji cham jotcujc'ájtɨn mɨɨd Jesucristo ɨɨch ajt nHuindzɨn. 37 Miich ajcxy mnejhuɨɨyb yajxon nej tɨ ytunyii tɨ yjadyii ma judíojäy ajcxy ñaax ycajp chondacy jɨm Galilea, Juan el Bautista tɨ anajty capxhuäcxɨ Dios y'ayuc ytɨy'ajt etz yjäyyajnɨɨbety. 38 E mnejhuɨɨyb miich ajcxy co Dios yejc je Jesús je Nazaretpɨ je Espíritu Santo, e nej Jesús yhuɨdijty e tuuñ oy'ájtɨn, etz mɨjhuinma'ñ, jadu'n nej yajtzocy je jäy ajcxy huɨdi anajty ane'm'ijtp ma yɨ mujcu'. Com Dios anajty mɨɨd y'ity je Jesús. 39 Ɨɨch ajcxy je tɨy'ajt nmɨɨdɨch tüg'ócɨy jadu'n nej Jesús yjajty y'ayoy jɨm Judea naaxjot etz jɨm Jerusalén. Huin'it ajcxy Jesús yaj'o'cy cruudzcɨ́xy. 40 E Dios yajjugypɨjcy codugɨɨg xɨɨ, e chi yajnayguëxɨ̈cɨ ma ɨɨch ajcxy. 41 Ca' tɨ yajnayguëxɨ̈gyii ma tüg'ócɨy jäy, jëyɨ ma ɨɨch ajcxy huɨdi jayɨjp Dios yhuin'ijx jɨgɨx tɨy'ajt nyegɨpyɨch. Ɨɨch ajcxy caaymujc uucmujc huin'it co yjugypɨjcy ma y'o'cy. 42 Tɨ xyquexy ɨɨch ajcxy ayuc ngapxhuäcxpɨ ma mayjäy ajcxy etz nidɨy'ajt'adɨpyɨch ajcxy co Dios Jesús tɨ pɨdägy mɨj'ane'mbɨ ma yɨ juugypɨ etz ma yɨ ögypɨ. 43 Nañ jadu'n jecy'ajty tüg'ócɨy Dios y'ayucnajtzcapxɨɨybɨ ñimɨydac ajcxy Jesús, e ymɨnañ ajcxy co tüg'ócɨy je jäy ajcxy pɨnjaty mɨbɨjc je Cristo, Dios huinmecxɨɨb ajcxy ypocy.
44 Yam anajty Pedro ycapxyñɨ co je Espíritu Santo ñïdɨgɨɨyɨ ycödɨgɨɨyɨ ajcxy nidüg'ócɨy huɨdijaty y'amɨdo'ijt Pedro y'ayuc. 45 E je judío mɨbɨjcpɨdɨjc ajcxy tɨɨbɨ anajty miiñ mɨɨd Pedro, ooy ajcxy jɨhuɨy huinmay co Dios quejx Espíritu Santo ma je jäy ajcxy huɨdibɨ ca' yjudíojäyɨty, 46 co mɨdoy ycapxcɨxy mɨɨd huingbɨ ayuc, etz cömaygɨxy jäymejtzcɨxy Dios. 47 Chi Pedro ymɨnañ:
―¿Nej ca' jada' y'óyɨty co ñɨɨbedɨpy ajcxy huɨdibɨ Dios tɨ ymóoyɨgɨxy je yEspíritu Santo jadu'n nej ɨɨch ajt xymooyɨm?
48 Chi Pedro ni'ane'mdɨɨy huen nɨɨbejtcɨxy ma Huindzɨn Jesucristo yxɨɨ. Huin'it ajcxy Pedro cohuanɨɨy huen huɨ'my tüg xɨɨ mejtz xɨɨ mɨɨd je' ajcxy.
|
english
|
use crate::constants::*;
use crate::parsed_packet::*;
use crate::rr_iterator::*;
#[derive(Debug)]
pub struct EdnsIterator<'t> {
rr_iterator: RRIterator<'t>,
}
impl<'t> DNSIterable for EdnsIterator<'t> {
#[inline]
fn offset(&self) -> Option<usize> {
self.rr_iterator.offset
}
#[inline]
fn offset_next(&self) -> usize {
self.rr_iterator.offset_next
}
fn set_offset(&mut self, offset: usize) {
debug_assert!(offset <= self.packet().len());
self.rr_iterator.offset = Some(offset);
}
fn set_offset_next(&mut self, offset: usize) {
debug_assert!(offset <= self.packet().len());
self.rr_iterator.offset_next = offset;
}
fn invalidate(&mut self) {
self.rr_iterator.offset = None;
}
fn recompute_rr(&mut self) {
self.rr_iterator.recompute();
}
fn recompute_sections(&mut self) {
self.rr_iterator.parsed_packet.recompute().unwrap();
}
#[inline]
fn raw(&self) -> RRRaw<'_> {
RRRaw {
packet: &self.rr_iterator.parsed_packet.packet(),
offset: self.rr_iterator.offset.unwrap(),
name_end: self.rr_iterator.name_end,
}
}
#[inline]
fn raw_mut(&mut self) -> RRRawMut<'_> {
RRRawMut {
packet: self.rr_iterator.parsed_packet.packet_mut(),
offset: self.rr_iterator.offset.unwrap(),
name_end: self.rr_iterator.name_end,
}
}
#[inline]
fn parsed_packet(&self) -> &ParsedPacket {
&self.rr_iterator.parsed_packet
}
#[inline]
fn parsed_packet_mut(&mut self) -> &mut ParsedPacket {
&mut self.rr_iterator.parsed_packet
}
fn next(mut self) -> Option<Self> {
{
let rr_iterator = &mut self.rr_iterator;
let parsed_packet = &mut rr_iterator.parsed_packet;
debug_assert_eq!(rr_iterator.section, Section::Edns);
if rr_iterator.offset.is_none() {
let count = parsed_packet.edns_count;
let offset = parsed_packet.offset_edns;
if count == 0 {
return None;
}
rr_iterator.rrs_left = count;
rr_iterator.offset_next = offset.unwrap();
}
if rr_iterator.rrs_left == 0 {
return None;
}
rr_iterator.rrs_left -= 1;
rr_iterator.offset = Some(rr_iterator.offset_next);
rr_iterator.name_end = rr_iterator.offset.unwrap();
let offset_next =
RRIterator::edns_skip_rr(&parsed_packet.packet(), rr_iterator.name_end);
rr_iterator.offset_next = offset_next;
}
Some(self)
}
}
impl<'t> EdnsIterator<'t> {
pub fn new(rr_iterator: RRIterator<'t>) -> Self {
EdnsIterator { rr_iterator }
}
}
|
rust
|
Singapore restaurant owners face a gloomy Lunar New Year, with Covid-related interruptions signaling that even countries with a good handle on cases will suffer until the pandemic is under control globally.
Singapore restaurant owners face a gloomy Lunar New Year, with Covid-related interruptions signaling that even countries with a good handle on cases will suffer until the pandemic is under control globally.
A labor-supply crunch in the food and beverage sector and government restrictions on office-sponsored parties will weigh even more on a sector that’s already suffering more than the general economy. Across the region, much of which marks the holiday starting Friday, this year’s celebrations are likely to be muted given the ongoing struggle to control outbreaks of Covid.
“Stricter engagement rules, foreign worker shortages and food-supply disruptions will mean a far more quiet Chinese New Year,” said Chua Hak Bin, senior economist at Maybank Kim Eng Research Pte in Singapore.
While overall retail sales fell 3. 6% in December from a year earlier, food and beverage, including online purchases, were down 16. 5%, their eleventh straight month of double-digit declines.
The sector’s difficulties at the holiday underscore the challenge in raising Singapore’s growth from its worst annual pace in more than a half-century last year, even as local cases of Covid-19 hover close to zero and a vaccination drive is underway. The government is expected to include more industry-specific stimulus measures when it releases its new budget Feb. 16.
That’s one day after the government reports final fourth-quarter and full-year gross domestic product data. The latest official estimate is that the economy shrank 5. 8% in 2020 and will expand 4% to 6% in 2021.
The data on food and beverage sales suggest that residents who normally travel out of Singapore during the holiday, but are stuck in town this year, won’t make up for the loss of revenue from international visitors who can’t enter the city-state.
Maybank’s Chua says the hit now will be more serious than over the Christmas period, with total retail sales expected to fall by about 7% in January and February from a year earlier, almost twice the pace of December’s decline.
While much of the city-state this weekend will be tossing fish -- a holiday tradition the government has asked to be celebrated without the usual enthusiastic shouts -- food and beverage vendors face a laundry list of challenges:
Restaurant owners will be among those looking for more aid in the annual budget.
The retail and food sector “remains hopeful that there will be continued policy support this year in order to keep the players afloat for longer,” Selena Ling, head of treasury research and strategy at Oversea-Chinese Banking Corp. in Singapore, said in a Feb. 8 report.
The retail sales data for February are scheduled for release April 5.
|
english
|
- Priyanka Chopra CONCERNED About Air Pollution In Delhi; Has This To Say!
- Sunny Leone Takes Superhero Avatar; Announces 'Kore'
- Hrithik Roshan's Cousin Pashmina Roshan To Follow In His Footsteps And Enter Bollywood In 2020?
- Abhishek Bachchan Shuts Troll Who Called Him 'Unemployed'; His Epic Reply Is A Must-Read!
- Pati Patni Aur Woh Trailer: 'Pati' Kartik Aaryan Is Caught Between 'Patni' Bhumi & 'Woh' Ananya!
- Eid 2020: Akshay Kumar And Salman Khan To Clash At The Box Office?
- Kareena Kapoor Would React Like This If She's Stuck In A Lift With Ranbir's Current GF & His Exes!
- Shah Rukh Khan, Wife Gauri Khan & Kids Aryan, AbRam & Suhana Squeeze Memories Into A Frame!
- Kartik Aaryan's Pati Patni Aur Woh Trailer Turns Out To Be Divisive; Check Out The Public Reaction!
- Bigg Boss 13: Is Vishal The Next Wild Card Entrant? Were Devoleena & Rashami Sent To Secret Room?
- Will Rajinikanth Accept Atlee's Storyline For Baasha 2?
- Was Vijay Paid Rs 1 Crore As Advance For Thalapathy 64?
- Suriya To Collaborate With Kaithi Director Lokesh Kanagaraj?
- Tamil TRP Ratings Week 43: Suriya's Singam 2 Dominates By Scoring Big!
- Ala Vaikunthapuramulo Third Single Set For Release; Is Sarileru Neekevvaru Lagging In The Race?
- Bigg Boss Telugu 3 Recap: The Eliminations That Occurred!
- Will Chiranjeevi Be A Better Host Than Nagarjuna For Bigg Boss Telugu 4?
- Prabhas To Help Ram Charan Recover From Sye Raa Narasimha Reddy Debacle?
- Naga Chaitanya And Venkatesh Starrer Venky Mama In Big Trouble Due To A Bollywood Biggie?
|
english
|
In a new twist to the complex Ram temple-Babri mosque case, main litigant Hashim Ansari has discussed with Akhara Parishad chief Mahant Gyan Das a new proposal for the resolution of the Ayodhya dispute that they plan to put before the Supreme Court.
The out-of-court settlement proposal suggests that the 70 acres of the disputed premises would accommodate both mosque and temple with a partition wall at a height of 100 feet.
Mr. Ansari has met Mr. Gyan Das, who is also the head priest of Ayodhya’s famous Hanuman Garhi temple, on several occasions to find a solution to the complex issue that has remained unresolved for decades.
The idea behind the plan is to find a middle path keeping in mind the sensibilities of both the Hindu and the Muslim communities, sources said.
“We are drafting the final points of a negotiation draft, which will be presented before the Supreme Court soon after the hearing starts. We will be meeting the Prime Minister too to seek his cooperation,” Mr. Das said after the meeting on Monday.
The proposal has been discussed with top Hindu religious groups and main spiritual leaders, he added.
Mr. Ansari said, “After the draft is finalised, we will get it signed by all the top religious leaders from both the communities who are supporting our cause since the beginning, before submitting it in the Supreme Court. ” The negotiation draft would be made public only after it was submitted to the Supreme Court, he added.
Referring to recent statements by the Vishwa Hindu Parishad on the issue, Mr. Das said it was not a party in the “peace process”.
“They just want to create communal tension between the communities. . . We are in favour of construction of both Ram temple and Babri mosque adjacent to each other but with a huge division wall of more than 100 ft in between,” the Hanuman Garhi temple head priest said.
|
english
|
#include <algorithm>
#include <cfloat>
#include <vector>
#include <cmath>
#include <iostream>
#include <fstream>
#include <sstream>
#include "caffe/layers/region_loss_layer.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/region_util.hpp"
#include "caffe/util/bbox_util.hpp"
int iter = 0;
namespace caffe {
template <typename Dtype>
Dtype delta_region_box(vector<Dtype> truth, Dtype* x, vector<Dtype> biases, int n, int index, int i, int j,
int w, int h, Dtype* delta, float scale, int stride) {
vector<Dtype> pred;
pred = get_region_box(x, biases, n, index, i, j, w, h, stride);
float iou = box_iou(pred, truth);
float tx = truth[0] * w - i;
float ty = truth[1] * h - j;
float tw = log(truth[2] * w / biases[2 * n]);
float th = log(truth[3] * h / biases[2 * n + 1]);
delta[index + 0 * stride] = scale * (tx - x[index + 0 * stride]);
delta[index + 1 * stride] = scale * (ty - x[index + 1 * stride]);
delta[index + 2 * stride] = scale * (tw - x[index + 2 * stride]);
delta[index + 3 * stride] = scale * (th - x[index + 3 * stride]);
return iou;
}
template <typename Dtype>
void delta_region_class(Dtype* data, Dtype* &diff, int index, int class_label, int classes,
string softmax_tree, tree *t, float scale, int stride, Dtype* avg_cat, bool tag) {
if (softmax_tree != "") {
} else {
if (diff[index] && tag) {
diff[index + stride * class_label] = scale * (1 - data[index + stride * class_label]);
return;
}
for (int n = 0; n < classes; ++n) {
diff[index + stride * n] = scale * (((n == class_label) ? 1 : 0) - data[index + stride * n]);
if (n == class_label) {
*avg_cat += data[index + stride * n];
}
}
}
}
template <typename Dtype>
Dtype get_hierarchy_prob(Dtype* data, tree *t, int c, int stride) {
float p = 1;
while (c >= 0) {
p = p * data[c * stride];
c = t->parent[c];
}
return p;
}
template <typename Dtype>
void gradient_array(const Dtype* x, const int n, Dtype* delta)
{
for (int i = 0; i < n; i++)
delta[i] *= x[i] * (1 - x[i]);
}
template <typename Dtype>
void RegionLossLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
LossLayer<Dtype>::LayerSetUp(bottom, top);
RegionLossParameter param = this->layer_param_.region_loss_param();
height_ = param.side();
width_ = param.side();
num_class_ = param.num_classes();
coords_ = param.coords();
num_ = param.num();
softmax_ = param.softmax();
batch_ = param.batch();
thresh_ = param.threshold();
bias_match_ = param.bias_match();
jitter_ = param.jitter();
rescore_ = param.rescore();
absolute_ = param.absolute();
random_ = param.random();
for (int c = 0; c < param.biases_size(); ++c) {
biases_.push_back(param.biases(c));
}
object_scale_ = param.object_scale();
noobject_scale_ = param.noobject_scale();
class_scale_ = param.class_scale();
coord_scale_ = param.coord_scale();
softmax_tree_ = param.softmax_tree();
if (softmax_tree_ != "")
t_ = tree(softmax_tree_);
class_map_ = param.class_map();
if (class_map_ != "") {
string line;
std::fstream fin(class_map_.c_str());
if (!fin){
LOG(INFO) << "no map file";
}
int index = 0;
int id = 0;
while (getline(fin, line)) {
stringstream ss;
ss << line;
ss >> id;
cls_map_[index] = id;
index ++;
}
fin.close();
}
int label_count = bottom[1]->count(1);
int tmp_label_count = 30 * num_;
CHECK_EQ(label_count, tmp_label_count);
int input_count = bottom[0]->count(1);
int tmp_input_count = width_ * height_ * num_ * (coords_ + num_class_ + 1);
CHECK_EQ(input_count, tmp_input_count);
}
template <typename Dtype>
void RegionLossLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
LossLayer<Dtype>::Reshape(bottom, top);
delta_.ReshapeLike(*bottom[0]);
output_.ReshapeLike(*bottom[0]);
}
template <typename Dtype>
void RegionLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const Dtype* input_data = bottom[0]->cpu_data();
const Dtype* label_data = bottom[1]->cpu_data();
batch_ = bottom[0]->num();
Dtype* output = output_.mutable_cpu_data();
caffe_copy(output_.count(), input_data, output);
forward_softmax<Dtype>(input_data, output, batch_, num_, width_, height_, coords_, num_class_, softmax_);
Dtype* delta = delta_.mutable_cpu_data();
caffe_set(delta_.count(), Dtype(0.0), delta);
Dtype avg_anyobj(0.0), avg_obj(0.0), avg_iou(0.0), avg_cat(0.0), recall(0.0), loss(0.0);
int count = 0;
int class_count = 0;
for (int b = 0; b < batch_; b++) {
for (int j = 0; j < height_; j++) {
for (int i = 0; i < width_; i++) {
for (int n = 0; n < num_; n++) {
int box_index = entry_index(b, n * width_ * height_ + j * width_ + i, 0, num_, width_, height_, coords_, num_class_);
vector<Dtype> pred = get_region_box(output, biases_, n, box_index, i, j, width_, height_, width_ * height_);
float best_iou = 0;
for(int t = 0; t < 30; ++t) {
vector<Dtype> truth;
Dtype x = label_data[b * 30 * (coords_ + 1) + t * (coords_ + 1) + 1];
Dtype y = label_data[b * 30 * (coords_ + 1) + t * (coords_ + 1) + 2];
Dtype w = label_data[b * 30 * (coords_ + 1) + t * (coords_ + 1) + 3];
Dtype h = label_data[b * 30 * (coords_ + 1) + t * (coords_ + 1) + 4];
if (x == 0.0f) break;
truth.push_back(x);
truth.push_back(y);
truth.push_back(w);
truth.push_back(h);
Dtype iou = box_iou(pred, truth);
if (iou > best_iou) {
best_iou = iou;
}
}
int obj_index = entry_index(b, n * width_ * height_ + j * width_ + i, coords_, num_, width_, height_, coords_, num_class_);
avg_anyobj += output[obj_index];
delta[obj_index] = noobject_scale_ * (0 - output[obj_index]);
if (best_iou > thresh_) {
delta[obj_index] = 0;
}
/*
if (iter < 12800 / batch_) {
vector<Dtype> truth;
truth.push_back((i + .5) / width_);
truth.push_back((j + .5) / height_);
truth.push_back((biases_[2 * n]) / width_);
truth.push_back((biases_[2 * n + 1]) / height_);
delta_region_box(truth, output, biases_, n, box_index, i, j, width_, height_, delta, .01f, width_ * height_);
}
*/
}
}
}
for (int t = 0; t < 30; t++) {
vector<Dtype> truth;
int class_label = label_data[b * 30 * (coords_ + 1) + t * (coords_ + 1) + 0];
Dtype x = label_data[b * 30 * (coords_ + 1) + t * (coords_ + 1) + 1];
Dtype y = label_data[b * 30 * (coords_ + 1) + t * (coords_ + 1) + 2];
Dtype w = label_data[b * 30 * (coords_ + 1) + t * (coords_ + 1) + 3];
Dtype h = label_data[b * 30 * (coords_ + 1) + t * (coords_ + 1) + 4];
if (x == 0.0f) break;
truth.push_back(x);
truth.push_back(y);
truth.push_back(w);
truth.push_back(h);
float best_iou = 0;
int best_n = 0;
int i = truth[0] * width_;
int j = truth[1] * height_;
vector<Dtype> truth_shift;
truth_shift.push_back(0);
truth_shift.push_back(0);
truth_shift.push_back(w);
truth_shift.push_back(h);
for (int n = 0; n < num_; n++) {
int box_index = entry_index(b, n * width_ * height_ + j * width_ + i, 0,
num_, width_, height_, coords_, num_class_);
vector<Dtype> pred = get_region_box(output, biases_, n, box_index, i, j, width_, height_, width_ * height_);
if (bias_match_) {
pred[2] = biases_[2 * n] / width_;
pred[3] = biases_[2 * n + 1] / height_;
}
pred[0] = 0;
pred[1] = 0;
float iou = box_iou(pred, truth_shift);
if (iou > best_iou) {
best_iou = iou;
best_n = n;
}
}
int box_index = entry_index(b, best_n * width_ * height_ + j * width_ + i, 0,
num_, width_, height_, coords_, num_class_);
float iou = delta_region_box(truth, output, biases_, best_n, box_index, i, j, width_, height_, delta,
coord_scale_ * (2 - truth[2] * truth[3]), width_ * height_);
if (iou > 0.5) recall += 1;
avg_iou += iou;
int obj_index = entry_index(b, best_n * width_ * height_ + j * width_ + i, coords_,
num_, width_, height_, coords_, num_class_);
avg_obj += output[obj_index];
delta[obj_index] = object_scale_ * (1 - output[obj_index]);
if (rescore_)
delta[obj_index] = object_scale_ * (iou - output[obj_index]);
if (class_map_ != "") class_label = cls_map_[class_label];
int class_index = entry_index(b, best_n * width_ * height_ + j * width_ + i, coords_ + 1,
num_, width_, height_, coords_, num_class_);
delta_region_class(output, delta, class_index, class_label, num_class_, softmax_tree_, &t_, class_scale_, width_ * height_, &avg_cat, !softmax_);
++count;
++class_count;
}
}
for (int i = 0; i < delta_.count(); ++i) {
loss += delta[i] * delta[i];
}
top[0]->mutable_cpu_data()[0] = loss;
iter++;
if (!(iter % 100)) {
LOG(INFO) << "avg_noobj: "<< avg_anyobj / (width_ * height_ * num_ * batch_)
<< " avg_obj: " << avg_obj / count
<<" avg_iou: " << avg_iou / count
<< " avg_cat: " << avg_cat / class_count
<< " recall: " << recall / count
<< " class_count: "<< class_count;
}
}
template <typename Dtype>
void RegionLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
if (propagate_down[1]) {
LOG(FATAL) << this->type() << " Layer cannot backpropagate to label inputs.";
}
if (propagate_down[0]) {
/*
for (int b = 0; b < bottom[0]->num(); b++) {
for (int n = 0; n < num_; n++) {
int index = entry_index(b, n * width_ * height_, 0, num_, width_, height_, coords_, num_class_);
gradient_array(output_.cpu_data() + index, 2 * width_ * height_, delta_.mutable_cpu_data() + index);
index = entry_index(b, n * width_ * height_, coords_, num_, width_, height_, coords_, num_class_);
gradient_array(output_.cpu_data() + index, width_ * height_, delta_.mutable_cpu_data() + index);
}
}
*/
const Dtype alpha = -1 * top[0]->cpu_diff()[0];
caffe_cpu_axpby(bottom[0]->count(), alpha, delta_.cpu_data(), Dtype(0), bottom[0]->mutable_cpu_diff());
}
}
#ifdef CPU_ONLY
STUB_GPU(RegionLossLayer);
#endif
INSTANTIATE_CLASS(RegionLossLayer);
REGISTER_LAYER_CLASS(RegionLoss);
} // namespace caffe
|
cpp
|
{%- assign social = site.theme_config.social_links -%}
<ul>
{%-if social.dribble-%}
<a href=""https://dribbble.com/{{ social.dribbble | cgi_escape | escape }}"">Dribble</a>
|
{%-endif-%}
{%-if social.facebook-%}
<a href="https://www.facebook.com/{{ social.facebook | cgi_escape | | escape }} }}">Facebook</a>
|
{%-endif-%}
{%-if social.flickr-%}
<a href="https://www.flickr.com/photos/{{ social.flickr | cgi_escape | | escape }} }}">Flickr</a>
|
{%-endif-%}
{%-if social.github-%}
<a href="https://github.com/{{ social.github | cgi_escape | escape }}">Github</a>
|
{%-endif-%}
{%-if social.instagram-%}
<a href="https://www.instagram.com/{{ social.instagram | cgi_escape | escape }}">Instagram</a>
|
{%-endif-%}
{%-if social.linkedin-%}
<a href="https://www.linkedin.com/in/{{ social.linkedin | cgi_escape | escape }}">Linkedin</a>
|
{%-endif-%}
{%-if social.pinterest-%}
<a href="https://www.pinterest.com/{{ social.pinterest | cgi_escape | escape }}"></a>
|
{%-endif-%}
{%- for mst in social.mastodon -%}{%- if mst.username and mst.instance -%}
<a href="https://{{ mst.instance | cgi_escape | escape }}/@{{ mst.username }}">MST</a>
|
{%-endif-%}{%- endfor -%}
{%-if social.twitter-%}
<a href="https://twitter.com/{{ social.twitter | cgi_escape | escape }}">Twitter</a>
|
{%-endif-%}
{%-if social.youtube-%}
<a href="https://www.youtube.com/{{ social.youtube | cgi_escape | escape }}">Youtube</a>
|
{%-endif-%}
{%-if social.youtube_channel-%}
<a href="https://www.youtube.com/channel/{{ social.youtube_channel | cgi_escape | escape }}">Youtube Channel</a>
|
{%-endif-%}
{%-if social.telegram-%}
<a href="https://t.me/{{ social.telegram | cgi_escape | escape }}">Telegram</a>
|
{%-endif-%}
{%-if social.microdotblog%}
<a href=""https://micro.blog/{{ social.microdotblog | cgi_escape | escape }}>Microdotblog</a>
|
{%-endif-%}
{%-if social.reddit-%}
<a href="https://reddit.com/user/{{ social.reddit | cgi_escape | escape }}">Reddit</a>
|
{%-endif-%}
{%-if social.phone-%}
<a href="{{ 'feed.xml' | relative_url }}">RSS</a>
|
{%-endif-%}
{%-if page.phone-%}
{{ page.phone }}
|
{%-endif-%}
</ul>
|
html
|
package ch07;
public class Ex02 {
public static void main(String[] args) {
int[][] numbers = new int[3][5];
int cnt;
cnt = 0;
for (int i = 0 ; i < 3 ; i++) {
for(int j = 0 ; j < 5 ; j++) {
numbers[i][j] = cnt;
cnt++;
}
}
for (int i = 0 ; i < 3 ; i++) {
for(int j = 0 ; j < 5 ; j++) {
System.out.print(numbers[i][j] + " ");
}
System.out.println();
}
}
}
|
java
|
/*
*
* EntityListForm actions
*
*/
import { SET_FILTER } from './constants';
export function setFilter(values) {
return {
type: SET_FILTER,
values,
};
}
|
javascript
|
After a month of heavy-duty action [PLAYERS, AGNEEPATH], the spotlight is on romance [EK MAIN AUR EKK TU, EKK DEEWANA THA] in the month of St. Valentine. Besides, films like READY, BODYGUARD and SINGHAM have revitalized the trend of South remakes. Gautham Menon returns to the Bollywood centre stage after a gap [REHNAA HAI TERRE DIL MEIN] with a remake of his films, made in Tamil first and Telugu later.
Both, the Tamil version [VINNAITHAANDI VARUVAAYAA] and also its Telugu adaptation [YE MAAYA CHESAVE] were considered path-breaking motion pictures. Though essentially a remake, EKK DEEWANA THA conjures memories of K. Balachander's roaring hit EK DUUJE KE LIYE. Menon is a master storyteller, no two opinions on that, but EKK DEEWANA THA fails to leave an impact for a valid reason: A beaten to death plot tends to stagnate after a point. Also, Menon overstays the hospitality by dragging the film in its second hour. Just when you think the story would conclude, Menon does a time travel and starts a new chapter in this never-ending love story. That, honestly, only makes this snail-paced movie a taxing and cumbersome experience.
Sachin [Prateik] is an engineering graduate from a middle class family in Mumbai, who is in love with the world of cinema. One day, he sees Jessie [Amy Jackson] and it is love at first sight for him. Jessie is beautiful, elegant, smart and classy. But Jessie belongs to an orthodox Malayali Christian family where watching movies or falling in love are completely taboo.
Sachin finds himself increasingly drawn to her. Jessie, on her part, tries to forge a friendship between them, believing that cloaking their feelings under the umbrella of friendship would save them heartache, tears and a full-blown family drama. But these two different characters go through the pangs and pleasure of first love, while battling with the situations that life has placed them in.
Opting for a tried and tested story is not sacrilegious, but the challenge lies in giving a new spin to the age-old tale, which, regrettably, EKK DEEWANA THA doesn't. Like all love stories, EKK DEEWANA THA doesn't lack drama and emotions, but barring a few episodes, the viewer doesn't get absorbed into the world of Sachin and Jessie, which is the chief inadequacy of the film and which, concurrently, reflects on the sketchy written material.
What baffles the viewer is the character of Jessie. While the guy is crazily in love with her, the girl, in contrast, seems downright confused about her feelings for the guy. She appears indecisive about what she really yearns for and this aspect, to put it bluntly, sends out puzzling signals not only to the lover boy, but to the by-now-exasperated viewer as well.
The screenplay totters and flounders the moment Jessie decides to part ways. The justification offered is least persuasive. Since the reason for separation is not forceful enough, it leaves the viewer feeling unsympathetic, detached and disconnected from the goings-on subsequently. The sequence at the Taj Mahal and the portions thereafter don't work either.
Menon does handle certain dramatic and emotional moments with aplomb, but the written material lets him down. Barring a few moments that stand out, the twists and turns in the plot are repetitive and devoid of exhilaration. Also, the film is agonizingly prolonged and should've been spruced up by judiciously trimming at least 20-25 minutes. Rahman's musical score has the unambiguous stamp of a genius. The best track is of course 'Hosanna'. But the film could've done without a song or two in the latter half. The film boasts of some stunning visuals and the credit for it goes to DoP M.S. Prabhu, who captures the scenic beauty of Kerala with dexterity. Manu Rishi's dialogue are real at times, but tend to get flowery at places.
Prateik is natural to the core. In fact, after DHOBI GHAT, wherein Prateik's efforts were appreciated, now EKK DEEWANA THA makes you wake up to the potential the talented youngster possesses. It requires tremendous self-assurance and acting prowess to enact this intricate and demanding character in an authoritative style. His dialogue delivery is near-perfect and body language, precise.
Amy Jackson is charming. She carries off her part -- and also the Indian attire -- splendidly. Though the character is not very compelling -- since she appears confused about her emotions for the madly-in-love Prateik -- it must be said that you don't detect slip-ups in her presentation of the character. In fact, it isn't a straight-forward role for a tenderfoot, but Amy handles it like a pro. However, her makeup is inconsistent. Manu Rishi excels and so does Sachin Khedekar. Babu Antony [as Jessie's father] does a fine job. Ashwin Kakumanu and Samantha get no scope. Ramesh Sippy is likeable in a cameo.
On the whole, EKK DEEWANA THA has a few sparkling moments, that's about it. However, it lacks the fizz for the spectator to go deewana!
|
english
|
<filename>calc.py
#!/usr/bin python3
# -*- coding:UTF-8 -*-
# Author: nigo
import os
import json
import pandas as pd
import akshare as ak
import baostock as bs
import datetime
import numpy as np
from multiprocessing import Pool
import multiprocessing.pool as mpp
import istarmap
from tqdm import tqdm
import plotly.figure_factory as ff
from plotly.subplots import make_subplots
from tabulate import tabulate
import wcwidth
import time
import re
import plotly.express as px
import plotly.graph_objects as go
import sys
import requests
PATH_CONFIG = './config.json'
PATH_TMP ='./tmp.csv'
with open(PATH_CONFIG,'rb') as f:
json_str = json.load(f)
INDEX_LIST = json_str['index_list']
PATH_INFO = json_str['path_info']
PATH_INDEX = json_str['path_index']
PATH_WEIGHT = json_str['path_weight']
PATH_STOCK = json_str['path_stock']
PATH_MARKET = json_str['path_market']
def read_csv(path,**kw):
df = pd.read_csv(path,converters=kw)
return df
def full_code(code,is_index=True,is_dot=False):
"""补全证券代码
code:6位证券代码
is_index:是否是指数代码
return:补全的代码
"""
if is_dot:
sh = 'sh.'
sz = 'sz.'
else:
sh = 'sh'
sz = 'sz'
if is_index:
if code[0] == '0':
full = sh + code
else:
full = sz + code
else:
if code[0] == '6':
full = sh + code
else:
full = sz + code
return full
def convert_code(code):
"""指数代码小写转大写"""
if code.endswith('sh'):
return code[0:6] + '.SH'
elif code.endswith('sz'):
return code[0:6] + '.SZ'
else:
return code
def get_security_info(code=None):
"""获取指数基本信息
code:6位代码
return:代码对应信息
"""
path = os.path.join(PATH_INFO,'index_info.csv')
if os.path.exists(path):
df = read_csv(path,index_code=str)
else:
print('获取指数基本信息列表')
df = ak.index_stock_info()
df.to_csv(path,index=False)
if code:
df = df[df.index_code==code]
return df
def config_update_date(is_all=False):
"""获取配置文件中上次更新日期"""
with open('config.json',mode='rb') as f:
json_str = json.load(f)
if is_all:
update_date = json_str['update_date_all']
else:
update_date = json_str['update_date']
if update_date == "None":
return None
else:
return update_date
def judge_update_stock(is_all=False):
"""判断是否更新数据"""
update_date = config_update_date(is_all)
if not update_date:
return True
if update_date < str(datetime.date.today()):
return True
else:
return False
def get_file_date(file):
"""获取文件修改日期"""
filemt = time.localtime(os.stat(file).st_mtime)
file_time = time.strftime('%Y-%m-%d',filemt)
return file_time
def judge_update_weight(code,date):
"""判断给定日期是否需要进行更新
date:给定日期
"""
file_new = code + '-new.csv'
path_new = os.path.join(PATH_WEIGHT,file_new)
file_history = code + '-history.csv'
path_history = os.path.join(PATH_WEIGHT,file_history)
if os.path.exists(path_new) and os.path.exists(path_history):
new_date = get_file_date(path_new)
history_date = get_file_date(path_history)
update_date = min(new_date,history_date)
given_date = datetime.datetime.strptime(date,'%Y-%m-%d')
update_date = datetime.datetime.strptime(update_date,'%Y-%m-%d')
diff_month = (given_date.year - update_date.year) * 12 + given_date.month - update_date.month # 月份差
if diff_month<1:
return False
else:
return True
else:
return True
def get_exists_stocks_path():
"""获取本地文件已有数据的股票列表"""
stock_files = os.listdir(PATH_STOCK)
stocks = [ os.path.join(PATH_STOCK,file) for file in stock_files if file.endswith('csv')]
return stocks
def get_all_stocks():
"""获取本地文件已有数据的股票列表"""
stock_files = os.listdir(PATH_STOCK)
stocks = [ file.split('_')[0] for file in stock_files if file.endswith('csv')]
return stocks
def get_stocks(code,date):
"""计算给定日期的成分股"""
df_new,df_history = get_index_weight(code,date)
df_new = df_new[df_new.in_date <= date]
df_history = df_history[(df_history.out_date > date) & (df_history.in_date <= date)]
a = df_new['stock_code'].to_list()
b = df_history['stock_code'].to_list()
c = a + b
stocks = list(set(c))
return stocks
def get_all_index_stocks(index_list):
"""计算指数列表所涉及到的所有股票"""
stock_list = []
for code in index_list:
df_new,df_history = get_index_weight(code)
a = df_new['stock_code'].to_list()
b = df_history['stock_code'].to_list()
c = a + b
stock_list += c
stock_list = list(set(stock_list))
if os.path.exists(PATH_TMP):
os.remove(PATH_TMP)
return stock_list
def get_index_weight(code,date=None):
"""获取指数成分股"""
if not date:
date = str(datetime.date.today())
file_new = code + '-new.csv'
path_new = os.path.join(PATH_WEIGHT,file_new)
file_history = code + '-history.csv'
path_history = os.path.join(PATH_WEIGHT,file_history)
flag = judge_update_weight(code,date)
# 判断是不是更新过了,应对接口频率限制
if os.path.exists(PATH_TMP):
tmp = read_csv(PATH_TMP,code=str)
else:
tmp = pd.DataFrame(columns=['code'])
ignore_code_list = tmp['code'].to_list()
if code in ignore_code_list:
flag = False
# 判断是不是更新过了,应对接口频率限制
if os.path.exists(path_new) and not flag:
df_new = read_csv(path_new,publish_date=str,stock_code=str)
else:
print('获取%s的成分股最新数据' % code)
df_new = ak.index_stock_cons(code)
df_new.columns = ['stock_code','stock_name','in_date']
df_new.to_csv(path_new,index=False)
if os.path.exists(path_history) and not flag:
df_history = read_csv(path_history,publish_date=str,stock_code=str)
else:
print('获取%s的成分股历史数据' % code)
df_history = ak.index_stock_hist(full_code(code))
df_history.to_csv(path_history,index=False)
df_updated = pd.DataFrame([code],columns=['code'])
tmp = pd.concat([tmp,df_updated])
tmp.to_csv(PATH_TMP,index=False)
return df_new,df_history
def get_k_date(full_code,start_date,end_date):
"""获取单个股票数据"""
rs = bs.query_history_k_data_plus(full_code,
"date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST",
start_date=start_date, end_date=end_date,
frequency="d", adjustflag="3")
result_list = []
while (rs.error_code == '0') & rs.next():
result_list.append(rs.get_row_data())
df = pd.DataFrame(result_list, columns=rs.fields)
return df
def get_trade_date(start_date=None,end_date=None):
"""获取交易日历
start_date:开始日期
end_date:结束日期
"""
if not start_date:
start_date = '1990-01-01'
if not end_date:
end_date = datetime.date.today()
end_date = end_date.strftime('%Y-%m-%d')
path = os.path.join(PATH_INFO,'a_trade_date.csv')
flag = judge_update_stock() and judge_update_stock(is_all=True)
if not flag and os.path.exists(path):
print('读取交易日历')
df = read_csv(path)
else:
print('获取交易日历')
df = ak.tool_trade_date_hist_sina()
df.columns = ['trade_date']
df.to_csv(path,index=False)
df['trade_date'] = df['trade_date'].apply(lambda x: x.strftime('%Y-%m-%d'))
df = df[(df.trade_date<=end_date) & (df.trade_date>=start_date)]
return df['trade_date'].to_list()
def get_hk_stock(code):
"""获取香港PE\PB"""
df_pb = ak.stock_hk_eniu_indicator(symbol=code, indicator="市净率")
df_pb = df_pb.loc[:,['date','pb']]
df_pe = ak.stock_hk_eniu_indicator(symbol=code, indicator="市盈率")
df_pe = df_pe.loc[:,['date','pe']]
df = pd.merge(df_pe,df_pb,on='date')
df['psTTM'] = ''
df.columns = ['date','peTTM','pbMRQ','psTTM']
path = os.path.join(PATH_STOCK,'%s_indicator.csv' % code)
df.to_csv(path,index=False)
def update_stock_data(stocks,is_all=False,use_flag=False):
"""更新所有股票数据"""
bs.login()
today = datetime.date.today()
today = str(today)
yestoday = datetime.date.today() - datetime.timedelta(days=1)
yestoday = str(yestoday)
trade_date_list = get_trade_date(end_date=yestoday)
end_date = trade_date_list[-1]
pbar = tqdm(stocks)
for stock in pbar:
pbar.set_description("更新股票%s数据" % stock)
# print('更新股票%s数据' % stock)
path = os.path.join(PATH_STOCK,'%s_indicator.csv' % stock)
if use_flag:
flag = judge_update_stock(is_all)
else:
flag = True
if os.path.exists(path):
if flag:
try:
df = read_csv(path,code=str,date=str)
data_date = df.iloc[-1,0]
if end_date<=data_date:
continue
else:
if stock[:2] == 'hk':
get_hk_stock(stock)
else:
start_date = datetime.datetime.strptime(data_date,'%Y-%m-%d') + datetime.timedelta(days=1)
start_date = start_date.strftime('%Y-%m-%d')
df_single = get_k_date(full_code(stock,is_index=False,is_dot=True),start_date,today)
if not df_single.empty:
df_single.to_csv(path,index=False,header=False,mode='a')
except:
if stock[:2] == 'hk':
get_hk_stock(stock)
else:
df_single = get_k_date(full_code(stock,is_index=False,is_dot=True),'1990-01-01',today)
if not df_single.empty:
df_single.to_csv(path,index=False)
else:
if stock[:2] == 'hk':
get_hk_stock(stock)
else:
df_single = get_k_date(full_code(stock,is_index=False,is_dot=True),'1990-01-01',today)
if not df_single.empty:
df_single.to_csv(path,index=False)
bs.logout()
def calc_avg(numbers):
"""等权平均"""
return len(numbers) / sum([1 / p if p > 0 else 0 for p in numbers])
def calc_mid(numbers):
numbers = [ i for i in numbers if i>0]
if numbers:
numbers.sort()
half = len(numbers) // 2
return (numbers[half] + numbers[~half]) / 2
else:
return 0
def calc_average(*args,method='avg'):
"""根据pe_list,pb_list,ps_list取平均数
args: (pe_list,pb_list,ps_list)
method:计算模式 avg等权平均 mid中位数
"""
num = len(args[0]) # 列表中元素数量
result_list = []
for arg in args:
if method == 'mid':
result = calc_mid(arg)
else:
result = calc_avg(arg)
result = round(result,2)
result_list.append(result)
return tuple(result_list)
def get_index_pe_pb_date(date, stocks):
'''指定日期的指数PE_PB(等权重)'''
pe_list = []
pb_list = []
ps_list = []
for stock in stocks:
path = os.path.join(PATH_STOCK,'%s_indicator.csv' % stock)
if not os.path.exists(path):
print('股票%s文件不存在' % stock)
continue
df = read_csv(path,code=str,date=str)
df_tmp = df[df.date == date]
df_tmp = df_tmp.reset_index(drop=True) # 重置索引
if not df_tmp.empty:
pe_list.append(df_tmp.loc[0,'peTTM'])
pb_list.append(df_tmp.loc[0,'pbMRQ'])
ps_list.append(df_tmp.loc[0,'psTTM'])
if len(pe_list) > 0:
try :
(pe,pb,ps) = calc_average(pe_list,pb_list,ps_list)
return (date,round(pe, 2), round(pb, 2), round(ps,2) )
except:
return None
else:
return None
def combine_all_markt_stocks():
"""合并所有存在的股票数据"""
paths = get_exists_stocks_path()
df_list = []
for path in tqdm(paths,desc='合并所有股票文件'):
df_tmp = read_csv(path,code=str,date=str)
df_tmp = df_tmp.loc[:,['date','code','peTTM','pbMRQ','psTTM']]
df_list.append(df_tmp)
df = pd.concat(df_list)
return df
def get_all_market_pe_pb_date(df,date):
df_date = df[df.date == date]
pe_list = df_date['peTTM'].to_list()
pb_list = df_date['pbMRQ'].to_list()
ps_list = df_date['psTTM'].to_list()
(pe,pb,ps) = calc_average(pe_list,pb_list,ps_list,method='mid')
return (date,round(pe,2),round(pb,2),round(ps,2))
def get_all_market_pe_pb():
"""计算指定期间的全市场pe,pb"""
flag = judge_update_stock(is_all=True)
path = os.path.join(PATH_MARKET,'all_market_pe_pb.csv')
end_date = datetime.date.today() - datetime.timedelta(1)
end_date = end_date.strftime('%Y-%m-%d')
if os.path.exists(path):
df = read_csv(path,trade_date=str)
if flag:
updated_date = df.iloc[-1].trade_date
updated_date = datetime.datetime.strptime(updated_date,'%Y-%m-%d')
start_date = updated_date + datetime.timedelta(1)
start_date = start_date.strftime('%Y-%m-%d')
# df_tmp = get_index_pe_pb(start_date=start_date)
df_tmp = calc_all_market_pe_pb(start_date,end_date)
df = pd.concat([df, df_tmp])
else:
df = calc_all_market_pe_pb('1990-01-01', end_date)
# df = get_index_pe_pb(start_date='1990-01-01')
df.to_csv(path,index=False)
return df
def calc_all_market_pe_pb(start_date,end_date):
"""计算指定期间的全市场pe,pb"""
df = combine_all_markt_stocks()
df['code'] = df['code'].apply(lambda x:re.sub('\D','',x)) # 去除股票代码中非数字项
start = datetime.datetime.strptime(start_date,'%Y-%m-%d')
end = datetime.datetime.strptime(end_date,'%Y-%m-%d')
trade_date_list = get_trade_date()
date_range = pd.date_range(start=start, end=end,freq="D")
dates = [ date.strftime('%Y-%m-%d') for date in date_range if date.strftime('%Y-%m-%d') in trade_date_list ]
args = [(df,date) for date in dates]
result = []
qbar = tqdm(dates)
for date in qbar:
qbar.set_description('计算%s全市场估值' % date)
df_date = df[df.date == date]
if not df_date.empty:
pe_list = df_date['peTTM'].to_list()
pb_list = df_date['pbMRQ'].to_list()
ps_list = df_date['psTTM'].to_list()
(pe,pb,ps) = calc_average(pe_list,pb_list,ps_list,method='mid')
result.append([date,pe,pb,ps])
df = pd.DataFrame(result,columns=['trade_date','PE','PB','PS'])
return df
def all_market_pe_pb_legu():
"""乐咕全市场"""
path_pe = './all_market/all_market_pe_legu.csv'
path_pb = './all_market/all_market_pb_legu.csv'
flag = judge_update_stock(is_all=True)
if os.path.exists(path_pe):
if flag:
df_pe = ak.stock_a_ttm_lyr()
df_pe.to_csv(path_pe,index=False)
else:
df_pe = read_csv(path_pe)
else:
df_pe = ak.stock_a_ttm_lyr()
df_pe.to_csv(path_pe,index=False)
if os.path.exists(path_pb):
if flag:
df_pb = ak.stock_a_all_pb()
df_pb.to_csv(path_pb,index=False)
else:
df_pb = read_csv(path_pb)
else:
df_pb = ak.stock_a_all_pb()
df_pb.to_csv(path_pb,index=False)
pe_ratio = df_pe.iloc[-1].quantileInAllHistoryMiddlePeTtm * 100 # 历史百分位
pb_ratio = df_pb.iloc[-1].quantileInAllHistoryMiddlePB * 100 # 历史百分位
df_pe = df_pe.loc[:,['date','middlePETTM']]
df_pb = df_pb.loc[:,['date','middlePB']]
df_pe.columns = ['trade_date','PE']
df_pb.columns = ['trade_date','PB']
df = pd.merge(df_pe,df_pb,on='trade_date')
date = df.iloc[-1].trade_date
pe = df.iloc[-1].PE
pb = df.iloc[-1].PB
# (pe_ratio,pb_ratio) = calc_ratio(df,'PE','PB')
title='%s全市场中位数PE、PB 当前PE:%.2f,当前PB:%.2f 当前PE百分位:%.2f,当前PB百分位:%.2f' % (date,pe,pb,pe_ratio,pb_ratio)
plot(df,title)
write_update_date(is_all=True)
def all_market_value(years=None):
"""全市场pe,pb"""
get_all_k_data() # 更新所有股票数据
df = get_all_market_pe_pb()
if years:
df = filter_recent_years(df,years)
else:
df = df[df.PE > 0]
(pe_ratio,pb_ratio) = calc_ratio(df,'PE','PB')
df = df.reset_index(drop=True)
min_pe = df['PE'].min()
max_pe = df['PE'].max()
mid_pe = df['PE'].median()
desc_pe = calc_state(pe_ratio)
min_pb = df['PB'].min()
max_pb = df['PB'].max()
mid_pb = df['PB'].median()
desc_pb = calc_state(pb_ratio)
init_date = df.loc[0,'trade_date']
columns=[
'日期','PE','PE百分位','PE估值','PB','PB百分位','PB估值',
'PE最小值','PE最大值','PE中位值','PB最小值','PB最大值','PB中位值',
'起始日期'
]
df = pd.DataFrame(
[df.iloc[-1].trade_date,
df.iloc[-1].PE,
'%.2f' % pe_ratio,
desc_pe,
df.iloc[-1].PB,
'%.2f' % pb_ratio,
desc_pb,
min_pe,max_pe,mid_pe,
min_pb,max_pb,mid_pb,
init_date]
)
df = df.T
df.columns = columns
write_update_date(is_all=True)
fmt = 'fancy_grid'
print(tabulate(df, headers='keys', tablefmt=fmt))
def calc_index_pe_pb(date,code=None):
"""计算指数一天的pe,pb,ps"""
# print('计算指数%s在日期%s的估值' % (code,date))
if code:
stocks = get_stocks(code,date)
else:
stocks = get_all_stocks()
pe_pb = get_index_pe_pb_date(date, stocks)
return pe_pb
def get_index_pe_pb(start_date=None, end_date=None,code=None):
'''指数历史PE_PB'''
if code:
init_date = get_security_info(code).iloc[0,-1] # 获取指数信息中的publish_date
else:
init_date = '1990-01-01'
pe_list = []
pb_list = []
ps_list = []
day_list = []
if start_date is None:
start_date = init_date
if end_date is None:
end_date = datetime.date.today() - datetime.timedelta(1) #如果有误,请删除#号 ,获取的是前一天的数据
end_date = datetime.date.strftime(end_date, '%Y-%m-%d')
trade_date_list = get_trade_date()
date_range = pd.date_range(start=start_date, end=datetime.date.today()-datetime.timedelta(1),freq="D")#交易日
if code:
args = [(day.strftime('%Y-%m-%d'),code) for day in date_range if day.strftime('%Y-%m-%d') in trade_date_list]
else:
args = [(day.strftime('%Y-%m-%d'),None) for day in date_range if day.strftime('%Y-%m-%d') in trade_date_list]
pool = Pool()
result = pool.istarmap(calc_index_pe_pb,args)
result_list = []
pbar = tqdm(result,total=len(args))
for _ in pbar:
result_list.append(_)
pool.close()
pool.join()
# result_list = []
# for arg in args:
# pe_pb = calc_index_pe_pb(arg[0],arg[1])
# result_list.append(pe_pb)
result = [i for i in result_list if i]
df = pd.DataFrame(result,columns=['trade_date','PE','PB','PS'])
df = df.sort_values(by='trade_date')
return df
def get_hs_data(index_list):
'''增量更新沪深指数估值数据'''
for code in index_list:
print(u'正在计算:', code)
path = os.path.join(PATH_INDEX,'%s_pe_pb.csv' % code)
if os.path.exists(path): #增量更新
df_pe_pb = pd.read_csv(path,
converters={'trade_date': str},
index_col=False)
start_date = datetime.datetime.strptime(df_pe_pb.iloc[-1].trade_date,
'%Y-%m-%d') + datetime.timedelta(1)
start_date = start_date.strftime('%Y-%m-%d')
df_pe_pb = pd.concat([df_pe_pb, get_index_pe_pb(code=code, start_date=start_date)])
else: #初次计算
print('init')
df_pe_pb = get_index_pe_pb(code=code)
if not df_pe_pb.empty:
df_pe_pb.to_csv(path, index=None)
print('已更新%s-pepbps数据' % code)
else:
print('未更新%s-pepbps数据' % code)
def filter_recent_years(df, year_num):
"""筛选近几年的数据
df:指数估值表
year_num:年数
"""
end_date = datetime.datetime.strptime(df.iloc[-1].trade_date, '%Y-%m-%d')
start_date = end_date - datetime.timedelta(365 * year_num)
df = df[df['trade_date'] > start_date.strftime('%Y-%m-%d')]
return df
def calc_state(data):
if data < 10.0:
return u'极度低估'
elif 10 <= data and data < 20:
return u'低估'
elif 20 <= data and data < 40:
return u'正常偏低'
elif 40 <= data and data < 60:
return u'正常'
elif 60 <= data and data < 80:
return u'正常偏高'
elif 80 <= data and data < 90:
return u'高估'
elif 90 <= data:
return u'极度高估'
def calc_ratio(df,*args):
"""计算比率"""
ratio_list = []
for arg in args:
ratio = len(df[df[arg] < df.iloc[-1][arg]]) / float(len(df)) * 100
ratio_list.append(ratio)
return tuple(ratio_list)
def pe_pb_analysis(index_list=['000300', '000905']):
'''PE_PB分析'''
all_index = get_security_info()
all_index=all_index.set_index('index_code')
hk_idx_name = {'hscei': u'国企指数', 'hsi': u'恒生指数'}
pe_results = []
pe_code_list = []
pb_results = []
pb_code_list = []
ps_results = []
ps_code_list = []
#沪深
for code in index_list:
path = os.path.join(PATH_INDEX,'%s_pe_pb.csv' % code)
if not os.path.exists(path): #增量更新
continue
index_name = all_index.loc[code, 'display_name']
# df_pe_pb = read_csv(path,trade_date=str)
df_pe_pb = pd.read_csv(path,
index_col=None,
converters={'trade_date': str})
df_pe_pb = filter_recent_years(df_pe_pb, 10)
if len(df_pe_pb) < 250 * 3: #每年250个交易日,小于3年不具有参考价值
continue
(pe_ratio, pb_ratio, ps_ratio) = calc_ratio(df_pe_pb,'PE','PB','PS')
pe_results.append([
index_name, df_pe_pb.iloc[-1].PE,
'%.2f' % pe_ratio,
calc_state(pe_ratio),
min(df_pe_pb.PE),
max(df_pe_pb.PE),
'%.2f' % np.median(df_pe_pb.PE),
'%.2f' % np.std(df_pe_pb.PE), df_pe_pb.iloc[0].trade_date
])
pb_results.append([
index_name, df_pe_pb.iloc[-1].PB,
'%.2f' % pb_ratio,
calc_state(pb_ratio),
min(df_pe_pb.PB),
max(df_pe_pb.PB),
'%.2f' % np.median(df_pe_pb.PB),
'%.2f' % np.std(df_pe_pb.PB), df_pe_pb.iloc[0].trade_date
])
ps_results.append([
index_name, df_pe_pb.iloc[-1].PS,
'%.2f' % ps_ratio,
calc_state(ps_ratio),
min(df_pe_pb.PS),
max(df_pe_pb.PS),
'%.2f' % np.median(df_pe_pb.PS),
'%.2f' % np.std(df_pe_pb.PS), df_pe_pb.iloc[0].trade_date
])
pe_code_list.append(code)
pb_code_list.append(code)
ps_code_list.append(code)
date_str = df_pe_pb.iloc[-1].trade_date
# 恒生指数、恒生国企指数
for code,index_name in hk_idx_name.items():
df_pe_pb = get_hk_pe_pb(code)
df_pe_pb = filter_recent_years(df_pe_pb,10)
(pe_ratio,) = calc_ratio(df_pe_pb,'PE')
pe_results.append([
index_name,df_pe_pb.iloc[-1].PE,
'%.2f' % pe_ratio,
calc_state(pe_ratio),
min(df_pe_pb.PE),
max(df_pe_pb.PE),
'%.2f' % df_pe_pb['PE'].median(),
'%.2f' % df_pe_pb['PE'].std(),df_pe_pb.iloc[0].trade_date
])
pe_columns = [
u'名称', u'当前PE', u'百分位(%)', u'估值状态', u'最小', u'最大', u'中位数', u'标准差',
u'起始日期'
]
pe_df = pd.DataFrame(data=pe_results,
index=pe_code_list + list(hk_idx_name.keys()),
columns=pe_columns)
pe_df.index.name = date_str
pb_columns = [
u'名称', u'当前PB', u'百分位(%)', u'估值状态', u'最小', u'最大', u'中位数', u'标准差',
u'起始日期'
]
pb_df = pd.DataFrame(data=pb_results,
index=pb_code_list ,
columns=pb_columns)
pb_df.index.name = date_str
ps_columns = [
u'名称', u'当前PS', u'百分位(%)', u'估值状态', u'最小', u'最大', u'中位数', u'标准差',
u'起始日期'
]
ps_df = pd.DataFrame(data=ps_results,
index=ps_code_list,
columns=ps_columns)
ps_df.index.name = date_str
pe_df = pe_df.apply(pd.to_numeric, errors='ignore')
pb_df = pb_df.apply(pd.to_numeric, errors='ignore')
ps_df = ps_df.apply(pd.to_numeric, errors='ignore')
return (pe_df.sort_values(by='百分位(%)', ascending=True),
pb_df.sort_values(by='百分位(%)', ascending=True),
ps_df.sort_values(by='百分位(%)', ascending=True),
)
def write_update_date(is_all=False):
with open(PATH_CONFIG,'rb') as f:
json_str = json.load(f)
if is_all:
json_str['update_date_all'] = str(datetime.date.today())
else:
json_str['update_date'] = str(datetime.date.today())
with open(PATH_CONFIG,'w') as f:
json.dump(json_str,f,indent=2)
def index_customer_value():
"""将自选的指数生成pe\pb\ps估值列表"""
stock_list = get_all_index_stocks(INDEX_LIST)
update_stock_data(stock_list,use_flag=True)
get_hs_data(INDEX_LIST)
pe,pb,ps = pe_pb_analysis(INDEX_LIST)
# 写入更新时间
write_update_date()
fmt = 'fancy_grid'
print(tabulate(pe, headers='keys', tablefmt=fmt))
print(tabulate(pb, headers='keys', tablefmt=fmt))
print(tabulate(ps, headers='keys', tablefmt=fmt))
def stock_info(is_all=False):
"""获取股票信息"""
flag = judge_update_stock(is_all)
path = os.path.join(PATH_INFO,'stock_info.csv')
if os.path.exists(path) and not flag:
df = read_csv(path,code=str)
else:
df = ak.stock_info_a_code_name()
df.to_csv(path,index=False)
return df
def get_all_k_data():
"""更新A股所有股票数据"""
df = stock_info(is_all=True)
stocks = df['code'].to_list()
update_stock_data(stocks,is_all=True,use_flag=True)
def request_hk(url,path):
"""获取恒生指数与恒生国企指数PE"""
response = requests.get(url)
df = pd.DataFrame(response.json())
df = df.fillna('')
if not df.empty:
df.columns = ['trade_date','PE','close']
df.to_csv(path,index=False)
else:
df = None
return df
def get_hk_pe_pb(code):
"""获取恒生指数与恒生国企指数PE"""
if code == 'hsi':
url = 'https://eniu.com/chart/peindex/hkhsi/t/all'
path = os.path.join(PATH_INDEX,'hsi_pe_pb.csv')
elif code == 'hscei':
url = 'https://eniu.com/chart/peindex/hkhscei/t/all'
path = os.path.join(PATH_INDEX,'hscei_pe_pb.csv')
else:
return None
if os.path.exists(path):
df = read_csv(path)
data_date = df.iloc[-1].trade_date
yestoday = datetime.date.today() - datetime.timedelta(days=1)
if data_date>=str(yestoday):
pass
else:
df = request_hk(url,path)
else:
df = request_hk(url,path)
return df
def plot_pe_pb(df,title,**kw):
"""绘图主程序"""
line1 = go.Scatter(x=df.trade_date,y=df.PE,mode='lines',name='PE',
hovertemplate='<b>日期</b>:%{x|%Y-%m-%d}<br><b>PE</b>:%{y}',
line_color='#555555') #EF553B
line2 = go.Scatter(x=df.trade_date,y=df.PB,mode='lines',name='PB',yaxis='y2',
hovertemplate='<b>日期</b>:%{x|%Y-%m-%d}<br><b>PB</b>:%{y}',
line_dash='dot',line_color='#778AAE')
fig = go.Figure([line1,line2])
relation = {
'pe_high': {'name':'90% PE','color':'#DC3912','yaxis':'y','dash':None},
'pe_low': {'name':'10% PE','color':'#66AA00','yaxis':'y','dash':None},
'pe_mid': {'name':'50% PE','color':'#FF9900','yaxis':'y','dash':None},
'pb_high': {'name':'90% PB','color':'#DC3912','yaxis':'y2','dash':'dot'},
'pb_low': {'name':'10% PB','color':'#66AA00','yaxis':'y2','dash':'dot'},
'pb_mid': {'name':'50% PB','color':'#FF9900','yaxis':'y2','dash':'dot'},
}
if kw:
for k,v in relation.items():
if k in kw.keys():
line = go.Scatter(x=df.trade_date,y=[kw[k]] * len(df) ,mode='lines',name=v['name'],line_color=v['color'],yaxis=v['yaxis'],line_dash=v['dash'])
fig.add_trace(line)
else:
fig.update_traces(line_color='#EF553B',selector={'name':'PE'})
fig.update_layout(title=title,
yaxis_title='PE',
yaxis_dtick=10,
yaxis2=dict(title='PB',overlaying='y',side='right',dtick=1),
xaxis_title='日期',
# hovermode="y unified",
# xaxis_dtick = 'Y1'
)
fig.show()
def plot_all_market(start_date='1995-01-01'):
"""绘制全市场估值趋势图"""
path = os.path.join(PATH_MARKET,'all_market_pe_pb.csv')
df = pd.read_csv(path)
df = df[df.trade_date >= start_date]
plot_pe_pb(df,'全市场估值')
def plot(df,title):
"""绘制基础图形"""
pe_high = df['PE'].quantile(0.9)
pe_low = df['PE'].quantile(0.1)
pe_mid = df['PE'].quantile(0.5)
pb_high = df['PB'].quantile(0.9)
pb_low = df['PB'].quantile(0.1)
pb_mid = df['PB'].quantile(0.5)
plot_pe_pb(df,title,pe_high=pe_high,pe_low=pe_low,pe_mid=pe_mid,pb_high=pb_high,pb_low=pb_low,pb_mid=pb_mid)
def plot_index(code,start_date='2000-01-01'):
"""绘制指数估计趋势图"""
path = os.path.join(PATH_INDEX,'%s_pe_pb.csv' % code)
df = pd.read_csv(path)
df = df[df.trade_date >= start_date]
info = get_security_info(code)
name = info.iloc[0].display_name
(pe_ratio, pb_ratio) = calc_ratio(df,'PE','PB')
last_date = df.iloc[-1].trade_date
pe = df.iloc[-1].PE
pb = df.iloc[-1].PB
title = '%s %s %s估值 当前PE:%.2f,当前PB:%.2f 当前PE百分位:%.2f,当前PB百分位:%.2f' % (name,code,last_date,pe,pb,pe_ratio,pb_ratio)
plot(df,title)
def plot_stock(code,start_date='1995-01-01'):
"""绘制个股的估值图"""
path = os.path.join(PATH_STOCK,'%s_indicator.csv' % code)
df = pd.read_csv(path)
df = df.loc[:,['date','peTTM','pbMRQ','psTTM']]
df.columns = ['trade_date','PE','PB','PS']
if code[:2] =='hk':
name = ''
else:
info = stock_info()
info = info[info.code==code]
name = info.iloc[0]['name']
df = df[df.trade_date >= start_date]
(pe_ratio, pb_ratio) = calc_ratio(df,'PE','PB')
last_date = df.iloc[-1].trade_date
pe = df.iloc[-1].PE
pb = df.iloc[-1].PB
title = '%s %s %s估值 当前PE:%.2f,当前PB:%.2f 当前PE百分位:%.2f,当前PB百分位:%.2f' % (name,code,last_date,pe,pb,pe_ratio,pb_ratio)
plot(df,title)
def check_dir():
path_list = [PATH_INDEX,PATH_INFO,PATH_STOCK,PATH_MARKET,PATH_WEIGHT]
for path in path_list:
if not os.path.exists(path):
os.mkdir(path)
def main():
if len(sys.argv)<2:
print('需要至少1个参数\r\nmarket:全市场估计\r\nindex:指数估值\r\nstock:个股估值')
else:
check_dir()
if sys.argv[1] == 'market':
if len(sys.argv)<3:
all_market_pe_pb_legu()
# all_market_value()
# plot_all_market()
# print("输入python calc.py market 2015-01-01\r\n将从指定日期开始计算\r\n否则默认图形从1995-01-01开始绘制")
else:
all_market_pe_pb_legu()
# all_market_value()
# plot_all_market(sys.argv[2])
elif sys.argv[1] == 'index':
if len(sys.argv)<3:
index_customer_value()
print("需要输入指数代码,如:\r\npython calc.py index 000827")
elif len(sys.argv)==3:
stocks = get_all_index_stocks([sys.argv[2]])
update_stock_data(stocks)
get_hs_data([sys.argv[2]])
plot_index(sys.argv[2])
else:
stocks = get_all_index_stocks([sys.argv[2]])
update_stock_data(stocks)
get_hs_data([sys.argv[2]])
plot_index(sys.argv[2],sys.argv[3])
elif sys.argv[1] == 'stock':
if len(sys.argv)<3:
print("需要输入股票代码,如:\r\npython calc.py stock 000002")
elif len(sys.argv)==3:
update_stock_data([sys.argv[2]])
plot_stock(sys.argv[2])
else:
update_stock_data([sys.argv[2]])
plot_stock(sys.argv[2],sys.argv[3])
else:
print('参数错误')
if __name__ == "__main__":
main()
# get_hk_stock('hk09988')
# update_stock_data('hk09988')
# all_market_pe_pb_legu()
# index_customer_value()
# all_market_value()
# check_dir()
|
python
|
<reponame>AN3223/lc3vm
use lc3vm::*;
// Tests that the Register enums
// correctly cast into u16 values
#[test]
fn registers_as_u16() {
assert_eq!(R::R0 as u16, 0);
assert_eq!(R::R1 as u16, 1);
assert_eq!(R::R2 as u16, 2);
assert_eq!(R::R3 as u16, 3);
assert_eq!(R::R4 as u16, 4);
assert_eq!(R::R5 as u16, 5);
assert_eq!(R::R6 as u16, 6);
assert_eq!(R::R7 as u16, 7);
assert_eq!(R::PC as u16, 8);
assert_eq!(R::COND as u16, 9);
}
// Tests that the opcodes correctly
// cast into u16 values
#[test]
fn ops_as_u16() {
assert_eq!(OP::BR as u16, 0);
assert_eq!(OP::ADD as u16, 1);
assert_eq!(OP::LD as u16, 2);
assert_eq!(OP::ST as u16, 3);
assert_eq!(OP::JSR as u16, 4);
assert_eq!(OP::AND as u16, 5);
assert_eq!(OP::LDR as u16, 6);
assert_eq!(OP::STR as u16, 7);
assert_eq!(OP::RTI as u16, 8);
assert_eq!(OP::NOT as u16, 9);
assert_eq!(OP::LDI as u16, 10);
assert_eq!(OP::STI as u16, 11);
assert_eq!(OP::JMP as u16, 12);
assert_eq!(OP::RES as u16, 13);
assert_eq!(OP::LEA as u16, 14);
assert_eq!(OP::TRAP as u16, 15);
}
// Ensures the condition flags properly
// cast into u16 values
#[test]
fn condition_flags_as_u16() {
assert_eq!(FL::POS as u16, 1);
assert_eq!(FL::ZRO as u16, 2);
assert_eq!(FL::NEG as u16, 4);
}
|
rust
|
<filename>reactor-core/src/test/java/reactor/core/publisher/FluxPublishOnTest.java
/*
* Copyright (c) 2011-2017 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 reactor.core.publisher;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.Disposable;
import reactor.core.Exceptions;
import reactor.core.Fuseable;
import reactor.core.Scannable;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.test.MockUtils;
import reactor.test.StepVerifier;
import reactor.test.publisher.FluxOperatorTest;
import reactor.test.subscriber.AssertSubscriber;
import reactor.util.annotation.Nullable;
import reactor.util.concurrent.Queues;
import reactor.util.function.Tuple2;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static reactor.core.Scannable.Attr.*;
import static reactor.core.scheduler.Schedulers.fromExecutor;
import static reactor.core.scheduler.Schedulers.fromExecutorService;
public class FluxPublishOnTest extends FluxOperatorTest<String, String> {
@Override
protected Scenario<String, String> defaultScenarioOptions(Scenario<String, String> defaultOptions) {
return defaultOptions.prefetch(Queues.SMALL_BUFFER_SIZE)
.fusionModeThreadBarrier(Fuseable.ASYNC)
.fusionMode(Fuseable.ASYNC);
}
void assertRejected(StepVerifier.Step<String> step) {
try {
step.verifyErrorSatisfies(e -> Assert.assertTrue(Exceptions.unwrap(e) instanceof RejectedExecutionException));
}
catch (Exception e) {
assertThat(Exceptions.unwrap(e)).isInstanceOf(RejectedExecutionException.class);
}
}
void assertNoRejected(StepVerifier.Step<String> step) {
try {
step
.thenAwait()
.consumeErrorWith(e -> Assert.assertTrue(Exceptions.unwrap(e) instanceof RejectedExecutionException))
.verify(Duration.ofMillis(1));
}
catch (Exception e) {
assertThat(Exceptions.unwrap(e)).isInstanceOf(RejectedExecutionException.class);
}
catch (AssertionError e){
if(!e.getMessage().contains("timed out")) {
throw e;
}
}
}
@Override
protected List<Scenario<String, String>> scenarios_operatorError() {
return Arrays.asList(
scenario(f -> f.publishOn(Schedulers.fromExecutor(d -> {
throw exception();
})))
.producerError(new RejectedExecutionException("Scheduler unavailable"))
.receiverDemand(0),
scenario(f -> f.publishOn(new FailWorkerScheduler()))
.producerEmpty(),
scenario(f -> f.publishOn(new FailNullWorkerScheduler()))
.producerEmpty(),
scenario(f -> f.publishOn(new RejectingWorkerScheduler(false, false)))
.verifier(this::assertNoRejected)
.receiverDemand(0),
scenario(f -> f.publishOn(new RejectingWorkerScheduler(true, false)))
.verifier(this::assertRejected)
.receiverDemand(0),
scenario(f -> f.publishOn(new RejectingWorkerScheduler(true, true)))
.verifier(this::assertNoRejected)
.receiverDemand(0),
scenario(f -> f.publishOn(new RejectingWorkerScheduler(false, true)))
.verifier(this::assertNoRejected),
scenario(f -> f.publishOn(new RejectingWorkerScheduler(false, false)))
.verifier(this::assertNoRejected)
.receiverDemand(0),
scenario(f -> f.publishOn(new RejectingWorkerScheduler(false, true)))
.verifier(this::assertNoRejected)
.producerEmpty(),
scenario(f -> f.publishOn(new RejectingWorkerScheduler(true, false)))
.verifier(this::assertRejected)
.receiverDemand(0),
scenario(f -> f.publishOn(new RejectingWorkerScheduler(true, true)))
.verifier(this::assertNoRejected)
.receiverDemand(0)
);
}
@Override
protected List<Scenario<String, String>> scenarios_operatorSuccess() {
return Arrays.asList(
scenario(f -> f.publishOn(Schedulers.immediate())),
scenario(f -> f.publishOn(Schedulers.immediate(), false, 4))
.prefetch(4),
scenario(f -> f.publishOn(Schedulers.immediate(), 1))
.prefetch(1),
scenario(f -> f.publishOn(Schedulers.immediate(), Integer.MAX_VALUE))
.prefetch(Integer.MAX_VALUE)
);
}
public static ExecutorService exec;
@BeforeClass
public static void before() {
exec = Executors.newSingleThreadExecutor();
}
@AfterClass
public static void after() {
exec.shutdownNow();
}
@Test(expected = IllegalArgumentException.class)
public void failPrefetch() {
Flux.range(1, 10)
.publishOn(Schedulers.immediate(), -1);
}
@Test
public void normal() {
StepVerifier.create(Flux.range(1, 1_000_000)
.hide()
.publishOn(Schedulers.fromExecutorService(exec)))
.expectNextCount(1_000_000)
.verifyComplete();
}
@Test
public void normalBackpressured1() throws Exception {
StepVerifier.create(Flux.range(1, 1_000)
.hide()
.publishOn(Schedulers.fromExecutorService(exec)), 0)
.thenRequest(500)
.expectNextCount(500)
.thenRequest(500)
.expectNextCount(500)
.verifyComplete();
}
@Test
public void normalBackpressured() throws Exception {
StepVerifier.create(Flux.range(1, 1_000_000)
.hide()
.publishOn(Schedulers.fromExecutorService(exec)), 0)
.thenRequest(500_000)
.expectNextCount(500_000)
.thenRequest(500_000)
.expectNextCount(500_000)
.verifyComplete();
}
@Test
public void normalSyncFused() {
StepVerifier.create(Flux.range(1, 1_000_000)
.publishOn(Schedulers.fromExecutorService(exec)))
.expectNextCount(1_000_000)
.verifyComplete();
}
@Test
public void normalSyncFusedBackpressured() throws Exception {
StepVerifier.create(Flux.range(1, 1_000_000)
.publishOn(Schedulers.fromExecutorService(exec)), 0)
.thenRequest(500_000)
.expectNextCount(500_000)
.thenRequest(500_000)
.expectNextCount(500_000)
.verifyComplete();
}
@Test
public void normalAsyncFused() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Sinks.Many<Integer> up =
Sinks.many().unsafe().unicast().onBackpressureBuffer(new ConcurrentLinkedQueue<>());
for (int i = 0; i < 1_000_000; i++) {
up.emitNext(i);
}
up.emitComplete();
up.asFlux()
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValueCount(1_000_000)
.assertNoError()
.assertComplete();
}
@Test
public void normalAsyncFusedBackpressured() throws Exception {
Sinks.Many<Integer> up =
Sinks.many().unsafe().unicast().onBackpressureBuffer(Queues.<Integer>unbounded(1024).get());
for (int i = 0; i < 1_000_000; i++) {
up.emitNext(0);
}
up.emitComplete();
StepVerifier.create(up.asFlux().publishOn(Schedulers.fromExecutorService(exec)), 0)
.expectSubscription()
.thenRequest(500_000)
.expectNextCount(500_000)
.thenRequest(500_000)
.expectNextCount(500_000)
.verifyComplete();
}
@Test
public void error() {
StepVerifier.create(Flux.error(new RuntimeException("forced failure"))
.publishOn(Schedulers.fromExecutorService(exec)))
.verifyErrorMessage("forced failure");
}
@Test
public void errorHide() {
StepVerifier.create(Flux.error(new RuntimeException("forced failure"))
.hide()
.publishOn(Schedulers.fromExecutorService(exec)))
.verifyErrorMessage("forced failure");
}
@Test
public void empty() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.<Integer>empty().publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertNoValues()
.assertNoError()
.assertComplete();
}
@Test
public void errorDelayed() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux<Integer> err = Flux.error(new RuntimeException("forced " + "failure"));
Flux.range(1, 1000)
.concatWith(err)
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValueCount(1000)
.assertError(RuntimeException.class)
.assertErrorMessage("forced failure")
.assertNotComplete();
}
@Test
public void classicJust() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.just(1)
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertNoError()
.assertComplete();
}
@Test
public void classicJustBackpressured() throws Exception {
AssertSubscriber<Integer> ts = AssertSubscriber.create(0);
Flux.just(1)
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
Thread.sleep(100);
ts.assertNoValues()
.assertNoError()
.assertNotComplete();
ts.request(500);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertNoError()
.assertComplete();
}
@Test
public void filtered() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.range(1, 2_000_000)
.hide()
.publishOn(Schedulers.fromExecutorService(exec))
.filter(v -> (v & 1) == 0)
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValueCount(1_000_000)
.assertNoError()
.assertComplete();
}
@Test
public void filtered1() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.range(1, 2_000)
.hide()
.publishOn(Schedulers.fromExecutorService(exec))
.filter(v -> (v & 1) == 0)
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValueCount(1000)
.assertNoError()
.assertComplete();
}
@Test
public void normalFilteredBackpressured() throws Exception {
StepVerifier.create(Flux.range(1, 2_000_000)
.hide()
.publishOn(Schedulers.fromExecutorService(exec))
.filter(v -> (v & 1) == 0), 0)
.thenRequest(500_000)
.expectNextCount(250_000)
.thenRequest(500_000)
.expectNextCount(750_000)
.verifyComplete();
}
@Test
public void normalFilteredBackpressured1() throws Exception {
StepVerifier.create(Flux.range(1, 2_000)
.hide()
.publishOn(Schedulers.fromExecutorService(exec))
.filter(v -> (v & 1) == 0), 0)
.thenRequest(500)
.expectNextCount(250)
.thenRequest(500)
.expectNextCount(750)
.verifyComplete();
}
@Test
public void callableEvaluatedTheRightTime() {
AtomicInteger count = new AtomicInteger();
Mono<Integer> p = Mono.fromCallable(count::incrementAndGet)
.publishOn(Schedulers.fromExecutorService(ForkJoinPool.commonPool()));
Assert.assertEquals(0, count.get());
AssertSubscriber<Integer> ts = AssertSubscriber.create();
p.subscribe(ts);
if (!ts.await(Duration.ofSeconds(5))
.isTerminated()) {
ts.cancel();
Assert.fail("AssertSubscriber timed out");
}
Assert.assertEquals(1, count.get());
}
public void diamond() {
@SuppressWarnings("deprecation")
DirectProcessor<Integer> sp = DirectProcessor.create();
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux<Integer> fork1 = sp.map(d -> d)
.publishOn(Schedulers.fromExecutorService(exec));
Flux<Integer> fork2 = sp.map(d -> d)
.publishOn(Schedulers.fromExecutorService(exec));
ts.request(256);
Flux.merge(fork1, fork2)
.publishOn(Schedulers.fromExecutorService(ForkJoinPool.commonPool()))
.subscribe(ts);
Flux.range(0, 128)
.hide()
.publishOn(Schedulers.fromExecutorService(ForkJoinPool.commonPool()))
.subscribe(sp);
ts.await(Duration.ofSeconds(5))
.assertTerminated()
.assertValueCount(256)
.assertNoError()
.assertComplete();
}
@Test
public void prefetchAmountOnly() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
ConcurrentLinkedQueue<Long> clq = new ConcurrentLinkedQueue<>();
Flux.range(1, 2)
.hide()
.doOnRequest(v -> {
clq.offer(v);
})
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(100));
ts.assertValues(1, 2)
.assertNoError()
.assertComplete();
int s = clq.size();
Assert.assertTrue("More requests?" + clq, s == 1 || s == 2 || s == 3);
Assert.assertEquals((Long) (long) Queues.SMALL_BUFFER_SIZE, clq.poll());
}
@Test
public void boundedQueue() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.range(1, 100_000)
.hide()
.publishOn(Schedulers.fromExecutor(exec), 128)
.subscribe(ts);
ts.await(Duration.ofSeconds(1));
ts.assertValueCount(100_000)
.assertNoError()
.assertComplete();
}
@Test
public void boundedQueueFilter() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.range(1, 100_000)
.hide()
.publishOn(Schedulers.fromExecutor(exec), 128)
.filter(v -> (v & 1) == 0)
.subscribe(ts);
ts.await(Duration.ofSeconds(1));
ts.assertValueCount(50_000)
.assertNoError()
.assertComplete();
}
@Test
public void withFlatMap() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.range(1, 100_000)
.flatMap(Flux::just)
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValueCount(100_000)
.assertNoError()
.assertComplete();
}
@Test
public void syncSourceWithNull() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.just(1, null, 1)
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertError(NullPointerException.class)
.assertNotComplete();
}
@Test
public void syncSourceWithNull2() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.fromIterable(Arrays.asList(1, null, 1))
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertError(NullPointerException.class)
.assertNotComplete();
}
@Test
public void mappedsyncSourceWithNull() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.just(1, 2)
.map(v -> v == 2 ? null : v)
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertError(NullPointerException.class)
.assertNotComplete();
}
@Test
public void mappedsyncSourceWithNullHidden() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.just(1, 2)
.hide()
.map(v -> v == 2 ? null : v)
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertError(NullPointerException.class)
.assertNotComplete();
}
@Test
public void mappedsyncSourceWithNullPostFilterHidden() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.just(1, 2)
.hide()
.map(v -> v == 2 ? null : v)
.publishOn(Schedulers.fromExecutorService(exec))
.filter(v -> true)
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertError(NullPointerException.class)
.assertNotComplete();
}
@Test
public void mappedsyncSourceWithNull2() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.fromIterable(Arrays.asList(1, 2))
.map(v -> v == 2 ? null : v)
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertError(NullPointerException.class)
.assertNotComplete();
}
@Test
public void mappedsyncSourceWithNull2Hidden() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.fromIterable(Arrays.asList(1, 2))
.hide()
.map(v -> v == 2 ? null : v)
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertError(NullPointerException.class)
.assertNotComplete();
}
@Test
public void mappedFilteredSyncSourceWithNull() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.just(1, 2)
.map(v -> v == 2 ? null : v)
.filter(v -> true)
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertError(NullPointerException.class)
.assertNotComplete();
}
@Test
public void mappedFilteredSyncSourceWithNull2() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Flux.fromIterable(Arrays.asList(1, 2))
.map(v -> v == 2 ? null : v)
.filter(v -> true)
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertError(NullPointerException.class)
.assertNotComplete();
}
@Test
public void mappedAsyncSourceWithNull() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Sinks.Many<Integer> up =
Sinks.many().unsafe().unicast().onBackpressureBuffer(Queues.<Integer>get(2).get());
up.emitNext(1);
up.emitNext(2);
up.emitComplete();
up.asFlux().map(v -> v == 2 ? null : v)
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertError(NullPointerException.class)
.assertNotComplete();
}
@Test
public void mappedAsyncSourceWithNullPostFilter() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Sinks.Many<Integer> up =
Sinks.many().unsafe().unicast().onBackpressureBuffer(Queues.<Integer>get(2).get());
up.emitNext(1);
up.emitNext(2);
up.emitComplete();
up.asFlux().map(v -> v == 2 ? null : v)
.publishOn(Schedulers.fromExecutorService(exec))
.filter(v -> true)
.subscribe(ts);
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertError(NullPointerException.class)
.assertNotComplete();
}
@Test
public void crossRangeHidden() {
int count = 1000000;
StepVerifier.create(Flux.range(1, count)
.hide()
.flatMap(v -> Flux.range(v, 2)
.hide(), false, 128, 1)
.hide()
.publishOn(Schedulers.fromExecutorService(exec)))
.expectNextCount(2 * count)
.verifyComplete();
}
@Test
public void crossRange() {
int count = 1000000;
StepVerifier.create(Flux.range(1, count)
.flatMap(v -> Flux.range(v, 2), false, 128, 1)
.publishOn(Schedulers.fromExecutorService(exec)))
.expectNextCount(2 * count)
.verifyComplete();
}
@Test
public void crossRangeMaxHidden() throws Exception {
int count = 1000000;
StepVerifier.create(Flux.range(1, count)
.hide()
.flatMap(v -> Flux.range(v, 2)
.hide(), false, 4, 32)
.hide()
.publishOn(Schedulers.fromExecutorService(exec)))
.expectNextCount(2 * count)
.verifyComplete();
}
@Test
public void crossRangeMax() {
int count = 1000000;
StepVerifier.create(Flux.range(1, count)
.flatMap(v -> Flux.range(v, 2), false, 128, 32)
.publishOn(Schedulers.fromExecutorService(exec)))
.expectNextCount(2 * count)
.verifyComplete();
}
@Test
public void crossRangeMaxUnbounded() {
int count = 1000000;
StepVerifier.create(Flux.range(1, count)
.flatMap(v -> Flux.range(v, 2))
.publishOn(Schedulers.fromExecutorService(exec)))
.expectNextCount(2 * count)
.verifyComplete();
}
@Test
public void threadBoundaryPreventsInvalidFusionMap() {
Sinks.Many<Integer> up =
Sinks.many().unsafe().unicast().onBackpressureBuffer(Queues.<Integer>get(2).get());
AssertSubscriber<String> ts = AssertSubscriber.create();
up.asFlux().map(v -> Thread.currentThread()
.getName())
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
up.emitNext(1);
up.emitComplete();
ts.await(Duration.ofSeconds(5));
ts.assertValues(Thread.currentThread()
.getName())
.assertNoError()
.assertComplete();
}
@Test
public void threadBoundaryPreventsInvalidFusionFilter() {
Sinks.Many<Integer> up =
Sinks.many().unsafe().unicast().onBackpressureBuffer(Queues.<Integer>get(2).get());
String s = Thread.currentThread()
.getName();
AssertSubscriber<Integer> ts = AssertSubscriber.create();
up.asFlux().filter(v -> s.equals(Thread.currentThread()
.getName()))
.publishOn(Schedulers.fromExecutorService(exec))
.subscribe(ts);
up.emitNext(1);
up.emitComplete();
ts.await(Duration.ofSeconds(5));
ts.assertValues(1)
.assertNoError()
.assertComplete();
}
@Test
public void crossRangePerfDefault() {
AssertSubscriber<Integer> ts = AssertSubscriber.create();
Scheduler scheduler = Schedulers.fromExecutorService(exec);
int count = 1000;
Flux<Integer> source = Flux.range(1, count)
.flatMap(v -> Flux.range(v, 2), false, 128, 32);
source.publishOn(scheduler)
.subscribe(ts);
if (!ts.await(Duration.ofSeconds(10))
.isTerminated()) {
ts.cancel();
}
ts.assertValueCount(count * 2)
.assertNoError()
.assertComplete();
}
@Test
public void limitRate() {
List<Long> upstreamRequests = new LinkedList<>();
List<Long> downstreamRequests = new LinkedList<>();
Flux<Integer> source = Flux.range(1, 400)
.doOnRequest(upstreamRequests::add)
.doOnRequest(r -> System.out.println(
"upstream request of " + r))
.limitRate(40)
.doOnRequest(downstreamRequests::add)
.doOnRequest(r -> System.out.println(
"downstream request of " + r));
AssertSubscriber<Integer> ts = AssertSubscriber.create(400);
source.subscribe(ts);
ts.await(Duration.ofMillis(100))
.assertComplete();
assertThat(downstreamRequests.size()).as("downstream number of requests").isOne();
assertThat(downstreamRequests.get(0)).as("unique request").isEqualTo(400L);
long total = 0L;
for (Long requested : upstreamRequests) {
total += requested;
//30 is the optimization that eagerly prefetches when 3/4 of the request has been served
assertThat(requested).as("rate limit check").isIn(40L, 30L);
}
assertThat(total).as("upstream total request")
.isGreaterThanOrEqualTo(400L)
.isLessThan(440L);
}
@Test
public void limitRateWithCloseLowTide() {
List<Long> rebatchedRequest = Collections.synchronizedList(new ArrayList<>());
final Flux<Integer> test = Flux
.range(1, 14)
.hide()
.doOnRequest(rebatchedRequest::add)
.limitRate(10,8);
StepVerifier.create(test, 14)
.expectNextCount(14)
.verifyComplete();
assertThat(rebatchedRequest)
.containsExactly(10L, 8L);
}
@Test
public void limitRateWithVeryLowTide() {
List<Long> rebatchedRequest = Collections.synchronizedList(new ArrayList<>());
final Flux<Integer> test = Flux
.range(1, 14)
.hide()
.doOnRequest(rebatchedRequest::add)
.limitRate(10,2);
StepVerifier.create(test, 14)
.expectNextCount(14)
.verifyComplete();
assertThat(rebatchedRequest)
.containsExactly(10L, 2L, 2L, 2L, 2L, 2L, 2L, 2L);
}
@Test(timeout = 5000)
public void rejectedExecutionExceptionOnDataSignalExecutor()
throws InterruptedException {
final AtomicReference<Throwable> throwableInOnOperatorError =
new AtomicReference<>();
final AtomicReference<Object> dataInOnOperatorError = new AtomicReference<>();
try {
CountDownLatch hookLatch = new CountDownLatch(1);
Hooks.onOperatorError((t, d) -> {
throwableInOnOperatorError.set(t);
dataInOnOperatorError.set(d);
hookLatch.countDown();
return t;
});
ExecutorService executor = newCachedThreadPool();
CountDownLatch latch = new CountDownLatch(1);
AssertSubscriber<Integer> assertSubscriber = new AssertSubscriber<>();
Flux.range(0, 5)
.publishOn(fromExecutorService(executor))
.doOnNext(s -> {
try {
latch.await();
}
catch (InterruptedException e) {
}
})
.publishOn(fromExecutor(executor))
.subscribe(assertSubscriber);
executor.shutdownNow();
assertSubscriber.assertNoValues()
.assertNoError()
.assertNotComplete();
hookLatch.await();
assertThat(throwableInOnOperatorError.get()).isInstanceOf(RejectedExecutionException.class);
assertThat(dataInOnOperatorError).hasValue(0);
}
finally {
Hooks.resetOnOperatorError();
}
}
@Test
@Ignore //Fix or deprecate fromExecutor, this test might randomly hang on CI
public void rejectedExecutionExceptionOnErrorSignalExecutor()
throws InterruptedException {
Exception exception = new IllegalStateException();
final AtomicReference<Throwable> throwableInOnOperatorError =
new AtomicReference<>();
final AtomicReference<Object> dataInOnOperatorError = new AtomicReference<>();
try {
CountDownLatch hookLatch = new CountDownLatch(2);
Hooks.onOperatorError((t, d) -> {
throwableInOnOperatorError.set(t);
dataInOnOperatorError.set(d);
hookLatch.countDown();
return t;
});
ExecutorService executor = newCachedThreadPool();
CountDownLatch latch = new CountDownLatch(1);
AssertSubscriber<Integer> assertSubscriber = new AssertSubscriber<>();
Flux.range(0, 5)
.publishOn(fromExecutorService(executor))
.doOnNext(s -> {
try {
latch.await();
}
catch (InterruptedException e) {
throw Exceptions.propagate(exception);
}
})
.publishOn(fromExecutor(executor))
.subscribe(assertSubscriber);
executor.shutdownNow();
assertSubscriber.assertNoValues()
.assertNoError()
.assertNotComplete();
hookLatch.await();
assertThat(throwableInOnOperatorError.get()).isInstanceOf(RejectedExecutionException.class);
assertThat(throwableInOnOperatorError.get().getSuppressed()[0]).isSameAs(exception);
}
finally {
Hooks.resetOnOperatorError();
}
}
@Test(timeout = 5000)
@Ignore
public void rejectedExecutionExceptionOnDataSignalExecutorService()
throws InterruptedException {
CountDownLatch hookLatch = new CountDownLatch(1);
Hooks.onOperatorError((t, d) -> {
assertThat(t).isInstanceOf(RejectedExecutionException.class);
assertThat(d).isNotNull();
hookLatch.countDown();
return t;
});
try {
ExecutorService executor = newCachedThreadPool();
StepVerifier.create(Flux.range(0, 5)
.log()
.publishOn(Schedulers.boundedElastic())
.doOnRequest(n -> executor.shutdownNow())
.publishOn(fromExecutorService(executor))
.doOnNext(this::infiniteBlock))
.then(() -> {
try {
hookLatch.await();
}
catch (InterruptedException e) {
}
})
.thenCancel()
.verify();
}
finally {
Hooks.resetOnOperatorError();
}
}
void infiniteBlock(Integer t) {
try {
new CountDownLatch(1).await();
}
catch (InterruptedException e) {
}
}
@Test
public void rejectedExecutionExceptionOnErrorSignalExecutorService() {
Exception exception = new IllegalStateException();
ExecutorService executor = newCachedThreadPool();
CountDownLatch latch = new CountDownLatch(1);
final Flux<Integer> flux = Flux.range(0, 5)
.publishOn(fromExecutorService(executor))
.doOnNext(s -> {
try {
latch.await();
}
catch (InterruptedException e) {
throw Exceptions.propagate(exception);
}
})
.publishOn(fromExecutorService(executor));
StepVerifier.create(flux, 0)
.expectSubscription()
.then(executor::shutdownNow)
.expectNextCount(0)
.expectErrorMatches(throwable ->
throwable instanceof RejectedExecutionException &&
throwable.getSuppressed()[0] == exception)
.verify(Duration.ofSeconds(5));
}
/**
* See #294 the consumer received more or less calls than expected Better reproducible
* with big thread pools, e.g. 128 threads
*
* @throws InterruptedException on interrupt
*/
@Test
public void mapNotifiesOnce() throws InterruptedException {
final int COUNT = 10000;
final Object internalLock = new Object();
final Object consumerLock = new Object();
final CountDownLatch internalLatch = new CountDownLatch(COUNT);
final CountDownLatch consumerLatch = new CountDownLatch(COUNT);
final AtomicInteger internalCounter = new AtomicInteger(0);
final AtomicInteger consumerCounter = new AtomicInteger(0);
final ConcurrentHashMap<Object, Long> seenInternal = new ConcurrentHashMap<>();
final ConcurrentHashMap<Object, Long> seenConsumer = new ConcurrentHashMap<>();
Sinks.Many<Integer> s = Sinks.many().multicast().onBackpressureBuffer();
Flux<Integer> d = s.asFlux();
/*Disposable c = */
d.publishOn(Schedulers.parallel())
.parallel(8)
.groups()
.subscribe(stream -> stream.publishOn(Schedulers.parallel())
.map(o -> {
synchronized (internalLock) {
internalCounter.incrementAndGet();
long curThreadId = Thread.currentThread()
.getId();
Long prevThreadId =
seenInternal.put(o, curThreadId);
if (prevThreadId != null) {
fail(String.format(
"The object %d has already been seen internally on the thread %d, current thread %d",
o,
prevThreadId,
curThreadId));
}
internalLatch.countDown();
}
return -o;
})
.subscribe(o -> {
synchronized (consumerLock) {
consumerCounter.incrementAndGet();
long curThreadId = Thread.currentThread()
.getId();
Long prevThreadId =
seenConsumer.put(o, curThreadId);
if (prevThreadId != null) {
fail(String.format(
"The object %d has already been seen by the consumer on the thread %d, current thread %d",
o,
prevThreadId,
curThreadId));
}
consumerLatch.countDown();
}
}));
final long start = System.currentTimeMillis();
for (int i = 0; i < COUNT; i++) {
long busyLoops = 0;
while (s.tryEmitNext(i).hasFailed()) {
busyLoops++;
if (busyLoops % 5000 == 0 && System.currentTimeMillis() - start >= 10_0000) {
throw new RuntimeException("Busy loop timed out");
}
}
}
internalLatch.await(5, TimeUnit.SECONDS);
assertThat(internalCounter).as("after 5s").hasValue(COUNT);
consumerLatch.await(5, TimeUnit.SECONDS);
assertThat(internalCounter).as("after 10s").hasValue(COUNT);
}
@Test
public void mapManyFlushesAllValuesThoroughly() throws InterruptedException {
int items = 1000;
CountDownLatch latch = new CountDownLatch(items);
Random random = ThreadLocalRandom.current();
Sinks.Many<String> s = Sinks.many().multicast().onBackpressureBuffer();
Flux<String> d = s.asFlux();
Flux<Integer> tasks = d.publishOn(Schedulers.parallel())
.parallel(8)
.groups()
.flatMap(stream -> stream.publishOn(Schedulers.parallel())
.map((String str) -> {
try {
Thread.sleep(random.nextInt(
10));
}
catch (InterruptedException e) {
Thread.currentThread()
.interrupt();
}
return Integer.parseInt(str);
}));
/* Disposable tail =*/
tasks.subscribe(i -> {
latch.countDown();
});
final long start = System.currentTimeMillis();
for (int i = 1; i <= items; i++) {
long busyLoops = 0;
while (s.tryEmitNext(String.valueOf(i)).hasFailed()) {
busyLoops++;
if (busyLoops % 5000 == 0 && System.currentTimeMillis() - start >= 10_0000) {
throw new RuntimeException("Busy loop timed out");
}
}
}
latch.await(15, TimeUnit.SECONDS);
assertThat(latch.getCount())
.withFailMessage("%d of %d items were not counted down", latch.getCount(), items)
.isZero();
}
@Test
public void callablePath() {
StepVerifier.create(Mono.fromCallable(() -> "test")
.flux()
.publishOn(Schedulers.immediate()))
.expectNext("test")
.verifyComplete();
StepVerifier.create(Mono.fromCallable(() -> {
throw new Exception("test");
})
.flux()
.publishOn(Schedulers.immediate()))
.verifyErrorMessage("test");
StepVerifier.create(Mono.fromCallable(() -> null)
.flux()
.publishOn(Schedulers.immediate()))
.verifyComplete();
}
@Test
public void scanOperator(){
Flux<Integer> source = Flux.just(1);
Scheduler scheduler = Schedulers.immediate();
FluxPublishOn<Integer> test = new FluxPublishOn<>(source, scheduler, false, 3, 4, Queues.one());
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(source);
assertThat(test.scan(PREFETCH)).isEqualTo(3);
assertThat(test.scan(RUN_ON)).isSameAs(scheduler);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(RunStyle.ASYNC);
}
@Test
public void scanSubscriber() throws InterruptedException {
CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
FluxPublishOn.PublishOnSubscriber<Integer> test = new FluxPublishOn.PublishOnSubscriber<>(actual,
Schedulers.single(), Schedulers.single().createWorker(), true, 123, 123, Queues.unbounded());
Subscription parent = Operators.emptySubscription();
test.onSubscribe(parent);
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
assertThat(test.scan(Scannable.Attr.DELAY_ERROR)).isTrue();
assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(123);
test.requested = 35;
assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(35L);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(RunStyle.ASYNC);
assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
test.onError(new IllegalStateException("boom"));
assertThat(test.scan(Scannable.Attr.ERROR)).hasMessage("boom");
assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
test.cancel();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
//once cancelled, there shouldn't be any draining left
// => better place to test that BUFFERED reflects the size of the queue
Thread.sleep(50); //"hiccup" to ensure cancellation / draining is done
test.queue.add(1);
test.queue.add(1);
assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(2);
}
@Test
public void scanConditionalSubscriber() {
@SuppressWarnings("unchecked")
Fuseable.ConditionalSubscriber<Integer> actual = Mockito.mock(MockUtils.TestScannableConditionalSubscriber.class);
FluxPublishOn.PublishOnConditionalSubscriber<Integer> test =
new FluxPublishOn.PublishOnConditionalSubscriber<>(actual, Schedulers.single(),
Schedulers.single().createWorker(), true, 123, 123, Queues.unbounded());
Subscription parent = Operators.emptySubscription();
test.onSubscribe(parent);
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
assertThat(test.scan(Scannable.Attr.DELAY_ERROR)).isTrue();
assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(123);
test.requested = 35;
assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(35L);
test.queue.add(1);
assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(1);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(RunStyle.ASYNC);
assertThat(test.scan(Scannable.Attr.ERROR)).isNull();
assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
test.onError(new IllegalStateException("boom"));
assertThat(test.scan(Scannable.Attr.ERROR)).hasMessage("boom");
assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
test.cancel();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
}
//see https://github.com/reactor/reactor-core/issues/767
@Test
public void publishOnAsyncDetection() {
Publisher<String> a = Flux.just("a");
Publisher<String> b = Mono.just("b");
Flux<Tuple2<String, String>> flux =
Flux.from(a)
.flatMap(value -> Mono.just(value)
.zipWith(Mono.from(b)))
.publishOn(Schedulers.single());
StepVerifier.create(flux)
.expectFusion(Fuseable.ASYNC)
.assertNext(tuple -> {
assertThat(tuple.getT1()).isEqualTo("a");
assertThat(tuple.getT2()).isEqualTo("b");
})
.verifyComplete();
}
//see https://github.com/reactor/reactor-core/issues/767
@Test
public void publishOnAsyncDetectionConditional() {
Publisher<String> a = Flux.just("a");
Publisher<String> b = Mono.just("b");
Flux<Tuple2<String, String>> flux =
Flux.from(a)
.flatMap(value -> Mono.just(value)
.zipWith(Mono.from(b)))
.publishOn(Schedulers.single())
.filter(t -> true);
StepVerifier.create(flux)
.expectFusion(Fuseable.ASYNC)
.assertNext(tuple -> {
assertThat(tuple.getT1()).isEqualTo("a");
assertThat(tuple.getT2()).isEqualTo("b");
})
.verifyComplete();
}
@Test
public void limitRateDisabledLowTide() throws InterruptedException {
LongAdder request = new LongAdder();
CountDownLatch latch = new CountDownLatch(1);
Flux.range(1, 99).hide()
.doOnRequest(request::add)
.limitRate(10, 0)
.subscribe(new BaseSubscriber<Integer>() {
@Override
protected void hookOnSubscribe(Subscription subscription) {
request(100);
}
@Override
protected void hookFinally(SignalType type) {
latch.countDown();
}
});
assertThat(latch.await(1, TimeUnit.SECONDS)).as("took less than 1s").isTrue();
assertThat(request.sum()).as("request not compounded").isEqualTo(100L);
}
private static class FailNullWorkerScheduler implements Scheduler {
@Override
public Disposable schedule(Runnable task) {
throw Exceptions.failWithRejected();
}
@Override
@Nullable
public Worker createWorker() {
return null;
}
}
private static class RejectingWorkerScheduler implements Scheduler {
final boolean isSchedulerTerminated;
final boolean isWorkerTerminated;
RejectingWorkerScheduler(boolean isSchedulerTerminated,
boolean isWorkerTerminated) {
this.isSchedulerTerminated = isSchedulerTerminated;
this.isWorkerTerminated = isWorkerTerminated;
}
@Override
public Disposable schedule(Runnable task) {
throw Exceptions.failWithRejected();
}
@Override
public boolean isDisposed() {
return isSchedulerTerminated;
}
@Override
public Worker createWorker() {
return new Worker() {
@Override
public Disposable schedule(Runnable task) {
throw Exceptions.failWithRejected();
}
@Override
public void dispose() {
}
@Override
public boolean isDisposed() {
return isWorkerTerminated;
}
};
}
}
private class FailWorkerScheduler implements Scheduler {
@Override
public Disposable schedule(Runnable task) {
throw Exceptions.failWithRejected();
}
@Override
public Worker createWorker() {
throw exception();
}
}
@Test
public void scanRunOn() {
Scannable publishOnScannable = Scannable.from(
Flux.just(1).hide()
.publishOn(Schedulers.boundedElastic())
);
Scannable runOnScannable = publishOnScannable.scan(Scannable.Attr.RUN_ON);
assertThat(runOnScannable).isNotNull()
.matches(Scannable::isScanAvailable, "isScanAvailable");
System.out.println(runOnScannable + " isScannable " + runOnScannable.isScanAvailable());
System.out.println(runOnScannable.scan(Scannable.Attr.NAME));
runOnScannable.parents().forEach(System.out::println);
System.out.println(runOnScannable.scan(Scannable.Attr.BUFFERED));
}
}
|
java
|
{
"vorgangId": "150314",
"VORGANG": {
"WAHLPERIODE": "12",
"VORGANGSTYP": "Kleine Anfrage",
"TITEL": "Der Parlamentarische Staatssekretär Eduard Lintner, die \"Lüge von der Kriegsschuld\" und der \"Kampf gegen die Umerzieher\" (G-SIG: 12011295)",
"INITIATIVE": "Gruppe der PDS/LL",
"AKTUELLER_STAND": "Beantwortet",
"SIGNATUR": "",
"GESTA_ORDNUNGSNUMMER": "",
"WICHTIGE_DRUCKSACHE": [
{
"DRS_HERAUSGEBER": "BT",
"DRS_NUMMER": "12/4395",
"DRS_TYP": "Kleine Anfrage",
"DRS_LINK": "http://dipbt.bundestag.de:80/dip21/btd/12/043/1204395.pdf"
},
{
"DRS_HERAUSGEBER": "BT",
"DRS_NUMMER": "12/4545",
"DRS_TYP": "Antwort",
"DRS_LINK": "http://dipbt.bundestag.de:80/dip21/btd/12/045/1204545.pdf"
}
],
"EU_DOK_NR": "",
"SACHGEBIET": "Innere Sicherheit",
"SCHLAGWORT": [
"Der Schlesier",
"Innere Sicherheit",
"Kriegsfolgen",
{
"_fundstelle": "true",
"__cdata": "Lintner, Eduard"
},
"Rechtsextremismus",
"Weltkrieg"
],
"ABSTRAKT": "Rechtsextremistische Tendenzen in der Wochenzeitung \"Der Schlesier\", insbesondere Thesen zur \"Kriegsschuldlüge\" und zur \"Umerziehung\", Befangenheit und mangelnde Sorgfalt des Parlamentarischen Staatssekretärs Eduard Lintner bei der Beantwortung von Anfragen zum Rechtsextremismus, zu Vertriebenenverbänden und -zeitungen "
},
"VORGANGSABLAUF": {
"VORGANGSPOSITION": [
{
"ZUORDNUNG": "BT",
"URHEBER": "Kleine Anfrage, Urheber : Gruppe der PDS/LL ",
"FUNDSTELLE": "12.02.1993 - BT-Drucksache 12/4395",
"FUNDSTELLE_LINK": "http://dipbt.bundestag.de:80/dip21/btd/12/043/1204395.pdf",
"PERSOENLICHER_URHEBER": {
"VORNAME": "Ulla",
"NACHNAME": "Jelpke",
"FUNKTION": "MdB",
"FRAKTION": "PDS/LL",
"AKTIVITAETSART": "Kleine Anfrage"
}
},
{
"ZUORDNUNG": "BT",
"URHEBER": "Antwort, Urheber : Bundesregierung, Bundesministerium des Innern (federführend)",
"FUNDSTELLE": "10.03.1993 - BT-Drucksache 12/4545",
"FUNDSTELLE_LINK": "http://dipbt.bundestag.de:80/dip21/btd/12/045/1204545.pdf"
}
]
}
}
|
json
|
'use strict';
const text = (s = '') => ({
line: a => text(`${s}\n${a}`),
toString: () => s
});
// Usage
const txt = text('line1')
.line('line2')
.line('line3')
.line('line4');
console.log(`${txt}`);
|
javascript
|
<reponame>shakahl/diablo2-1
import { createHash } from 'crypto';
import { promises as fs } from 'fs';
import { Mpq } from '../index';
const MpqFileName = './patch_d2.mpq';
async function main(): Promise<void> {
console.time('ReadMpq');
const fileData = await fs.readFile(MpqFileName);
const mpqFileHash = createHash('sha256').update(fileData).digest('base64');
const mpq = Mpq.load(fileData);
console.timeEnd('ReadMpq');
console.log('LoadedMPQ', MpqFileName, { hash: mpqFileHash });
const files = [
'data/global/excel/Armor.bin',
'data/global/excel/Weapons.bin',
'data/global/excel/MonStats.bin',
'data/global/excel/MonStats2.bin',
'data/global/excel/MonStats2.bin',
'data/local/LNG/ENG/string.tbl',
'data/local/LNG/ENG/expansionstring.tbl',
'data/local/LNG/ENG/patchstring.tbl',
];
for (const fileName of files) {
const data = await mpq.extract(fileName);
if (data == null) continue;
const hash = createHash('sha3-224').update(data).digest('hex');
console.log(fileName, data.length, hash);
}
}
main().catch((e) => console.log(e));
|
typescript
|
Candidates who have qualified for the exam can download their admit cards on the official website mpsconline.gov.in.
The Maharashtra Public Service Commission (MPSC) has released the admit cards for the upcoming Group B services Main exam 2023. Candidates who have qualified for the exam can download their admit cards on the official website mpsc.gov.in or mpsconline.gov.in.
According to the notification, the Group B services Main exam is scheduled to be conducted on November 5, 2023. The recruitment drive aims to fill up a total of 756 Non-Gazetted vacancies in the MPSC. The Group B services Paper II was conducted on October 22 for some candidates.
Here’s the admit card notification by MPSC.
For more details, candidates are advised to visit the official website here.
|
english
|
{
"author": {
"id": "t2_1e2zw06f",
"name": "rootstemmultimedia"
},
"date": {
"day": 1540252800,
"full": 1540300583,
"month": 1538352000,
"week": 1540080000
},
"id": "t3_9qov20",
"picture": {
"filesize": 83000,
"fullUrl": "https://preview.redd.it/2mxvwnnxqxt11.jpg?auto=webp&s=d7083f814b7e5bf342ffc3d24c6cf8c4fc904f33",
"hash": "8cc4d5369d",
"height": 519,
"lqip": "data:image/jpg;base64,/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAANABADASIAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAABQQI/8QAIhAAAgEEAgIDAQAAAAAAAAAAAQMCBAURIQAGEjETFBYi/8QAFAEBAAAAAAAAAAAAAAAAAAAABf/EABwRAAEEAwEAAAAAAAAAAAAAAAIAARExAwQygf/aAAwDAQACEQMRAD8AK7AbXe75UUnX3VDbslU4CpqFiMKho1KZmMeOs49AkD1yGqXan9WdQyYf1CpFklwafrMaMAfznxMpADe9j3vmiY2u2saxsrbRfIwmU5BMQZEjGTrgNy6b1114Vcp2pIrF4IlAmIJHomI0eAjssNTCaMCy9PL14v/Z",
"url": "https://preview.redd.it/2mxvwnnxqxt11.jpg?width=640&crop=smart&auto=webp&s=94a3eb91c6dd6887c920798659b05ecbe8762dbd",
"width": 640
},
"score": {
"comments": 9,
"downs": 0,
"ratio": 0.98,
"ups": 114,
"value": 114
},
"subreddit": {
"id": "t5_2xy5e",
"name": "TerrainBuilding"
},
"tags": [],
"title": "Some terrain for Adeptus Titanicus. Made by my buddy <NAME> and painted by me.",
"url": "https://www.reddit.com/r/TerrainBuilding/comments/9qov20/some_terrain_for_adeptus_titanicus_made_by_my/"
}
|
json
|
table {
@apply min-w-full;
@apply border-separate !important;
border-spacing: 0;
}
th {
@apply font-medium;
@apply text-secondary;
@apply text-left;
@apply text-sm;
@apply px-2;
@apply py-1;
@apply border-t;
@apply border-b;
@apply bg-secondary;
}
th:first-child {
@apply border-l;
@apply rounded-l;
}
th:last-child {
@apply border-r;
@apply rounded-r;
}
td {
@apply text-left;
@apply px-2;
@apply py-2;
@apply border-b;
}
tr.no-border td {
@apply border-b-0;
}
dl {
@apply grid;
@apply grid-cols-3;
}
dt {
@apply py-1.5;
@apply font-medium;
@apply border-b;
@apply text-secondary;
@apply col-span-1;
}
dd {
@apply py-1.5;
@apply border-b;
@apply col-span-2;
}
.table-toolbar {
@apply sm:flex items-center justify-between;
@apply px-2 py-1;
@apply border;
@apply -mb-px;
@apply rounded-t;
@apply text-sm;
}
.table-toolbar ~ table {
th:first-child {
@apply rounded-tl-none;
@apply rounded-bl;
}
th:last-child {
@apply rounded-tr-none;
@apply rounded-br;
}
}
|
css
|
Titane, or the titanium of the title, refers to the metallic plate fitted in Alexia’s head after a car accident. Director Julia Ducournau doesn’t waste time on the tragedy. There is blood splattered on the back window. We see Alexia in surgery and then in recovery. Look out for unusual behaviour, the neurosurgeon cautions Alexia’s parents.
Once recovered and discharged from hospital, Alexia’s most intimate reunion is not with her parents, but with their car.
Years later, Alexia (Agathe Rousselle) is an exotic dancer performing at a motor show. Forced to go on the run after a series of events, Alexia reinvents herself by inflicting unimaginable pain on her body. This brings her in contact with fireman Vincent (Vincent Lindon).
Vincent’s emotional condition is fragile, in denial about a painful truth or consciously overlooking it to fill the chasm in his life. In turn, Alexia is experiencing multiple changes and new feelings. The progression of their bond, powered by Lindon and Rouselle’s performances, is the movie’s beating heart. With few words, they convey the depth of their pain. Music and dance gives them moments of respite.
Titane’s now infamous sex scene takes place early on in the 109-minute movie, but that’s not what plays in your mind after the end credits have rolled. You take away thoughts on family drama, the hand life deals and how love – of all kinds – can be found in the most unexpected places.
The French-language Titane, which won the Palme d’Or at Cannes in 2021, is out on MUBI. Ducournau, who has previously directed Raw, takes the less-is-more route. She chooses to be sketchy, outrageous and provocative while also exploring relatable themes, from found families to body horror and sexuality to modern fable. Just go along with the unexpected and judgment-free but sometimes shocking and often gory ride that is Titane.
|
english
|
<filename>tsconfig.json
{
"compilerOptions": {
// Brings in Promise and all es2015 extensions to TS
// TODO: Bringing in dom to quell URL issue, please remove if possible
"lib": [
"es2015",
"dom",
"es7"
],
"outDir": "dist",
// Emits types for others to consume
"declaration": true,
"declarationDir": "dist/types",
// Using commonjs here to play nice with node (imports not welcome here)
"module": "commonjs",
"target": "es6",
"moduleResolution": "node",
// Help TS understand node globals
"types": [
"node",
"jasmine"
],
// Let's allow `import`
"allowSyntheticDefaultImports": true,
// Don't let sneaky null/undefined through
"strictNullChecks": true,
// Yes plz
"sourceMap": true,
// Don't update JS dist with failing TS src
"noEmitOnError": true
},
"include": [
"src"
]
}
|
json
|
<filename>_data/cask/fedora-media-writer.json<gh_stars>1-10
{
"token": "<PASSWORD>",
"full_token": "<PASSWORD>",
"tap": "homebrew/cask",
"name": [
"Fedora Media Writer"
],
"desc": "Tool to write Fedora images to portable media files",
"homepage": "https://docs.fedoraproject.org/en-US/quick-docs/creating-and-using-a-live-installation-image/",
"url": "https://github.com/FedoraQt/MediaWriter/releases/download/4.2.0/FedoraMediaWriter-osx-4.2.0.unnotarized.dmg",
"appcast": "https://github.com/FedoraQt/MediaWriter/releases.atom",
"version": "4.2.0",
"installed": null,
"outdated": false,
"sha256": "182b0f0a357f2bdae299acdd7ea99c72a94f76fdf49958970c96ef14330858a1",
"artifacts": [
[
"Fedora Media Writer.app"
]
],
"caveats": null,
"depends_on": {
},
"conflicts_with": null,
"container": null,
"auto_updates": null
}
|
json
|
function testMe(cb) {
cb();
}
module.exports = testMe;
|
javascript
|
#!/usr/bin/env python3
"""Common library for working with numerical vectors and matrices.
This module provides functions for operating one-dimensional sequences
(vectors) and two-dimensional collections (matrices) of numbers. Examples
include calculating dot and cross products and finding the optimal assignment
in a cost matrix.
"""
import copy
from typing import Iterable, List, Optional, Sequence, Tuple
from common.typex import Coord, Matrix, T
def _try_assign_zeros(matrix: Matrix[int]) -> Sequence[Coord]:
"""Finds the most zeros possible in distinct rows and columns of a matrix.
Args:
matrix: A two-dimensional integer matrix.
Returns:
A sequence of integer tuples, each representing the row and column of a
zero value in ``matrix``, no two of which share the same row or column.
"""
# convert matrix to bipartite graph, with zeros indicating edges
edge_matrix = [[value == 0 for value in row] for row in matrix]
return max_bipartite_matching(edge_matrix)
def _try_bipartite_match(
edge_matrix: Matrix[bool],
row: int,
col_marked: List[bool],
col_assignments: List[int],
) -> bool:
"""Tries to assign a free column to a matrix row, reassigning as necessary.
Args:
edge_matrix: A boolean matrix indicating edges between rows and
columns. In order for column ``j`` to be assigned to row ``i``,
``edge_matrix[i][j]`` must be ``True``.
row: Index of the row to be assigned a free column.
col_marked: Aist of columns pending assignment in the current recursive
call stack.
col_assignments: An integer list of length ``len(edge_matrix[0])``,
where the value at each index ``i`` is the index of the column
assigned to row ``i``, or -1 if row ``i`` has no assigned column.
Returns:
``True`` if ``row`` was successfully assigned a free column, possibly
by reassigning columns to other rows in ``col_assignments``, or
``False`` otherwise.
"""
# try to match row to each column
for j in range(len(edge_matrix[0])):
# check if row can be matched with unmarked column
if edge_matrix[row][j] and not col_marked[j]:
col_marked[j] = True
# check if column is unmatched or can be re-matched with new row
if (
col_assignments[j] == -1 or
_try_bipartite_match(
edge_matrix,
col_assignments[j],
col_marked,
col_assignments,
)
):
col_assignments[j] = row
return True
# couldn't match row with any column
return False
def cross_product_3d(
p1: Sequence[float],
p2: Sequence[float],
) -> Tuple[float, float, float]:
"""Returns the cross product of two 3-dimensional points.
Args:
p1: A sequence of length 3, representing the coordinates of a 3D point.
p2: A second sequence of length 3, representing another 3D point.
Returns:
A tuple of three numbers, representing the cross product ``p1 x p2`` of
the two original points.
"""
# compute determinant of cross product matrix
prod_i = (p1[1] * p2[2]) - (p1[2] * p2[1])
prod_j = (p1[2] * p2[0]) - (p1[0] * p2[2])
prod_k = (p1[0] * p2[1]) - (p1[1] * p2[0])
return prod_i, prod_j, prod_k
def dot_product(u: Iterable[float], v: Iterable[float]) -> float:
"""Returns the dot product of vectors u and v."""
return sum(i * j for i, j in zip(u, v))
def flatten_matrix(matrix: Matrix[T]) -> Sequence[T]:
"""Builds a sequence from the elements of a matrix, in row-major order.
Args:
matrix: A two-dimensional matrix of values.
Returns:
A one-dimensional sequence of values taken from ``matrix``.
Specifically, if ``matrix`` has ``n`` rows and ``m`` columns, the
resulting sequence will have the form::
[
matrix[0][0], matrix[0][1], ..., matrix[0][m - 1],
matrix[1][0], matrix[1][1], ..., matrix[1][m - 1],
...,
matrix[n - 1][0], matrix[n - 1][1], ..., matrix[n - 1][m - 1]
]
"""
flat_matrix: List[T] = []
for row in matrix:
for value in row:
flat_matrix.append(value)
return flat_matrix
def make_spiral(
layers: int,
_matrix: Optional[Matrix[int]] = None,
_depth: int = 0
) -> Matrix[int]:
"""Constructs an integer spiral with a given number of layers.
Args:
layers: A positive integer number of layers.
Returns:
A spiral matrix formed by starting with 1 in the center and moving to
the right in a clockwise direction, incrementing the value of each
subsequent space by 1. The resulting matrix will have
``layers * 2 - 1`` rows and columns.
"""
# compute the dimension of one side of the spiral
side = layers * 2 - 1
# initialize the matrix that will hold the spiral
if _matrix is None:
_matrix = [[1 for _ in range(side)] for _ in range(side)]
# base case: a spiral with one layer will contain the number 1
if layers < 2:
return _matrix
side_min_1 = side - 1
value = side * side
# fill the top row of the spiral
for i in range(side_min_1):
_matrix[_depth][-1 - _depth - i] = value
value -= 1
# fill the left column of the spiral
for i in range(side_min_1):
_matrix[_depth + i][_depth] = value
value -= 1
# fill the bottom row of the spiral
for i in range(side_min_1):
_matrix[-1 - _depth][_depth + i] = value
value -= 1
# fill the right column of the spiral
for i in range(side_min_1):
_matrix[-1 - _depth - i][-1 - _depth] = value
value -= 1
# recurse to fill the inside of the spiral
return make_spiral(layers - 1, _matrix, _depth + 1)
def max_bipartite_matching(edge_matrix: Matrix[bool]) -> Sequence[Coord]:
"""Finds the edges in the maximum matching of a bipartite graph.
Args:
edge_matrix: A boolean matrix mapping vertices in partition ``V`` to
those in partition ``U``. ``edge_matrix[u][v]`` must be ``True`` if and
only if there is an edge between ``u`` and ``v``, where ``u`` is the
index of a vertex in ``U`` and ``v`` is the index of a vertex in ``V``.
Returns:
A sequence of matrix coordinates in the maximum matching of the
bipartite graph ``U + V``. Each coordinate is of the form ``(u, v)``,
with ``u`` and ``v`` defined as above.
"""
n = len(edge_matrix) # number of rows
m = len(edge_matrix[0]) # number of columns
# try to assign each row to a column
col_assignments: List[int] = [-1] * m
for i in range(n):
col_marked = [False] * m
_try_bipartite_match(edge_matrix, i, col_marked, col_assignments)
# convert to list of matched pairs and return
return [(i, j) for j, i in enumerate(col_assignments) if i != -1]
def minimum_line_cover(matrix: Matrix[int]) -> Sequence[Tuple[bool, int]]:
"""Returns a list of the fewest lines needed to cover all zeros in matrix.
Lines are given in the format (is_vertical, i), where is_vertical is a
boolean indicating whether the line is oriented vertically, and i is the
index of the row (if is_vertical = False) or column (if is_vertical = True)
in the matrix that would be covered by this line.
"""
# assign as many (row, col) pairs with zeros as possible
assignments = _try_assign_zeros(matrix)
# if all zeros assigned, n lines are needed
n = len(matrix)
if len(assignments) == n:
return [(False, i) for i in range(n)]
# convert to row assignment array
row_assignments: List[Optional[int]] = [None] * n
for i, j in assignments:
row_assignments[i] = j
# mark all unassigned rows
m = len(matrix[0])
row_marked = [False] * n
col_marked = [False] * m
new_marked_rows = []
for i, assigned_col in enumerate(row_assignments):
if assigned_col is None:
row_marked[i] = True
new_marked_rows.append(i)
while new_marked_rows:
# mark all unmarked columns with zeros in newly marked rows
for i in new_marked_rows:
for j in range(m):
if not col_marked[j] and matrix[i][j] == 0:
col_marked[j] = True
# mark all unmarked rows with assigned zeros in marked columns
new_marked_rows = []
for i in range(n):
if not row_marked[i]:
assignment = row_assignments[i]
assert assignment is not None
if col_marked[assignment]:
row_marked[i] = True
new_marked_rows.append(i)
# cover all unmarked rows and marked columns
lines = []
for i, marked in enumerate(row_marked):
if not marked:
lines.append((False, i))
for j, marked in enumerate(col_marked):
if marked:
lines.append((True, j))
return lines
def optimal_assignment(cost_matrix: Matrix[int]) -> Sequence[Coord]:
"""Assigns each row to a column of the square matrix cost_matrix so that
the sum of the cost values in the assigned positions is minimized.
Returns a list of matrix coordinates in the format (row, col).
"""
# make a deep copy so we don't change the input matrix
cost_matrix = copy.deepcopy(cost_matrix)
# Step 1: subtract the minimum element from each row
n = len(cost_matrix)
for i, row in enumerate(cost_matrix):
min_element = min(row)
for j in range(n):
cost_matrix[i][j] -= min_element
# Step 2: subtract the minimum element from each column
for j in range(n):
col = [cost_matrix[i][j] for i in range(n)]
min_element = min(col)
for i in range(n):
cost_matrix[i][j] -= min_element
# Step 3: cover zeros with minimum number of lines
lines = minimum_line_cover(cost_matrix)
# Step 4: subtract min uncovered from all uncovered & add to double-covered
while len(lines) < n:
# find rows and columns covered by lines
covered_rows = set()
covered_cols = set()
for is_vertical, index in lines:
if is_vertical:
covered_cols.add(index)
else:
covered_rows.add(index)
# search for min uncovered value
min_uncovered = None
for i, row in enumerate(cost_matrix):
if i in covered_rows:
continue
for j, value in enumerate(row):
if j in covered_cols:
continue
if min_uncovered is None or value < min_uncovered:
min_uncovered = value
assert min_uncovered is not None
# subtract and add min value to matrix entries as needed
for i in range(n):
for j in range(n):
if i not in covered_rows and j not in covered_cols:
cost_matrix[i][j] -= min_uncovered
elif i in covered_rows and j in covered_cols:
cost_matrix[i][j] += min_uncovered
# repeat steps 3-4 until n lines are needed to cover zeros
lines = minimum_line_cover(cost_matrix)
# now that a total assignment exists, find and return it
return _try_assign_zeros(cost_matrix)
|
python
|
streetlights = [
{
"_id": "5c33cb90633a6f0003bcb38b",
"latitude": 40.109356050955824,
"longitude": -88.23546712954632,
},
{
"_id": "5c33cb90633a6f0003bcb38c",
"latitude": 40.10956288950609,
"longitude": -88.23546931624688,
},
{
"_id": "5c33cb90633a6f0003bcb38d",
"latitude": 40.11072693111868,
"longitude": -88.23548184676547,
},
{
"_id": "5c33cb90633a6f0003bcb38e",
"latitude": 40.11052593366689,
"longitude": -88.23548345321224,
},
{
"_id": "5c33cb90633a6f0003bcb38f",
"latitude": 40.1105317123791,
"longitude": -88.23527189093869,
},
]
def get_streetlights():
return streetlights
|
python
|
// Copyright 2018 <NAME> <<EMAIL>>
// All rights reserved. MIT License.
type MessageCallback = (msg: ArrayBuffer) => void;
interface Deno {
recv(channel: string, cb: MessageCallback): void;
send(channel: string, msg: ArrayBuffer): null | ArrayBuffer;
print(x: string): void;
}
declare let deno: Deno;
|
typescript
|
<reponame>douglasbreyer/GAMES-2019-T2
{"name":null,"assets":"aoy4:pathy34:assets%2Fdata%2Fdata-goes-here.txty4:sizezy4:typey4:TEXTy2:idR1goR0y30:assets%2Fimages%2Fasteroid.pngR2i13244R3y5:IMAGER5R6goR0y24:assets%2Fimages%2Fbg.pngR2i15133R3R7R5R8goR0y28:assets%2Fimages%2Fbkgd_0.pngR2i1591171R3R7R5R9goR0y29:assets%2Fimages%2Fexplode.pngR2i16165R3R7R5R10goR0y26:assets%2Fimages%2Ffoto.pngR2i16331R3R7R5R11goR0y43:assets%2Fimages%2Fgame%2F01%20-%20final.pngR2i13239R3R7R5R12goR0y43:assets%2Fimages%2Fgame%2F02%20-%20final.pngR2i77133R3R7R5R13goR0y43:assets%2Fimages%2Fgame%2F03%20-%20final.pngR2i74840R3R7R5R14goR0y27:assets%2Fimages%2Fheart.pngR2i201R3R7R5R15goR0y36:assets%2Fimages%2Fimages-go-here.txtR2zR3R4R5R16goR0y27:assets%2Fimages%2Flazer.pngR2i3395R3R7R5R17goR0y29:assets%2Fimages%2Fmunicao.pngR2i3541R3R7R5R18goR0y26:assets%2Fimages%2Fship.pngR2i7683R3R7R5R19goR0y26:assets%2Fimages%2Fstar.pngR2i3094R3R7R5R20goR0y26:assets%2Fimages%2Funiv.pngR2i17161R3R7R5R21goR0y50:assets%2Fmusic%2Fmelodic_power_track_c64_style.oggR2i802467R3y5:SOUNDR5R22goR0y36:assets%2Fmusic%2Fmusic-goes-here.txtR2zR3R4R5R24goR0y32:assets%2Fsounds%2FDark-Intro.wavR2i14214990R3R23R5R25goR0y26:assets%2Fsounds%2Fdead.wavR2i101512R3R23R5R26goR0y27:assets%2Fsounds%2Ffundo.oggR2i5364758R3y5:MUSICR5R27goR0y27:assets%2Fsounds%2FINTRO.wavR2i5707940R3R23R5R29goR0y33:assets%2Fsounds%2Fitem_pickup.wavR2i46584R3R23R5R30goR0y27:assets%2Fsounds%2Flaser.wavR2i16784R3R23R5R31goR0y33:assets%2Fsounds%2Flife_pickup.wavR2i67952R3R23R5R32goR0y37:assets%2Fsounds%2FRetro_No%20hope.wavR2i2408718R3R23R5R33goR2i5794R3R23y9:classNamey31:__ASSET__flixel_sounds_beep_oggR5y26:flixel%2Fsounds%2Fbeep.ogggoR2i33629R3R23R34y33:__ASSET__flixel_sounds_flixel_oggR5y28:flixel%2Fsounds%2Fflixel.ogggoR2i15744R3y4:FONTR34y35:__ASSET__flixel_fonts_nokiafc22_ttfR5y30:flixel%2Ffonts%2Fnokiafc22.ttfgoR2i29724R3R39R34y36:__ASSET__flixel_fonts_monsterrat_ttfR5y31:flixel%2Ffonts%2Fmonsterrat.ttfgoR2i519R3R7R34y36:__ASSET__flixel_images_ui_button_pngR5y33:flixel%2Fimages%2Fui%2Fbutton.pnggoR2i3280R3R7R34y39:__ASSET__flixel_images_logo_default_pngR5y36:flixel%2Fimages%2Flogo%2Fdefault.pnggh","rootPath":null,"version":2,"libraryArgs":[],"libraryType":null}
|
json
|
<filename>interp/README.md
# Partial evaluation of initialization code in Go
For several reasons related to code size and memory consumption (see below), it
is best to try to evaluate as much initialization code at compile time as
possible and only run unknown expressions (e.g. external calls) at runtime. This
is in practice a partial evaluator of the `runtime.initAll` function, which
calls each package initializer.
It works by directly interpreting LLVM IR:
* Almost all operations work directly on constants, and are implemented using
the llvm.Const* set of functions that are evaluated directly.
* External function calls and some other operations (inline assembly, volatile
load, volatile store) are seen as having limited side effects. Limited in
the sense that it is known at compile time which globals it affects, which
then are marked 'dirty' (meaning, further operations on it must be done at
runtime). These operations are emitted directly in the `runtime.initAll`
function. Return values are also considered 'dirty'.
* Such 'dirty' objects and local values must be executed at runtime instead of
at compile time. This dirtyness propagates further through the IR, for
example storing a dirty local value to a global also makes the global dirty,
meaning that the global may not be read or written at compile time as it's
contents at that point during interpretation is unknown.
* There are some heuristics in place to avoid doing too much with dirty
values. For example, a branch based on a dirty local marks the whole
function itself as having side effect (as if it is an external function).
However, all globals it touches are still taken into account and when a call
is inserted in `runtime.initAll`, all globals it references are also marked
dirty.
* Heap allocation (`runtime.alloc`) is emulated by creating new objects. The
value in the allocation is the initializer of the global, the zero value is
the zero initializer.
* Stack allocation (`alloca`) is often emulated using a fake alloca object,
until the address of the alloca is taken in which case it is also created as
a real `alloca` in `runtime.initAll` and marked dirty. This may be necessary
when calling an external function with the given alloca as paramter.
## Why is this necessary?
A partial evaluator is hard to get right, so why go through all the trouble of
writing one?
The main reason is that the previous attempt wasn't complete and wasn't sound.
It simply tried to evaluate Go SSA directly, which was good but more difficult
than necessary. An IR based interpreter needs to understand fewer instructions
as the LLVM IR simply has less (complex) instructions than Go SSA. Also, LLVM
provides some useful tools like easily getting all uses of a function or global,
which Go SSA does not provide.
But why is it necessary at all? The answer is that globals with initializers are
much easier to optimize by LLVM than initialization code. Also, there are a few
other benefits:
* Dead globals are trivial to optimize away.
* Constant globals are easier to detect. Remember that Go does not have global
constants in the same sense as that C has them. Constants are useful because
they can be propagated and provide some opportunities for other
optimizations (like dead code elimination when branching on the contents of
a global).
* Constants are much more efficent on microcontrollers, as they can be
allocated in flash instead of RAM.
For more details, see [this section of the
documentation](https://tinygo.org/compiler-internals/differences-from-go/).
|
markdown
|
Your login session has expired. Please logout and login again.
Opinion: Was loaning out Paco Alcacer to Dortmund a mistake by the Barcelona board?
R U Next?
🏃🏻♀️ Sports (30+)
Edition:
|
english
|
{
"refs": [
{
"category": null,
"text": "<NAME>. 1980. Creolization, linguistic universals, natural semantax and the brain. In Day, <NAME>. (ed.), Issues in English creoles, 1–18. Heidelberg: Julius Groos.",
"html": "<p class=\"ReferencetitlesCxSpMiddle\" style=\"margin-top:0cm;margin-right:45.0pt;margin-bottom:0cm;margin-left:14.2pt;margin-bottom:.0001pt;text-indent:-14.2pt;line-height:150%\"><span><NAME>. 1980. Creolization, linguistic universals, natural semantax and the brain. In Day, <NAME>. (ed.), <i>Issues in English creoles</i>, 1–18. Heidelberg: Julius Groos.</span></p>",
"id": "bickerton1980",
"key": "Bickerton 1980"
},
{
"category": null,
"text": "Voorhoeve, Jan. 1957. The verbal system of Sranan. Lingua 6. 374–96.",
"html": "<p class=\"ReferencetitlesCxSpMiddle\" style=\"margin-top:0cm;margin-right:45.0pt;margin-bottom:0cm;margin-left:14.2pt;margin-bottom:.0001pt;text-indent:-14.2pt;line-height:150%\"><span>Voorhoeve, Jan. 1957. The verbal system of Sranan. <i>Lingua</i> 6. 374–96.</span></p>",
"id": "voorhoeve1957",
"key": "Voorhoeve 1957"
}
],
"outline": [
[
"1. Introduction",
"section-1introduction"
],
[
"2. The values",
"section-2thevalues"
],
[
"3. Distribution",
"section-3distribution"
]
],
"authors": []
}
|
json
|
<filename>package.json<gh_stars>1-10
{
"name": "electron-updater-channels",
"version": "0.0.1",
"main": "main.js",
"repository": "<EMAIL>:borisbutenko/electron-updater-channels.git",
"author": "borisbutenko <<EMAIL>>",
"license": "MIT",
"private": false,
"keywords": [
"Electron",
"auto updater",
"channels",
"start",
"example",
"tutorial",
"demo"
],
"scripts": {
"serve": "node server",
"dev": "cross-env NODE_ENV=development electron .",
"dist": "yarn dist:stable",
"dist:stable": "electron-builder --x64 --linux --config config/stable.json",
"dist:beta": "electron-builder --x64 --linux --config config/beta.json"
},
"devDependencies": {
"cross-env": "^5.2.0",
"electron": "^4.1.3",
"electron-builder": "^20.39.0",
"eslint": "^5.16.0",
"eslint-config-standard": "^12.0.0",
"eslint-plugin-import": "^2.16.0",
"eslint-plugin-node": "^8.0.1",
"eslint-plugin-promise": "^4.1.1",
"eslint-plugin-standard": "^4.0.0"
},
"dependencies": {
"electron-log": "^3.0.5",
"electron-updater": "^4.0.6",
"express": "^4.16.4"
}
}
|
json
|
export default function renderTime(hours, minutes) {
return ("" + hours).padStart(2, "0") + ":" + ("" + minutes).padStart(2, "0");
}
|
javascript
|
Vidyasagar has hit the big time in south Indian film music. He is a much more confident musician these days. That is what success does to your mental make up. The thing about Vidyasagar is that he has flair for both melody and mass numbers. He can adapt himself pretty well to the situation. And in Chandupottu, he shows why he is very important among the modern crop of music directors.
There is a rustic simplicity to this starting number. There is a catchy pastoral cadence the soft instrumentation of Vidyasagar. And they get the right backing from Vineeth Srinivasan. The singer gives the number the right tonal amplifications. And what emerges in the final analysis is a quiet melody.
Sujatha has a husky base and they get a good stage in this number as her humming sets the base for some tender tune. The male voice (Shahaas Amaan), thought nasally, has the right timbre to enunciate the compelling and serious lyrics. The orchestration is restrained. Though slightly old-fashioned, it suits the song the situation. All in all, an attractive ditty.
Janaki takes the centre stage after a long time. Though age has indeed left its mark on her voice, the essential surety of touch and the melody is still very much in place. The sweetness she comes out with makes you nostalgic for the days gone by. Vintage Janaki in this uncomplicated number.
It is not Cochi. It is Goa. We are talking about the rhythms and the drift. This typical Konkanicoastal song is very good on the ears. Sung with verve by Ranjith, the song is a fun one. But the melody and methods are serious. Good stuff.
Another number that seems to cast a spell on you with its softness. This theme bit reaches for your soul and deep beneath. Rohini's high-pitched vocalization is good.
Vidyasagar shows that class, as opposed to form, is permanent.
|
english
|
Every year, International Human Rights Day is celebrated on December 10, the theme for 2019 is Youth Standing Up for Human Rights.
By India Today Web Desk: International Human Rights Day is observed on December 10 annually. The main aim behind celebrating this day is to improve the physical, social, cultural and spiritual well being and welfare of the vulnerable group of people globally.
On this day the United Nations General Assembly adopted the Universal Declaration of Human Rights in 1948. However, on December 4, 1950, the United Nations General Assembly invited all its member states and other interested organisations to formally establish the Human Rights Day. Since then every year the member states of the United Nations and other countries observe December 10 as the 'Human Rights Day'.
In 1993, an autonomous public body, National Human Rights Commission (NHRC) of India, was established for the protection and promotion of human rights, which works on rights relating to life, liberty, equality and dignity of an individual.
UDHR is regarded as one of the world's most profound and far-reaching international agreements. It is an inalienable right which everyone is inherently entitled to as a human being regardless of race, colour, religion, sex, language, political or other opinions, national or social origin, property, birth or belong from other status.
According to the official website of the United Nations, today is the 71st anniversary of Universal Declaration of Human Rights and the theme of Human Rights Day 2019 is Youth Standing Up for Human Rights.
Eleanor Roosevelt once said "Where, after all, do universal human rights begin? In small places, close to home -- so close and so small that they cannot be seen on any maps of the world. [. . . ] Unless these rights have meaning there, they have little meaning anywhere. Without concerted citizen action to uphold them close to home, we shall look in vain for progress in the larger world. "
On this Human Rights Day, here are some popular quotes which you can use in conferences, debates, meetings and cultural events to discuss the human rights violations.
"A right delayed is a right denied. " - Martin Luther King, Jr.
"Until justice rolls down like water and righteousness like a mighty stream. " -Martin Luther King Jr.
"Everyone has the right to freedom of opinion and expression; this right includes freedom to hold opinions without interference and to seek, receive and impart information and ideas through any media and regardless of frontiers. "
-United Nations, Universal Declaration of Human Rights.
|
english
|
- Mahatma Gandhi v/s Nehru v/s Sardar Patel – Whom would you choose as your PM if they were alive today? Explain why and why not.
- If you are given a ticket to contest Lok Sabha elections by the Aam Aadmi Party from New Delhi, would you contest leaving behind your IAS dream? Give a reasoned explanation.
|
english
|
export const IntersectType = {
None: 0,
Parallel: 1,
Perpendicular: 2,
Collineation: 3,
}
export const Orientation = {
None: -1,
Common: 0,
Positive: 1,
Negative: 2,
Intersect: 3,
}
|
javascript
|
<gh_stars>0
{"version":"1.0","provider_name":"EstateGuru","provider_url":"https:\/\/estateguru.co","title":"P\u0101r\u0146em Kontroli P\u0101r Savu Finansi\u0101lo N\u0101kotni.","type":"rich","width":600,"height":338,"html":"<blockquote class=\"wp-embedded-content\"><a href=\"https:\/\/estateguru.co\/lv\/investor\/\">Investoriem<\/a><\/blockquote>\n<script type='text\/javascript'>\n<!--\/\/--><![CDATA[\/\/><!--\n\t\t\/*! This file is auto-generated *\/\n\t\t!function(d,l){\"use strict\";var e=!1,o=!1;if(l.querySelector)if(d.addEventListener)e=!0;if(d.wp=d.wp||{},!d.wp.receiveEmbedMessage)if(d.wp.receiveEmbedMessage=function(e){var t=e.data;if(t)if(t.secret||t.message||t.value)if(!\/[^a-zA-Z0-9]\/.test(t.secret)){var r,a,i,s,n,o=l.querySelectorAll('iframe[data-secret=\"'+t.secret+'\"]'),c=l.querySelectorAll('blockquote[data-secret=\"'+t.secret+'\"]');for(r=0;r<c.length;r++)c[r].style.display=\"none\";for(r=0;r<o.length;r++)if(a=o[r],e.source===a.contentWindow){if(a.removeAttribute(\"style\"),\"height\"===t.message){if(1e3<(i=parseInt(t.value,10)))i=1e3;else if(~~i<200)i=200;a.height=i}if(\"link\"===t.message)if(s=l.createElement(\"a\"),n=l.createElement(\"a\"),s.href=a.getAttribute(\"src\"),n.href=t.value,n.host===s.host)if(l.activeElement===a)d.top.location.href=t.value}}},e)d.addEventListener(\"message\",d.wp.receiveEmbedMessage,!1),l.addEventListener(\"DOMContentLoaded\",t,!1),d.addEventListener(\"load\",t,!1);function t(){if(!o){o=!0;var e,t,r,a,i=-1!==navigator.appVersion.indexOf(\"MSIE 10\"),s=!!navigator.userAgent.match(\/Trident.*rv:11\\.\/),n=l.querySelectorAll(\"iframe.wp-embedded-content\");for(t=0;t<n.length;t++){if(!(r=n[t]).getAttribute(\"data-secret\"))a=Math.random().toString(36).substr(2,10),r.src+=\"#?secret=\"+a,r.setAttribute(\"data-secret\",a);if(i||s)(e=r.cloneNode(!0)).removeAttribute(\"security\"),r.parentNode.replaceChild(e,r)}}}}(window,document);\n\/\/--><!]]>\n<\/script><iframe sandbox=\"allow-scripts\" security=\"restricted\" src=\"https:\/\/estateguru.co\/lv\/investor\/embed\/\" width=\"600\" height=\"338\" title=\"“Investoriem” — EstateGuru\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" class=\"wp-embedded-content\"><\/iframe>","description":"Jau vair\u0101k k\u0101 28 000 investoru no visas pasaules pelna iev\u0113rojamu atdevi, invest\u0113jot \u012bstermi\u0146a aizdevumos, kas nodro\u0161in\u0101ti ar vienu no dro\u0161\u0101kajiem akt\u012bviem - nekustamo \u012bpa\u0161umu Eirop\u0101. Uzs\u0101c savu ce\u013cu pret\u012b finansi\u0101lai br\u012bv\u012bbai s\u0101kot ar \u20ac50 un pelni l\u012bdz pat 12% gad\u0101.","thumbnail_url":"https:\/\/estateguru.co\/wp-content\/uploads\/2019\/09\/EG_FB_1200x630_LAT.png","thumbnail_width":1024,"thumbnail_height":538}
|
json
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import mineid
import pathlib
HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
setup(
name=mineid.__name__,
version=mineid.__version__,
description="A small Python library for getting Minecraft UUIDs.",
long_description=README,
long_description_content_type="text/markdown",
package_dir={"": "mineid"},
url="https://github.com/SomeHybrid/mineid",
classifiers=[
"Framework :: AsyncIO",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Programming Language :: Python",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Topic :: Internet :: WWW/HTTP"
]
)
|
python
|
What makes a great Android app? One that melds the virtual world with the real world in a fun or informative way. One app that does that in an impressive fashion is called JOYity and it comes from Zelfi, a German mobile gaming startup. JOYity uses the GPS in the Android phone to let you play games and go on adventures based on your location in the real world.
JOYity is a gaming platform in its own right. When you download the app you can play one of three games (YouCatch, Roads of San Francisco, City Race Munich) or design your own. In Roads of San Francisco, for instance, you have to go around the city picking up clues. When you get to a destination, a text or picture message tells you where to go next. It is a Scavenger Hunt with a story line. You can also design your own Scavenger Hunt games and play them with large groups of people.
Another game that comes with JOYity, YouCatch, is a version of Manhunt. Players in the same city sign up for a game. Everyone acts as both hunter and hunted at the same time. The game assigns you a player that you are hunting, while assigning you to someone else as a victim. Everyone’s location is periodically flashed on the map. When you get within 25 feet of your victim, you press the scrollball on the phone for the kill. But every time you press the button, your location is shown to all the other players as well. The last person standing wins.
Below are two video reviews from AppVee. The first is of JOYity itself and Roads of San Francisco. The second is of YouCatch, and it shows the game actually being played in Madison Square Park in New York City. AppVee was similarly impressed by JOYity, describing it as a “massive multiplayer trans-reality game.” For more Android video reviews, see our previous posts here and here. JOYity wasn’t on my original top-ten list of Android apps because it hadn’t hit teh Andrpoid market yet, but it would definitely be on that list now.
|
english
|
import { IColorComponent } from '../components/color/IColorComponent';
import { IGameObject } from '../gameobjects/IGameObject';
export declare function Brown<T extends IGameObject & IColorComponent>(gameObject: T, multiply?: boolean): T;
//# sourceMappingURL=Brown.d.ts.map
|
typescript
|
import { Container } from '@material-ui/core';
import { Button, Col, InputNumber, notification, Row } from 'antd';
import React from 'react';
import { useHistory } from 'react-router-dom';
import CartItem from './CartItem';
import './Cart.css';
import { currencyFormat } from '../../utils/NumberFormat';
import { useState } from 'react';
import { useEffect } from 'react';
import { MdAddShoppingCart } from 'react-icons/md';
import Axios from 'axios';
// let products = [
// {
// id: "1",
// name: "<NAME>",
// img:
// "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcR5wV-hb1HVpDFxiauwakIwb1S3InjIIS2ZhQ&usqp=CAU",
// price: 1000000,
// discount: 50,
// description:
// "Definitely annoying though. A simple check for Xcode installation and then an update during the OS update would be pretty simple to add. It's always something with these OS updates from Apple. You'd think they'd have figured it out by now",
// amount: 10,
// },
// {
// id: "2",
// name: "<NAME>",
// img:
// "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcR5wV-hb1HVpDFxiauwakIwb1S3InjIIS2ZhQ&usqp=CAU",
// price: 2000000,
// discount: 20,
// description:
// "Definitely annoying though. A simple check for Xcode installation and then an update during the OS update would be pretty simple to add. It's always something with these OS updates from Apple. You'd think they'd have figured it out by now",
// amount: 5,
// },
// ];
function Cart(props) {
const history = useHistory();
const token = localStorage.getItem('token');
let cart = JSON.parse(localStorage.getItem('cart'));
const [listProduct, setListProduct] = useState(cart === null ? [] : cart);
const [totalPrice, setTotalPrice] = useState(0);
let cartOrder = JSON.parse(localStorage.getItem('cart'));
useEffect(() => {
setTotalPrice(showTotalPrice());
}, [listProduct]);
const updateProduct = (id, amount) => {
console.log('pay ', id, ' ,quan ', amount);
let index = findIndex(id);
let tmp = listProduct;
tmp[index].amount = amount;
setListProduct(tmp);
localStorage.setItem('cart', JSON.stringify([...tmp]));
// listProduct[index].amount = amount ;
console.log('list ', listProduct);
setTotalPrice(showTotalPrice());
};
const showTotalPrice = () => {
let total = 0;
listProduct.map((item) => {
total =
total + item.price * item.amount * (1 - item.discount / 100);
});
return total;
};
const findIndex = (id) => {
let index = -1;
listProduct.map((item, i) => {
if (item.id === id) {
index = i;
}
});
return index;
};
const handleDelete = (id) => {
// console.log("id", id);
let tmp = listProduct.map((item) => item);
let index = findIndex(id);
if (index !== -1) {
tmp.splice(index, 1);
}
console.log('tmp ', tmp);
setListProduct(tmp);
localStorage.setItem('cart', JSON.stringify([...tmp]));
};
const onSubmit = () => {
let bill_items = [];
bill_items = listProduct.map((item) => {
return {
product_id: item.id,
amount: item.amount,
price: item.price,
};
});
let data = {
total_price: totalPrice,
discount: 0,
bill_note: null,
status: 1,
customer_id: localStorage.getItem('userId'),
number_of_product: listProduct.length,
bill_items: bill_items,
};
// console.log("submit ", data)
Axios.post(`/api/bill/upload`, data, {
headers: { Authorization: token },
})
.then((res) => {
console.log('res', res.data);
localStorage.removeItem('cart');
notification.success({
message: `Đặt hàng thành công!`,
style: {
borderRadius: 15,
backgroundColor: '#b7eb8f',
},
duration: 2,
placement: 'bottomRight',
});
history.push('/user');
})
.catch((err) => {
notification.error({
message: `Đặt hàng thất bại!`,
style: {
borderRadius: 15,
backgroundColor: '#fff2f0',
},
duration: 2,
placement: 'bottomRight',
});
});
};
return (
<Container>
<div className='cart'>
<h2>Giỏ hàng</h2>
<div className='cart-item'>
<Row className='detail-item'>
<Col span={2}>Sản phẩm</Col>
<Col span={4}> </Col>
<Col span={4}>Khuyến mãi</Col>
<Col span={4}>Giá </Col>
<Col span={4}>
<div>Số lượng</div>{' '}
</Col>
<Col span={4}>Số tiền</Col>
</Row>
</div>
{listProduct.map((product, index) => {
return (
<CartItem
key={index}
product={product}
updateProduct={updateProduct}
handleDelete={handleDelete}
/>
);
})}
<div className='pay'>
<h4>Thanh toán</h4>
<Row>
<Col className='tth'>
<div>
Tổng tiền hàng ({listProduct.length} loại hàng):{' '}
</div>
</Col>
<Col span={4}>
<div className='total-price'>
{currencyFormat(totalPrice)}
</div>
</Col>
<Col>
<div className='btnPayment'>
<Button
icon={<MdAddShoppingCart />}
style={{ width: 200, marginLeft: 600 }}
onClick={onSubmit}
>
Đặt hàng
</Button>
</div>
</Col>
</Row>
</div>
</div>
</Container>
);
}
export default Cart;
|
javascript
|
import 'cross-fetch/polyfill';
import { DateTime, Duration } from 'luxon';
import { unit } from 'mathjs';
import { Api, Workout } from '../../src';
const api = new Api();
api.setUserId(1);
const putSpy = jest.spyOn(api, 'put').mockImplementation(() => {
return Promise.resolve({ data: {}, status: 200, source: new Response(''), request: new Request('') });
});
describe('Api testing', () => {
let workout: Workout;
beforeEach(() => {
workout = Workout.get(
0,
DateTime.fromObject({
year: 2018,
month: 3,
day: 5,
hour: 4,
zone: 'utc',
}),
Duration.fromObject({ minutes: 5 }),
);
});
afterEach(() => {
putSpy.mockReset();
});
describe('Edit workout', () => {
it('with basic parameters', async () => {
await api.editWorkout(workout);
expect(putSpy).toHaveBeenCalledWith('rest/v1/users/1/workouts/', {
duration: 300,
sport: 0,
start_time: '2018-03-05T04:00:00.000Z',
});
});
it('with distance', async () => {
await api.editWorkout(workout.setDistance(unit(6, 'km')));
expect(putSpy).toHaveBeenCalledWith('rest/v1/users/1/workouts/', {
duration: 300,
sport: 0,
start_time: '2018-03-05T04:00:00.000Z',
distance: 6,
});
});
it('with option properties', async () => {
await api.editWorkout(
workout
.setAvgHeartRate(80)
.setMaxHeartRate(180)
.setTitle('titulek')
.setAscent(unit(666, 'm'))
.setDescent(unit(999, 'm'))
.setMessage('xzxs')
.setMapPrivacy(0)
.setPrivacy(1),
);
expect(putSpy).toHaveBeenCalledWith('rest/v1/users/1/workouts/', {
ascent: 666,
descent: 999,
duration: 300,
heart_rate_avg: 80,
heart_rate_max: 180,
message: 'xzxs',
show_map: 0,
show_workout: 1,
sport: 0,
start_time: '2018-03-05T04:00:00.000Z',
title: 'titulek',
});
});
});
});
|
typescript
|
Fans have been eagerly awaiting the release of the much-anticipated teaser for Salaar Part 1 - Ceasefire, an exhilarating action-packed film that offers a thrilling glimpse into the upcoming cinematic experience. Prashanth Neel, renowned for his directorial brilliance in the widely acclaimed KGF, helms the project, while Vijay Kiragandur takes on the role of producer. The movie stars the charismatic Prabhas in the lead, accompanied by the talented actors Prithviraj Sukumaran and Shruti Haasan.
Salaar Part 1 - Ceasefire promises to be a captivating mass action and adventure spectacle, filmed across India, Europe, the Middle East, and Africa. With an estimated budget of approximately Rs 200 crore, no expense has been spared in crafting this cinematic masterpiece. The first instalment of the saga has already been completed, prompting Prabhas to focus wholeheartedly on wrapping up the final chapter. To ensure stunning visual effects, the production team has enlisted the expertise of a foreign studio.
With the release of the teaser, fans can now catch a tantalizing glimpse of the excitement and grandeur that awaits them in Salaar Part 1 - Ceasefire, setting the stage for an unforgettable cinematic experience.
|
english
|
/** Generated Assertion Class - DO NOT CHANGE */
package au.org.greekwelfaresa.idempiere.test.assertj.i_fajournal;
import javax.annotation.Generated;
import org.compiere.model.X_I_FAJournal;
/** Generated assertion class for I_FAJournal
* @author idempiere-test model assertion generator
* @version Release 6.2 - $Id: 75b5177830c614f368060425a1fcef4f6c4077f8 $ */
@Generated("class au.org.greekwelfaresa.idempiere.test.generator.ModelAssertionGenerator")
public class I_FAJournalAssert extends AbstractI_FAJournalAssert<I_FAJournalAssert, X_I_FAJournal>
{
/** Standard Constructor */
public I_FAJournalAssert (X_I_FAJournal actual)
{
super (actual, I_FAJournalAssert.class);
}
}
|
java
|
How is the declaration of conformity carried out?
The government should take care of the well-being of the population. Nutrition is considered to be one of the main aspects of the vital activity of citizens, that is why certain standards are set, which the output must correspond to. For this purpose, declaration of conformity is used.
So, the production of absolutely all goods is subject to the conditions specified by regulations.
A specially created body for product certification conducts checks and issues declarations, that is, certificates informing about the quality of products.
The legislation provides for certain criteria for each type of product. In order to complete this procedure, you must fill out an application. As an official applicant, any commercial organization or individual entrepreneur, as well as the seller, can act.
Declaring of compliance is allowed only by special companies accredited by the state. If the applicant fails to correctly draw up a declaration, he can apply to the state body, which for his part is obliged to conduct a detailed consultation. This document is sent to an organization called a certification authority, where it is subject to mandatory registration. The civil servant makes the necessary entries in the special book, then assigns the registration number to the document . The number consists of nine digits, with the first four representing the code of the body accredited by the government, and the next five digits being the document's serial number.
Authorized bodies have established a detailed list of products that require declaration of conformity when transporting across the border or importing into the territory of our country. And for successful implementation of the procedure it is necessary to have a quality certificate with you, that is, the degree of compliance with state standards, as well as data on the results of laboratory work, if any. Declaration of goods is carried out on the basis of information provided by the applicant. Information about the product and the manufacturer must be accurate, truthful and concise. So, the document will have to fill in mandatory details, including the name of the product, its article, detailed information about the manufacturer, the list of regulatory documents, the number assigned at registration, the date of issue and the period of operation of the document.
Declaration of conformity of production to the established quality standards is carried out for a certain period of time. The period during which the document is considered valid is selected by the applicant independently, based on the calculation of the degree of risk of non-compliance and liability for the consequences. To justify the chosen date, it is necessary to collect evidence, in other words, all the available notifications confirming the carrying out of various tests and inspections, any laboratory research can have a significant impact.
|
english
|
Jake Paul weighed in after the UFC's parent company incurred a massive loss after the news regarding the PFL gaining an investment from the Middle-East.
The promotion announced the investment, which will see the launch of PFL MENA and their upcoming PPV SUPER FIGHTS events being hosted in Saudi Arabia. Sportico tweeted that there was heavy volume that resulted in Endeavor's shares declining in value, writing:
"Shares of @WWE and @UFC parent Endeavor group fell Thursday on heavy volume in apparent reaction to the Saudi Arabian PIF investing $100 million into MMA upstart league @PFLMMA."
The tweet caught the attention of 'The Problem Child', who reacted by taking a jibe at the UFC and their business practices. Jake Paul mentioned that UFC fighters aren't earning their fair share of the revenue and also brought up the ongoing class action lawsuit.
He wrote:
"It is not sustainable to pay fighters less than 20% of revenue and fully control their services like they are employees. Fighters are the IP, pay them or free them. They put their lives on the line for you to make money...Oh and there is the class action lawsuit. Big business..."
It remains to be seen whether Endeavor's shares will bounce back to their previous stock price following the Saudi Arabian PIF's large investment into the PFL.
Jake Paul recently congratulated heavyweight boxing champion Oleksandr Usyk on his recent win over Daniel Dubois and also complimented him on the location of the fight.
'The Problem Child' has been riding high as he successfully bounced back from his first career loss earlier this year by defeating former UFC title challenger Nate Diaz. He was in attendance for the Usyk vs. Dubois fight and prior to the fight, he took to Twitter to compliment the heavyweight boxing champion for ensuring the bout was as close to Ukraine as possible.
He wrote:
"So much respect for Usyk for putting this fight on as close as possible to Ukraine. Equally much respect for Dubois taking on the challenge of Usyk +40,000 fans. Can’t wait."
|
english
|
<reponame>thomaslecointre/Distributed-Haskell
{"season":6,"name":"The Door","year":"2016","rated":"TV-MA","released":null,"episode":5,"runtime":"57 min","genres":"Adventure, Drama, Fantasy","director":"<NAME>","writer":"<NAME> (based on \"A Song of Ice and Fire\" by), <NAME> (created by), <NAME> (created by), <NAME> (written for television by), <NAME> (written for television by)","actors":"<NAME>, <NAME>, <NAME>, <NAME>","plot":"Littlefinger faces the consequences of his actions. Sansa and Jon make plans. Daenerys decides Jorah's fate. An uneasy truce in Slaver's Bay doesn't withhold Tyrion from trying to improve the situation. The Ironborn choose their new ruler. Noone(<NAME>) is given a new mission and witnesses a play. Bran learns about how the Long Night came to be but brings chaos upon his group. Wyllis holds the door.","languages":"English","country":"USA","awards":"N/A","poster":"https://images-na.ssl-images-amazon.com/images/M/MV5BMTc0MTg2MDkwOV5BMl5BanBnXkFtZTgwMzk0ODQ5ODE@._V1_SX300.jpg","ratings":[{"Source":"Internet Movie Database","Value":"9.7/10"}],"metascore":"N/A","rating":"9.7","votes":"42423","imdbid":"tt4283028","seriesid":"tt0944947","type":"episode","response":"True"}
|
json
|
The new COVID-19 variant Omicron has urged the need for a vaccination certificate. Many states are making it mandatory for travellers. So if you have received the first or second dose of Covaxin, Covishield, or Sputnik vaccine jab and are wondering how to download the vaccination certificate, look no further. Here’s a quick guide to that.
People who have received the COVID vaccines can download the COVID vaccine certificate online using the CoWIN portal, Aarogya Setu, Digilocker, and Umang app. Below is the step-by-step guide on how to COVID vaccination certificate download online, which remains the same for the second dose as well. But, before we get to that, here’s what you need to know about COVID vaccine certificate and why you need to download it.
What is COVID vaccine certificate?
COVID vaccine certificate is an official document that proves a person has been vaccinated. It is issued after the doses (first and second) of the COVID-19 vaccine is administered. The vaccine certificate has a unique 13-digit beneficiary reference ID using which you can access all the details of that particular person.
People who get the first dose of COVID vaccine will only get a provisional COVID vaccine certificate. Only after you have got both vaccine doses, you get all the details about the inoculation. But in either stage, you might wonder how to download COVID vaccination certificate. Well, there are multiple ways of getting it. You can use the government’s CoWIN website, Aarogya Setu app, DigiLocker app, or the Umang app to get a digital copy of the COVID vaccine certificate.
CoWIN, as you might know, is a government-authorised web portal that lets you register and schedule vaccine appointments. Once you get inoculated, follow these steps to download the PDF of COVID vaccine certificate.
Aarogya Setu is the mobile app through which you can schedule vaccine appointments on Android and iOS devices. But it also allows you to download the vaccine certificate. Here are the steps for that:
- Now you can download the COVID vaccine certificate.
Digilocker is another avenue through which you can download the COVID vaccine certificate. This digital platform lets you store important documents on the cloud that can be accessed anytime using the app. Digilocker is available on Android and iOS for all users.
Here are the steps to download the COVID vaccine certificate using Digilocker:
Umang app is another government source platform that can be used to download vaccination certificate. The app works on both Android and iPhone and facilitates all government services under one platform. Here’s how the certificate can be downloaded:
Vaccinated citizens of India can now get their inoculation certificate on WhatsApp. It can be done with these three simple steps:
If you have used the number to register for vaccination, you will get the PDF file of your certificate. In case, more than one person has been inoculated using the number, you’ll get the option to select a member whose COVID vaccine certificate you want to download.
Users can download their international travel COVID vaccine certificate from the CoWIN portal. The certificate is said to be in compliance with the WHO’s digital documentation of COVID-19 certificates vaccination status data dictionary. The certificate comprises date of birth, doses taken, vaccine name, type, manufacturer, number and dates of doses of the inoculators. International travel Covid vaccine certificate can be downloaded using the following steps:
How to download COVID vaccine certificate without mobile number?
You cannot download COVID vaccine certifcate without a mobile number. All the ways we have listed to download COVID vaccination certificate require a mobile number. You will need a mobile number to log into the CoWIN website, Aarogya Setu app, Umang app, and Digilocker app.
To download the COVID vaccine certificate without beneficiary ID or reference number, you can use the Umang app or the CoWIN portal. The Digilocker app and Aarogya Setu app require a beneficiary ID or reference number to download the certificate.
|
english
|
export interface Post {
identifier: string;
title: string;
body?: string;
slug: string;
subName: string;
username: string;
createdAt: string;
updatedAt: string;
sub?: Sub;
// virtual fields
url: string;
voteScore?: number;
commentCount?: number;
userVote?: number;
}
export interface User {
username: string;
email: string;
createdeAt: string;
updatedAt: string;
}
export interface Sub {
createdAt: string;
updatedAt: string;
name: string;
title: string;
description: string;
imageUrn: string;
bannerUrn: string;
username: string;
posts: Post[];
// virtual fields
imageUrl: string;
bannerUrl: string;
postCount?: number;
}
|
typescript
|
{
"socketURL": "/",
"dirPath": "./ui/",
"homePage": "index.html",
"socketMessageEvent": "DialogueService",
"socketCustomEvent": "__YOU_PASS__",
"port": "8081",
"enableLogs": "false",
"autoRebootServerOnFailure": "true",
"isUseHTTPs": "false",
"sslKey": "",
"sslCert": "",
"sslCabundle": "",
"enableAdmin": "false",
"adminUserName": "",
"adminPassword": ""
}
|
json
|
<h1>{{ pass_dict.course_title }}</h1>
<p class="text-justify">{{ pass_dict.course_description | safe }}</p>
<!-- Display main properties with glyphicons -->
<table id="glyph-table">
<tbody>
<tr>
<td>
<span class="glyphicon glyphicon-education"></span>
<p>Provider</p>
<!-- Use dict.pop so that remaining elements can be rendered with for loop -->
<p class="glyph-info">{{ pass_dict.course_info.pop('Provider', '<awaiting mapping>') }}</p>
</td>
<td>
<span class="glyphicon glyphicon-time"></span>
<p>Duration</p>
{% set duration = pass_dict.course_info.pop('Duration', 0) %}
<p class="glyph-info">{{ duration }} {{ 'hours' if duration != 1 else 'hour' }}</p>
</td>
</tr>
<tr>
<td>
<span class="glyphicon glyphicon-pencil"></span>
<p>Business Line</p>
<p class="glyph-info">{{ pass_dict.course_info.pop('Business Line', '<awaiting mapping>') }}</p>
</td>
<td>
<span class="glyphicon glyphicon-eye-open"></span>
<p>Displayed on GCcampus</p>
<p class="glyph-info">{{ pass_dict.course_info.pop('Displayed on GCcampus', '<awaiting mapping>') }}</p>
</td>
</tr>
</tbody>
</table>
<!-- Additional Info -->
<table class="table table-hover">
<thead>
<tr>
<td class="text-center" colspan="2">
<h4>
<strong>Additional Info</strong>
<img id="additional-info-tooltip" class="inline-tooltip" src="{{ url_for('static', filename='stars/tooltip.png') }}" alt="Tooltip" />
</h4>
</td>
</tr>
<tr>
<td><strong>Field</strong></td>
<td class="text-right"><strong>Contents</strong></td>
</tr>
</thead>
<tbody>
{% for key, value in pass_dict.course_info.items() %}
<tr>
<td>{{ key }}</td>
<td class="text-right">{{ value }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<script async>
// Add tooltip
$('#additional-info-tooltip').tooltip({
placement: 'right',
title: '<h5>Tip:</h5><p>This information is tracked by Curriculum Management.</p>',
animation: true,
html: true
});
</script>
|
html
|
package com.lingganhezi.myapp.ui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import android.widget.BaseAdapter;
public abstract class ListAdapter<T> extends BaseAdapter {
private List<T> mData = new ArrayList<T>();
@Override
public int getCount() {
return mData.size();
}
@Override
public T getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return mData.get(position).hashCode();
}
public void add(T item) {
mData.add(item);
}
public void add(T item, int pos) {
if (pos >= mData.size() - 1) {
pos = mData.size() - 1;
}
mData.add(pos, item);
}
public void add(Collection<T> items) {
mData.addAll(items);
}
public void remove(T item) {
mData.remove(item);
}
public void remove(int pos) {
mData.remove(pos);
}
public void clear() {
mData.clear();
}
public List<T> getData() {
return mData;
}
}
|
java
|
<gh_stars>10-100
---
layout: data_model
title: OptionDataType
this_version: 1.1.1
---
<div class="alert alert-danger bs-alert-old-docs">
<strong>Heads up!</strong> These docs are for STIX 1.1.1, which is not the latest version (1.2). <a href="/data-model/1.2/PacketObj/OptionDataType">View the latest!</a>
</div>
<div class="row">
<div class="col-md-10">
<h1>OptionDataType<span class="subdued">Network Packet Object Schema</span></h1>
<p class="data-model-description">Defines the variable-length fields associated with IPv6 extension headers (the Hop-by-Hop Options header and the Destination Options header). Contains one or more type-length-value (TLV)-encoded options.</p>
</div>
<div id="nav-area" class="col-md-2">
<p>
<form id="nav-version">
<select>
<option value="1.2" >STIX 1.2</option>
<option value="1.1.1" selected="selected">STIX 1.1.1</option>
<option value="1.1" >STIX 1.1</option>
<option value="1.0.1" >STIX 1.0.1</option>
<option value="1.0" >STIX 1.0</option>
</select>
</form>
</p>
</div>
</div>
<hr />
<h2>Fields</h2>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Field Name</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Option_Type<span class="occurrence">0..1</span></td>
<td>
<a href="/data-model/1.1.1/PacketObj/IPv6OptionType">IPv6OptionType</a>
</td>
<td>
<p>Identifies the type of option. This 8-bit Option Type identifier is internally encoded such that different bits have different meanings. These meanings are further specified in the <a href='/data-model/1.1.1/PacketObj/IPv6OptionType'>IPv6OptionType</a> type.</p>
</td>
</tr>
<tr>
<td>Option_Data_Len<span class="occurrence">0..1</span></td>
<td>
<a href="/data-model/1.1.1/cyboxCommon/HexBinaryObjectPropertyType">HexBinaryObjectPropertyType</a>
</td>
<td>
<p>Length of the Option Data field of this option, in octets.</p>
</td>
</tr>
<tr>
<td>Pad1<span class="occurrence">0..1</span></td>
<td>
<a href="/data-model/1.1.1/PacketObj/Pad1Type">Pad1Type</a>
</td>
<td>
<p>The Pad1 option is used to insert one octet of padding into the Options area of a header. The Pad1 option does not have length and value fields.</p>
</td>
</tr>
<tr>
<td>PadN<span class="occurrence">0..1</span></td>
<td>
<a href="/data-model/1.1.1/PacketObj/PadNType">PadNType</a>
</td>
<td>
<p>The PadN option is used to insert two or more octets of paddings into the Options area of a header.</p>
</td>
</tr>
</tbody>
</table>
|
html
|
<reponame>andydotxyz/go-gerber
package gerber
import (
"math"
"testing"
_ "github.com/gmlewis/go-fonts/fonts/freeserif"
)
func TestTextT_Primitive(t *testing.T) {
var p Primitive = &TextT{}
if p == nil {
// In actuality, this test won't compile if it isn't a Primitive.
t.Errorf("TextT does not implement the Primitive interface")
}
}
func TestText(t *testing.T) {
const (
message = "012"
fontName = "freeserif"
wantWidth = 36.8554
wantHeight = 17.526
pts = 72
eps = 1e-6
sf = 1e6
)
tests := []struct {
name string
x, y float64
opts TextOpts
wantXmin float64
wantYmin float64
wantXmax float64
wantYmax float64
}{
{
name: "XLeft,YBottom",
wantXmin: 0,
wantYmin: 0,
wantXmax: wantWidth,
wantYmax: wantHeight,
},
{
name: "XLeft,YBottom w/ offset",
x: 10,
y: 20,
wantXmin: 10,
wantYmin: 20,
wantXmax: (10 + wantWidth),
wantYmax: (20 + wantHeight),
},
{
name: "XCenter,YBottom",
opts: BottomCenter,
wantXmin: -0.5 * wantWidth,
wantYmin: 0,
wantXmax: 0.5 * wantWidth,
wantYmax: wantHeight,
},
{
name: "XCenter,YBottom w/ offset",
x: 10,
y: 20,
opts: BottomCenter,
wantXmin: (10 - 0.5*wantWidth),
wantYmin: 20,
wantXmax: (10 + 0.5*wantWidth),
wantYmax: (20 + wantHeight),
},
{
name: "XRight,YBottom",
opts: BottomRight,
wantXmin: -wantWidth,
wantYmin: 0,
wantXmax: 0,
wantYmax: wantHeight,
},
{
name: "XRight,YBottom w/ offset",
x: 10,
y: 20,
opts: BottomRight,
wantXmin: (10 - wantWidth),
wantYmin: 20,
wantXmax: 10,
wantYmax: (20 + wantHeight),
},
{
name: "XLeft,YCenter",
opts: CenterLeft,
wantXmin: 0,
wantYmin: -0.5 * wantHeight,
wantXmax: wantWidth,
wantYmax: 0.5 * wantHeight,
},
{
name: "XLeft,YCenter w/ offset",
x: 10,
y: 20,
opts: CenterLeft,
wantXmin: 10,
wantYmin: (20 - 0.5*wantHeight),
wantXmax: (10 + wantWidth),
wantYmax: (20 + 0.5*wantHeight),
},
{
name: "XCenter,YCenter",
opts: Center,
wantXmin: -0.5 * wantWidth,
wantYmin: -0.5 * wantHeight,
wantXmax: 0.5 * wantWidth,
wantYmax: 0.5 * wantHeight,
},
{
name: "XCenter,YCenter w/ offset",
x: 10,
y: 20,
opts: Center,
wantXmin: (10 - 0.5*wantWidth),
wantYmin: (20 - 0.5*wantHeight),
wantXmax: (10 + 0.5*wantWidth),
wantYmax: (20 + 0.5*wantHeight),
},
{
name: "XRight,YCenter",
opts: CenterRight,
wantXmin: -wantWidth,
wantYmin: -0.5 * wantHeight,
wantXmax: 0,
wantYmax: 0.5 * wantHeight,
},
{
name: "XRight,YCenter w/ offset",
x: 10,
y: 20,
opts: CenterRight,
wantXmin: (10 - wantWidth),
wantYmin: (20 - 0.5*wantHeight),
wantXmax: 10,
wantYmax: (20 + 0.5*wantHeight),
},
{
name: "XLeft,YTop",
opts: TopLeft,
wantXmin: 0,
wantYmin: -wantHeight,
wantXmax: wantWidth,
wantYmax: 0,
},
{
name: "XLeft,YTop w/ offset",
x: 10,
y: 20,
opts: TopLeft,
wantXmin: 10,
wantYmin: (20 - wantHeight),
wantXmax: (10 + wantWidth),
wantYmax: 20,
},
{
name: "XCenter,YTop",
opts: TopCenter,
wantXmin: -0.5 * wantWidth,
wantYmin: -wantHeight,
wantXmax: 0.5 * wantWidth,
wantYmax: 0,
},
{
name: "XCenter,YTop w/ offset",
x: 10,
y: 20,
opts: TopCenter,
wantXmin: (10 - 0.5*wantWidth),
wantYmin: (20 - wantHeight),
wantXmax: (10 + 0.5*wantWidth),
wantYmax: 20,
},
{
name: "XRight,YTop",
opts: TopRight,
wantXmin: -wantWidth,
wantYmin: -wantHeight,
wantXmax: 0,
wantYmax: 0,
},
{
name: "XRight,YTop w/ offset",
x: 10,
y: 20,
opts: TopRight,
wantXmin: (10 - wantWidth),
wantYmin: (20 - wantHeight),
wantXmax: 10,
wantYmax: 20,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
text := Text(tt.x, tt.y, 1, message, fontName, pts, &tt.opts)
gotWidth := text.Width()
if math.Abs(gotWidth-wantWidth) > eps {
t.Errorf("width = %v, want %v", gotWidth, wantWidth)
}
gotHeight := text.Height()
if math.Abs(gotHeight-wantHeight) > eps {
t.Errorf("height = %v, want %v", gotHeight, wantHeight)
}
mbb := text.MBB()
if math.Abs(mbb.Min[0]-tt.wantXmin) > eps {
t.Errorf("Xmin = %v, want %v", mbb.Min[0], tt.wantXmin)
}
if math.Abs(mbb.Min[1]-tt.wantYmin) > eps {
t.Errorf("Ymin = %v, want %v", mbb.Min[1], tt.wantYmin)
}
if math.Abs(mbb.Max[0]-tt.wantXmax) > eps {
t.Errorf("Xmax = %v, want %v", mbb.Max[0], tt.wantXmax)
}
if math.Abs(mbb.Max[1]-tt.wantYmax) > eps {
t.Errorf("Ymax = %v, want %v", mbb.Max[1], tt.wantYmax)
}
})
}
}
|
go
|
package slimeknights.mantle.util;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.data.ModelProperty;
import net.minecraftforge.registries.ForgeRegistries;
import javax.annotation.Nullable;
/**
* This utility contains helpers to handle the NBT for retexturable blocks
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class RetexturedHelper {
/** Tag name for texture blocks. Should not be used directly, use the utils to interact */
private static final String TAG_TEXTURE = "texture";
/** Property for tile entities containing a texture block */
public static final ModelProperty<Block> BLOCK_PROPERTY = new ModelProperty<>(block -> block != Blocks.AIR);
/* Getting */
/**
* Gets a block for the given name
* @param name Block name
* @return Block entry, or {@link Blocks#AIR} if no match
*/
public static Block getBlock(String name) {
if (!name.isEmpty()) {
Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(name));
if (block != null) {
return block;
}
}
return Blocks.AIR;
}
/**
* Gets the name of the texture from NBT
* @param nbt NBT tag
* @return Name of the texture, or empty if no texture
*/
public static String getTextureName(@Nullable CompoundNBT nbt) {
if (nbt == null) {
return "";
}
return nbt.getString(TAG_TEXTURE);
}
/* Setting */
/**
* Sets the texture in an NBT instance
* @param nbt Tag instance
* @param texture Texture to set
*/
public static void setTexture(@Nullable CompoundNBT nbt, String texture) {
if (nbt != null) {
if (texture.isEmpty()) {
nbt.remove(TAG_TEXTURE);
} else {
nbt.putString(TAG_TEXTURE, texture);
}
}
}
}
|
java
|
package reserved
import (
"GoVM/chapter5-instructions/base"
"GoVM/chapter4-rtdt"
"GoVM/native"
//如果不显式使用lang包中的变量,只是让他执行init()方法,需要前面加下划线
_ "GoVM/native/java/lang"
_ "GoVM/native/sun/misc"
)
/**
即0xFE指令
*/
type INVOKE_NATIVE struct {
base.NoOperandsInstruction
}
func (self *INVOKE_NATIVE) Execute(frame *chapter4_rtdt.Frame) {
method := frame.Method()
className := method.Class().Name()
methodName := method.Name()
methodDescriptor := method.Descriptor()
nativeMethod := native.FindNativeMethod(className, methodName, methodDescriptor)
if nativeMethod == nil {
methodInfo := className + "." + methodName + "--" + methodDescriptor
panic("java.lang.UnsatisfiedLinkError: " + methodInfo)
}
//这相当于调用找到的native method
nativeMethod(frame)
}
|
go
|
use geometry::*;
use math::*;
use renderable::{Hit, Renderable};
use std::f64;
pub struct Scene {
objects: Vec<Box<Renderable>>
}
impl Scene {
pub fn new() -> Scene {
Scene { objects: Vec::new() }
}
pub fn add(&mut self, object: Box<Renderable>) {
self.objects.push(object);
}
pub fn intersect<'a>(&'a self, ray: &Ray) -> Option<Hit<'a>> {
let mut hit_dist = f64::INFINITY;
let mut hit_obj: Option<&Box<Renderable>> = None;
for obj in self.objects.iter() {
if let Some(dist) = obj.intersect(&ray) {
if dist < hit_dist {
hit_dist = dist;
hit_obj = Some(&obj);
}
}
}
match hit_obj {
None => { None },
Some(obj) => {
Some(obj.get_hit(&ray, hit_dist))
}
}
}
fn shadow_cast(&self, ray: &Ray, light: &Renderable) -> bool {
let mut hit_obj: Option<&Renderable> = None;
let mut hit_dist = f64::INFINITY;
for obj in self.objects.iter() {
if let Some(dist) = obj.intersect(&ray) {
if dist < hit_dist {
hit_dist = dist;
hit_obj = Some(&**obj);
}
}
}
match hit_obj {
None => { false },
Some(obj) => {
// Ideally, something like this:
// if obj as *const Renderable == light as *const Renderable { true } else { false }
// but we hit an ICE in rust 1.0.0
obj.identity() == light.identity()
}
}
}
pub fn sample_lights(&self, from: Vec3d, normal: Vec3d, rng: &mut F64Rng) -> Vec3d {
let mut emission = Vec3d::zero();
for obj in self.objects.iter() {
if !obj.is_emissive() { continue; }
let (random_obj_dir, obj_emission) = obj.random_emission(from, normal, rng);
let ray = Ray::new(from, random_obj_dir);
if self.shadow_cast(&ray, &**obj) {
emission = emission + obj_emission;
}
}
emission
}
}
|
rust
|
<gh_stars>0
# -*- coding: utf-8 -*-
'''
* @Author : jiangtao
* @Date : 2021-12-13 14:18:45
* @Email : <EMAIL>
* @LastEditTime : 2022-03-02 14:11:31
* @Description :
'''
import argparse
import cv2
import json
import os
import os.path as osp
import sys
import time
import warnings
from argparse import ArgumentParser
from tqdm import tqdm
from xtcocotools.coco import COCO
from mmpose.apis import (inference_top_down_pose_model, init_pose_model,
vis_pose_result)
from mmpose.datasets import DatasetInfo
dirpath = osp.dirname(osp.abspath(__file__)).replace('\\','/')
dirpath = osp.dirname(dirpath)
def parse_args():
parser = argparse.ArgumentParser(
description='Convert MMDetection models to ONNX')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
args = parser.parse_args()
return args
class handAlignment():
def __init__(self,
pose_config = '{}/configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/dms/res50_dms_256x256.py'.format(dirpath),
pose_checkpoint = '{}/work_dirs/res50_dms_256x256/best_NME_epoch_42.pth'.format(dirpath),
device = 'cuda:0'):
self.pose_config = pose_config
self.pose_checkpoint = pose_checkpoint
self.device = device
print('self.pose_checkpoint:',self.pose_checkpoint)
self.pose_model = init_pose_model(
self.pose_config, self.pose_checkpoint, device=self.device.lower())
self.dataset = self.pose_model.cfg.data['test']['type']
self.dataset_info = self.pose_model.cfg.data['test'].get('dataset_info', None)
# dataset is a str,dataset_info is a dict
if self.dataset_info is None:
warnings.warn(
'Please set `dataset_info` in the config.'
'Check https://github.com/open-mmlab/mmpose/pull/663 for details.',
DeprecationWarning)
else:
self.dataset_info = DatasetInfo(self.dataset_info)
# dataset_info is a instance of DatasetInfo
def alignment(self,img,box):
'''
box:[x,y,w,h]
'''
person = {}
person['bbox'] = box
person_results = []
person_results.append(person)
# test a single image, with a list of bboxes
pose_results, returned_outputs = inference_top_down_pose_model(
self.pose_model,
img,
person_results,
bbox_thr=None,
format='xywh',
dataset=self.dataset,
dataset_info=self.dataset_info,
return_heatmap=True,
outputs=None)
return pose_results,returned_outputs
def save(self, img, outfile, pose_results,returned_outputs):
img = vis_pose_result(
self.pose_model,
img,
pose_results,
dataset=self.dataset,
dataset_info=self.dataset_info,
kpt_score_thr=0.3,
radius=4,
thickness=1,
show=False,
out_file=outfile)
return img
handAlign = handAlignment()
if __name__ == '__main__':
args = parse_args()
handAlign = handAlignment(pose_config=args.config,
pose_checkpoint=args.checkpoint)
filename = './demo/images/face.jpg'
img = cv2.imread(filename,1)
# input box is w y w h format
# pose_results is a list of dict for every box, keys are bbox and keypoints
# returned_outputs is a list of dict for every box, keys are heatmap
pose_results, returned_outputs = handAlign.alignment(img,[495,221,400,400])
print(returned_outputs[0]['heatmap'].shape)
print(returned_outputs[0]['heatmap'][0][0][0][0])
print(returned_outputs[0]['heatmap'][-1][-1][-1][-1])
img = handAlign.save(img,
filename.replace('.jpg','_res.jpg'),
pose_results,
returned_outputs)
print(img.shape)
cv2.imwrite(filename.replace('.jpg','_res1.jpg'),img)
|
python
|
Begin typing your search above and press return to search.
The Indian Super League (ISL) outfit was in hopes to reap the benefits of the football know-how and management expertise the Qatar-based academy brings, when Delhi Dynamos FC signed a ground-breaking technical agreement in July last year with the famous Aspire Academy in Doha. Ever since its foundation in 2004, the predominantly shining Aspire Academy has played host to numerous top European clubs for its training facilities. It's highly sought after residential programme will now play host to a Dynamos starlet for the next four months. Shubham Sarangi who is Delhi's most recent acquisition will be making the trip to the Middle East. The 17-year-old forward was signed by the national capital-based outfit at the inception of the newly introduced January transfer window of the ISL. Shubham who is a native of Delhi, rose to prominence when he was selected to be a part of India's preparatory squad for the 2017 FIFA U-17 World Cup. Source: India Today The youngster ultimately did not make the cut for Luis Norton de Matos' final squad for the prestigious event. Shubham could only watch from far afield as his former teammates created history by becoming the first Indian side to play in any World Cup. The teenager has always dreamt about playing in Europe but when the chance came to sign for the ISL side, there was no way he could have turned it down. He told the press, 'I was approached by a few European clubs before signing for Delhi Dynamos. But I took advantage of the chance I was getting over here and realised how this would benefit me in the long run as Delhi Dynamos are providing me a huge platform and exposure second to none. From here I wish to gain more experience and become a better player and wait for better offers from Europe.' Missing out on the chance to play in a World Cup in front of his countrymen will always be a painful miss out for Shubham, but he has decided to let go off the missed chance and instead prove a better point for the chance he has been granted with. Shubham told the press, 'It was disappointing for me to not be a part of the World Cup squad but I have brushed aside the past and I am now focusing only on Delhi Dynamos and my future in ISL. I wanted to be a part of the U-17 World Cup but this is part of the game and I won't let such disappointments affect me in a negative way and instead I have only worked harder than what I did maybe three-to-four months back. I have a point to prove now.' In Miguel Angel Portugal, Shubham has a coach with a high pedigree when it comes to developing the stars of tomorrow. The former Real Madrid B team coach's possession-based brand of football is tailor-made for the young forward and he hopes to establish himself firmly in Delhi's squad by the time the next edition of the ISL comes knocking. When Shubham was asked about his experience so far with his new team-mates and coach, he told the press, 'It has been a good experience so far training under such a renowned coach who has worked with Real Madrid in the past and some experienced players like Pritam Kotal who plays in the Indian national team and captain Kalu Uche who has played the World Cup.' He continued, 'I enjoy coach Portugal's style of play which is more possession-based. I like to distribute the ball forward and even make runs into the box which is something coach Portugal also admires about my football and I am hopeful that by next season I can become a more regular name in the Delhi Dynamos team sheet." With a long-standing dream to play in Europe someday, Shubham does not have to look far for inspiration with Dynamos skipper Kalu Uche's presence in the squad. The confident forward player said, 'I really admire Kalu Uche. He has played in the senior World Cup, scored two goals as well for Nigeria. He has played in big La Liga clubs and it is my dream also to play in Europe so I get to learn a lot from him while training. We have all seen his quality on the field and off it as well he is a very humble person who is kind of enough to help others in training. It's always good to have someone with so much experience on the side.' Already been earmarked for a great future for the ISL side, the youngster is currently fully focused on his training stint with the Aspire Academy and hopes to use the experience to further his football development. Regarding his expectations from the short-span at the academy Shubham told the media, 'It's a great opportunity for me to go to Aspire and train there for four months. They have some of the best facilities in the world and are renowned for their coaching and training-centres. I have been working closely with coaches from Aspire who have come to Delhi Dynamos and I know the style of football that I will be taught in Qatar so I am hoping it will not be difficult for me to adjust there.' He added, 'It's a good learning opportunity and I want to make the most of this chance because not many Indian players get a chance to spend such long time in these facilities and under the guidance of such renowned coaches.' Now, let us all leave it to time to prove whether Shubham too has a star-lit future. For now, the signs are bright and the Aspire Academy period will only increase the abundant potential he has displayed until now.
|
english
|
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Selection Status Schema",
"description": "Selection Status Schema",
"type": "string",
"additionalProperties": false,
"enum": [
"Yes",
"No",
"NotSpecified"
]
}
|
json
|
"""
Examples tests using standard documentation.
https://docs.python.org/3/library/unittest.html
"""
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# Check that s.split fails when the seperator is not a string
with self.assertRaises(TypeError):
s.split(2)
def test_in(self):
s = 'Lambda School Rocks!'
self.assertTrue('L' in s)
self.assertIn('L', s)
if __name__ == '__main__':
unittest.main()
|
python
|
Got some extra gold bricks lying around? Check out the Gresso iPhone 4 Black Diamonds for Lady. It’s not a case, rather the phone has been modded to house 6 carats of black diamonds, edging in platinum, a 2 carat diamond home button and a frame of white diamonds. The back of the phone is made of a 200-year-old African Blackwood.
So far price is not known, but the version without diamonds is $10,000. I’d rather use a white iPhone.
|
english
|
{"organizations": [], "uuid": "cb26fc61e7291b38b71fe20647b304448de9ad6a", "thread": {"social": {"gplus": {"shares": 0}, "pinterest": {"shares": 0}, "vk": {"shares": 0}, "linkedin": {"shares": 0}, "facebook": {"likes": 0, "shares": 0, "comments": 0}, "stumbledupon": {"shares": 0}}, "site_full": "www.tripadvisor.com", "main_image": "https://media-cdn.tripadvisor.com/media/photo-s/0e/bd/4b/46/guest-room.jpg", "site_section": "https://www.tripadvisor.com/Hotel_Review-g60763-d93516-Reviews-or10-Novotel_New_York_Times_Square-New_York_City_New_York.html", "section_title": "Novotel New York Times Square - UPDATED 2017 Hotel Reviews & Price Comparison (New York City) - TripAdvisor", "url": "https://www.tripadvisor.com/ShowUserReviews-g60763-d93516-r467867066-Novotel_New_York_Times_Square-New_York_City_New_York.html", "country": "US", "domain_rank": 189, "title": "Clean, great location", "performance_score": 0, "site": "tripadvisor.com", "participants_count": 1, "title_full": "Clean, great location - Review of Novotel New York Times Square, New York City, NY - TripAdvisor", "spam_score": 0.0, "site_type": "discussions", "published": "2017-03-16T02:00:00.000+02:00", "replies_count": 0, "uuid": "cb26fc61e7291b38b71fe20647b304448de9ad6a"}, "author": "purrlocked", "url": "https://www.tripadvisor.com/ShowUserReviews-g60763-d93516-r467867066-Novotel_New_York_Times_Square-New_York_City_New_York.html", "ord_in_thread": 0, "title": "Clean, great location", "locations": [], "entities": {"persons": [], "locations": [], "organizations": []}, "highlightText": "", "language": "english", "persons": [], "text": "The location and cleanliness merits top marks. Special thanks to Geralde for facilitating our check-in and one day extension due to the snow storm. During our week long stay stay, we tried the Hotel restaurant Supernova twice, once for breakfast and another for lunch. It has a nice view of Times Square's lighted billboards. There are lots of choices for all price ranges near by: Pret A Manger, 99 Cents Fresh Pizza, Le Bernardin and Halal Guys.\nA few things to note. Buffet Breakfast coffee is only from coffee maker, not espresso based. Many breads available, but since breakfast is self service, each person needs to cut a piece of big loaves (like the baguettes) himself/herself. I've seen other guests handle it with their bare hands. Oranges and grapefruit come pre peeled immersed in a liquid. I would have preferred the whole fruit.\nLunch service, they never noticed we did not have butter knives for the rolls, so I just got one from another unoccupied table. They serve a nice complimentary variety of 4 rolls with olive oil, butter and olives (salty) on the side. It would have been better if there was balsamic vinegar to mix with the olive oil. They did ask how was our orders though, which was OK. I learned at this time that they can actually prepare espresso based drinks. I wish that option was offered at breakfast too.\nIt's location is best if you want to walk to Top of the Rock, St. Patrick's Cathedral, MoMa, Central Park and the the Museum Mile nearby. Lots of theaters are just a few steps away. In Broadway, the show goes on even if there is a snow storm. We just hoped the hotel shoveled a little snow from the sidewalk leading to their door. Even just a two feet wide section of their entrance would have been enough so guests and rolling luggages can pass without getting buried in snow.\nIf you are having packages delivered to the hotel, there's a handling fee of 2 USD for each one, which I think is fair because they sign and receive it for you when you are out. Do note that you can only retrieve your package during office hours.", "external_links": [], "published": "2017-03-16T02:00:00.000+02:00", "crawled": "2017-03-29T05:59:03.100+03:00", "highlightTitle": ""}
|
json
|
<reponame>ahmedlhanafy/guchub<filename>src/screens/Transcript.js
/* @flow */
import React from 'react';
import { Screen } from '../components';
export default () => {
return (
<Screen>
<Screen.Header title="Coming Soon" animated back />
<Screen.Content />
</Screen>
);
};
|
javascript
|
<reponame>champierre/jisx0402
{"prefecture":"岡山県","city":"鏡野町","prefecture_kana":"オカヤマケン","city_kana":"カガミノチョウ","code":"336068","code5":"33606"}
|
json
|
John Fetterman is a trust fund kid. He took money from his parents deep into middle age when he decided finally what he would like to do with the rest of his life, which is to be the U. S. senator from Pennsylvania. The problem is fate intervened and he can now no longer speak. He had a bad stroke and we feel bad about that. Everyone does, but because of that stroke, Fetterman now needs electronic assistance in order to communicate with other people.
He can't talk on his own. It's not a right-wing conspiracy theory. It's not QAnon. It's real. In fact, it's so real, his campaign concedes that it's real. That is true. Fetterman uses a software program to understand the words of those around him and to formulate his responses to those words. In other words, to talk. Now, to be perfectly clear, this software is not a hearing aid. Fetterman doesn't need a hearing aid because he isn't deaf. He's not hearing impaired. Instead, this program takes words and then rearranges them into language that John Fetterman can understand because his brain can no longer do that for him.
That's sad. For transhumanists, though, it is thrilling. This is an amazing moment. This is Neil Armstrong on the moon. Here you have one of the most famous politicians in the country merging with a computer. This is the future they imagine. They're thrilled by it, but for everyone else, for the voters of Pennsylvania, for example, it does raise some obvious questions. For example, where exactly does the software end and John Fetterman consciousness begin?
We don't know. We can't know, but it's obvious that Pennsylvania could very well be sending a computer program to the U. S. Senate where inevitably it will be hacked. Yesterday, MSNBC sat down with John Fetterman and his thinking machine to assess where the man ends and the machine begins and the initial impressions were not at all encouraging.
FETTERMAN SAYS STROKE NOT 'GOING TO HAVE AN IMPACT' ON DUTIES IF ELECTED, INSISTS CAMPAIGN 'VERY TRANSPARENT'
REPORTER DASHA BURNS: We had a monitor set up so that he could read my questions because he still has lingering auditory processing issues as a result of the stroke, which means he has a hard time understanding what he's hearing. Now once he reads the question, he's able to understand. You'll hear he also still has some problems, some challenges with speech, and I'll say, Katie, that just in some of the small talk prior to the interview, before the closed captioning was up and running, it did seem that he had a hard time understanding our conversations.
Well, good for her for admitting that. That's a rival channel. Don't watch a lot of MSNBC, but she should tell viewers that, and she did. What she just told you is that before the machine was turned on, John Fetterman could not understand human language, not even small talk. But once the machine was plugged in, he sounded or the machine sounded nearly human, but don't worry. Everything is going to be fine in the Senate as long as there's not a power outage. It's not like the electricity ever goes down in this country. We definitely have enough renewables to keep John Fetterman voting the right way for the next six years. Better build some more wind farms. That's the plan.
But once again, to the credit of the MSNBC. com reporter, she did ask a follow-up. How do we know your thinking machine isn't going to break, John Fetterman? Can we see a doctor's report on this? Here's how that exchange went:
REPORTER DASHA BURNS: Can voters trust that you will be able to do this job on day one?
JOHN FETTERMAN: Yeah, of course.
BURNS: So, you say you're on the road to full recovery, but right now, voters really have to take your word for it. We've asked for your medical records. We've asked to have a conversation with someone from your medical team to interview your physician. You've declined those requests. Why?
FETTERMAN: Well, I feel like we have been very transparent in a lot of different ways when our doctor has already given a letter saying that I'm able to serve and to be running.
BURNS: I mean, respectfully, that letter from your physician, that was six months ago. Don't voters deserve to know your status now?
FETTERMAN: Being on, in front of thousands and thousands of people and having interviews and getting around all across Pennsylvania, that gives everybody and the voters decide, you know, if they think that it's really the issue.
He's reading that off a screen and by the way, we're taking him at his word that there's not a staffer backstage typing out the answers because he himself can't formulate them. Now, again, you can feel deeply sympathetic to John Fetterman. That's sad to watch, but this is a guy who wants to run the federal government in a body of 100, the most powerful legislative body in the world, and he wants to be a member of it.
Over at CBS, reporter Ed O'Keefe asked the obvious question, "Will Pennsylvanians be comfortable with someone representing them who had to conduct a TV interview this way? " Now, that's a mild way to put it, but it's certainly a fair observation. The guy's reading his answers off a screen with the reporter three feet away. That's the definition of impairment and again, this is a very serious job.
But others in the media scoffed at the idea that was a problem at all. In fact, far from being a problem, it was an asset because if the equity agenda means anything, it means that incompetent people ought to be in charge. That's equity.
As New York City Councilwoman Rita Joseph put it, questions about Fetterman's profound brain damage are, "incredibly ableist. " Ableist? "We desperately need more diversity in elected office, and that includes people with speech impediments. " Well, we desperately need that. That is absolutely right, but actually we're not talking about a speech impediment. She's telling us he's got a stutter just like Joe Biden. Remember they told you that Joe Biden's dementia was just a stutter? But of course, a speech impediment would not prevent Fetterman or Biden from understanding other people's speech. Huh?
Investigative reporter Hunter Walker, who writes for Rolling Stone and The New Yorker, answered that question with a question of his own "Would they treat a deaf person like this for needing assistance? " Oh. So, if you have questions about John Fetterman, you hate the deaf. You're a hearingist, bigot. We're going to close down your bank account of JPMorgan, ablest. But again, it's not really relevant to the Senate race in Pennsylvania because once again, John Fetterman doesn't have hearing problems. He's not deaf. This isn't deafness. This is brain damage.
The Independent's Eric Michael Garcia tried to tie up that loose end, and he used an analogy to do it. That's how really smart people talk. "How is this any different," he wrote "from Tammy Duckworth or Madison Cawthorn needing a wheelchair? "
So, John Fetterman, being unable to talk without reading it off a screen, either from the software or from one of his staffers backstage is exactly the same as being wounded in defense of your own country. It's a war injury.
And then John Fetterman’s wife, who came into this country as an illegal alien by the way, wondered the same thing and we're quoting "Truly appalling. Have these ‘journalists’ never heard of the Americans with Disabilities Act? Really curious to learn how they feel about wheelchairs and glasses. "
Really? So, your questions about John Fetterman's mental health, the acuity of his brain, his ability to talk and listen and reason, use his higher faculties, those questions are banned by the Americans with Disabilities Act because he's not just an incompetent guy trying to take over the country. No, he's disabled.
Over at Vox, Ian Millhiser said he knows exactly how Fetterman's bigoted critics view people with eyeglasses. "Is it the position of NBC News that a senator with glasses cannot be trusted in office because they use assistive technology to accommodate their disability? "
It's unbelievable. Not only can you not ask questions about the guy you're supposed to vote for and whether he can actually represent you in the United States Senate, you're not allowed. He's fine and by the way, the fact he's not fine is the reason to vote for him. So, they're hitting you for both sides. Vote for him because he's so profoundly disabled. We don't have enough for those in the Senate. But if you note he is profoundly disabled, you're a bigot. They got you coming and going.
Have you heard this before? Does it sound kind of familiar where they take someone with an obvious impairment and then they use him to accrue more power for themselves? It's not really about the disabled person. It's about them and then if you ask questions about it, shut up bigot!
Does the name Greta Thunberg come to mind? That's the girl who is always lecturing you about global warming and how you are evil. Greta Thunberg is someone who needed help and concern from adults. At the age of 11, she lost 22 pounds because, according to her parents, she was so depressed about global warming that she couldn't eat and then she was diagnosed with a whole suite of very serious problems: OCD, mutism, Asperger's, very, very sad, actually.
But the people around Greta Thunberg and the people who used Greta Thunberg didn't see this as sad at all. They saw it as an advantage for them because Greta Thunberg could be used to accrue more power to them and you weren't allowed to say anything about it because she was disabled, which, by the way, you weren't allowed to notice. Here's Greta Thunberg:
GRETA THUNBERG: You all come to us young people for hope. How dare you! You have stolen my dreams and my childhood with your empty words. We are in the beginning of a mass extinction and all you can talk about is the money and fairy tales of eternal economic growth. How dare you!
So you look at that and on one level you think, why is this person lecturing me, someone who's never had a job before is in charge of, like, our energy policy? That's crazy.
And then the other level, the more deep level, the more important level, you realize what a tragedy you just saw. Here is someone who is profoundly troubled, who needs real help and care and empathy and love from the adults in her life, but she's not getting any of that. Instead, she's being carted out like a sideshow freak for the profit of others. They're using that child in exactly the way they're using Joe Biden and John Fetterman and by the way, Kamala Harris, the dimmest person ever to work in American politics. None of them have any idea what's going on. And they're being used by people for the benefit of those people, but you can't say anything because you would be against people with disabilities and the ADA prohibits you from doing that. Right?
You're supposed to accommodate Greta Thunberg's disability, pretend her words are profound, just like the fake poet at Biden's inauguration. Oh, she was so great. We dare you to say she wasn't. She was ridiculous, but you did not because it's so profound.
In Greta Thunberg's case, of course, the media loved it because they could use her too. They could use Greta Thunberg, didn't care anything about it. She could die and they wouldn't care. They would find someone else to use as a marionette for their own political ambitions. Watch them:
CNN ANCHOR: She is the teenager on strike for the planet. Time's Person of the Year. Greta Thunberg is leading a generation of climate kids.
LAURA COATES, CNN: Greta, first of all, I got to reassess my life choices. That is a force to be reckoned with.
BILL WEIR, CNN: Greta Thunberg, the Swedish girl who inspired so much, she said she was in a deep depression when she understood the warnings of science, but turned that depression into action. I see the result here today.
MIKA BRZEZINSKI, MSNBC: Greta's passion does reflect what really is happening and we're still arguing whether or not it exists?
She turned that depression into action. Well, no, she didn't, actually. She's living in hell. Like most emotionally unbalanced children, she's suffering, but you don't care because you can use her. You did nothing to support her, to love her, to cure for serious mental illness.
No, you used her to take more power and if anyone says anything about it, if you think children shouldn't go on television to talk about climate policy and energy, then you're a bigot. You hate children. You hate Greta Thunberg; And by the way, as you sit and watch the results of the lunatic policy that she's espousing without even understanding Europe's energy grid collapsing, then you're a bad person.
As Vox reported, "Attacks on Greta Thunberg expose the stigma autistic girls face. " No, they expose the callousness and cynicism of her parents and MSNBC anchors and everybody else who used her suffering to their own benefit. The Washington Post complained "Autistic young people deserve serious respect and attention, not dismissal as the pawns of others. " Really? Whose pawn is Greta Thunberg? Yours. Researchers at the University of Albany even published a study on "Analysis of ageism, sexism and ableism in user comments and YouTube videos about climate activist Greta Thunberg. "
So again, you need to listen to her because she's not well, but if you note that she's not well, you're a bigot. It's the same, exactly the same dynamic you're watching what the president of the United States, Joe Biden, who is not well and everybody knows it. Joe Biden mourned the death of Congresswoman Jackie Walorski publicly. Then a few weeks later, he asked, totally befuddled, why isn't she here at the event? But if you notice it, that happened, you're the ageist.
WHOOPI GOLDBERG: You know, my gosh, come on. You can't go after him for, you know, not giving aid to Florida or not tackling the infrastructure and he's giving aid to Ukraine. So, you can't go after him for that, but you can go after him for forgetting that someone has passed. I mean, and she passed last month, not like 100 years ago.
SUNNY HOSTIN: I think what it really shows is that this country is so ageist. This country has a problem with age and I think they need to stop weaponizing his age. I hate that about this country.
This country has a problem with age so if you don't like the fact the commander-in-chief, the guy who commands our nuclear arsenal, is deranged because of age, which he is, then you're the bigot. But underneath all of this is this single most cynical political move in the history of this country, and that is elevating Joe Biden precisely because he is fading away, because he is demented. That's why they chose him.
They had an option, actually. His name was Bernie Sanders. We're hardly endorsing Bernie Sanders' program, but Bernie Sanders could think clearly. And the people who run the Democratic Party just hated what he had to say. So, they picked a guy who had nothing going on upstairs, was flatlining mentally, so they couldn't control him. That's exactly what they're doing with Fetterman.
|
english
|
<filename>core/src/main/java/org/openhubframework/openhub/core/circuitbreaker/AbstractCircuitBreaker.java<gh_stars>10-100
package org.openhubframework.openhub.core.circuitbreaker;
import java.time.Instant;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.openhubframework.openhub.spi.circuitbreaker.CircuitBreaker;
import org.openhubframework.openhub.spi.circuitbreaker.CircuitConfiguration;
import org.openhubframework.openhub.spi.circuitbreaker.CircuitDownException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
/**
* Simple {@link CircuitBreaker} implementation base, does use {@link CircuitState} domain object
* to store state.
*
* All the interface methods are implemented, in its minimal variant only method
* to resolve CircuitState for given circuit is needed to be implemented.
*
* There are multiple "hooks" method that can be overriden - onSuccessCall, onCircuitDown,
* see javadoc directly on each of them.
*
* @author <NAME>
* @see CircuitState
* @since 2.2
*/
public abstract class AbstractCircuitBreaker implements CircuitBreaker {
private static final Logger LOG = LoggerFactory.getLogger(AbstractCircuitBreaker.class);
@Override
public Processor updateCircuitState() {
return exchange -> {
final CircuitConfiguration circuitConfiguration = getCircuitConfiguration(exchange);
final String circuitName = circuitConfiguration.getCircuitName();
// logic based on exception
if (exchange.getProperty(Exchange.EXCEPTION_CAUGHT) != null
|| exchange.getException() != null) {
final Throwable ex = exchange.getException() != null
? exchange.getException()
: exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
if (!(ex instanceof CircuitDownException)) {
LOG.trace("Circuit '{}' increase error count.", circuitName);
// failed call handling
onFailedCall(circuitName);
// update circuit state and check whether to break circuit or not
final CircuitState circuitState = getCircuitState(circuitName);
if (shouldBreakCircuit(circuitState, circuitConfiguration)) {
onCircuitSwitchDown(circuitName);
}
} else {
// do nothing, as circuit is down
LOG.trace("Circuit '{}' is down, skipping.", circuitName);
}
} else {
LOG.trace("Circuit '{}' increase success count.", circuitName);
// no exception - just update success count
try {
// success call handling
onSuccessCall(circuitName);
} catch (final Exception e) {
LOG.error("Unable to process circuit breaker data (step 1)", e);
}
}
// remove old values (if present)
try {
removeOldEntries(circuitConfiguration);
} catch (final Exception e) {
LOG.error("Unable to process circuit breaker data (step 2)", e);
}
};
}
@Override
public Processor checkCircuitIsOpen() throws CircuitDownException {
return exchange -> {
final CircuitConfiguration circuitConfiguration = getCircuitConfiguration(exchange);
// if circuitBreaker for circuit is disabled, do not check anything
if (!circuitConfiguration.isEnabled()) {
return;
}
final CircuitState circuitState = getCircuitState(circuitConfiguration.getCircuitName());
Assert.notNull(circuitState, "the circuitState must not be null");
// if circuit is down, do not continue, throw exception
if (circuitState.getLastShortcutTimestamp() + circuitConfiguration.getSleepInMillis() > Instant.now().toEpochMilli()) {
LOG.trace("Circuit is down, lastShortcutTimestamp is {}, will try again after {}.",
circuitState.getLastShortcutTimestamp(),
circuitState.getLastShortcutTimestamp() + circuitConfiguration.getSleepInMillis());
// do not continue, as circuit is down
throw new CircuitDownException("circuit '" + circuitConfiguration.getCircuitName() + "'");
}
// otherwise just continue
};
}
/**
* Logic to resolve if circuit should change it state to down.
*
* @param circuitState the circuit state.
* @param circuitConfiguration the circuit configuration.
* @return flag, true if circuit should switch down.
*/
protected boolean shouldBreakCircuit(CircuitState circuitState, CircuitConfiguration circuitConfiguration) {
final long windowStart = Instant.now().toEpochMilli() - circuitConfiguration.getWindowSizeInMillis();
// algorithm to determine whether it should break the circuit
final long successCount = circuitState.getSuccessCallList().stream()
.filter(it -> it > windowStart)
.count();
final long failedCount = circuitState.getFailedCallList().stream()
.filter(it -> it > windowStart)
.count();
// sum requests in window, if not enough, just continue
if (successCount + failedCount < circuitConfiguration.getMinimalCountInWindow()
|| successCount + failedCount < 1) {
LOG.trace("Not enough requests in window, skipping.");
return false;
}
final double failedCountPercentage = ((double) failedCount / (successCount + failedCount)) * 100;
LOG.trace("FailedCountPercentage {} %, successCount = {}, failedCount = {}",
failedCountPercentage, successCount, failedCount);
if (failedCountPercentage >= circuitConfiguration.getThresholdPercentage()) {
LOG.trace("Threshold triggered with '{}'% request failed, threshold is '{}'",
failedCountPercentage,
circuitConfiguration.getThresholdPercentage());
return true;
}
return false;
}
/**
* Get circuit state for circuit identified by its name.
*
* @param circuitName the name of circuit.
* @return CircuitState, not null, if circuit is misconfigured, exception should be thrown.
*/
protected abstract CircuitState getCircuitState(String circuitName);
/**
* On each successful exchange in given circuit.
*
* @param circuitName the name of circuit.
*/
protected void onSuccessCall(String circuitName) {
final CircuitState circuitState = getCircuitState(circuitName);
Assert.notNull(circuitState, "the circuitState must not be null.");
// insert success event
circuitState.getSuccessCallList().add(Instant.now().toEpochMilli());
}
/**
* On each failed exchange in given circuit.
* Failed means exception is present.
*
* @param circuitName the name of circuit.
*/
protected void onFailedCall(String circuitName) {
final CircuitState circuitState = getCircuitState(circuitName);
Assert.notNull(circuitState, "the circuitState must not be null.");
// insert failed event
circuitState.getFailedCallList().add(Instant.now().toEpochMilli());
}
/**
* Invoked once, when circuit state is changed to down.
*
* @param circuitName the name of circuit.
*/
protected void onCircuitSwitchDown(String circuitName) {
final CircuitState circuitState = getCircuitState(circuitName);
Assert.notNull(circuitState, "the circuitState must not be null.");
// reset counters
circuitState.resetFailedCallList();
circuitState.resetSuccessCallList();
// set lastShortcutTimestamp
circuitState.setLastShortcutTimestamp(Instant.now().toEpochMilli());
}
/**
* Invoked each time exchange is passed via CircuitBreaker. It is expected to clean
* old entries in circuit state.
*
* @param configuration the configuration of circuit.
*/
protected void removeOldEntries(CircuitConfiguration configuration) {
Assert.notNull(configuration, "the circuitConfiguration must not be null");
final CircuitState circuitState = getCircuitState(configuration.getCircuitName());
Assert.notNull(circuitState, "the circuitState must not be null.");
circuitState.getSuccessCallList()
.removeIf(it -> it < Instant.now().toEpochMilli() - configuration.getWindowSizeInMillis());
circuitState.getFailedCallList()
.removeIf(it -> it < Instant.now().toEpochMilli() - configuration.getWindowSizeInMillis());
}
}
|
java
|
[
{
"merged": "F:\\AndroidProjects\\WebView\\Camera2Video1\\Application\\build\\intermediates\\res\\merged\\debug\\drawable-mdpi\\ic_action_info.png",
"source": "F:\\AndroidProjects\\WebView\\Camera2Video1\\Application\\src\\main\\res\\drawable-mdpi\\ic_action_info.png"
},
{
"merged": "F:\\AndroidProjects\\WebView\\Camera2Video1\\Application\\build\\intermediates\\res\\merged\\debug\\drawable-mdpi\\ic_launcher.png",
"source": "F:\\AndroidProjects\\WebView\\Camera2Video1\\Application\\src\\main\\res\\drawable-mdpi\\ic_launcher.png"
}
]
|
json
|
Skip the lengthy reading. Click 'Summarize Content' for a concise summary powered by Vikas AI.
Despite rapid increase in the quantity of technical students in India, little is known about their quality. In particular, less information is available about the major specific competencies, knowledge and soft skills of individuals. So, this project aims to assess the technical knowledge, creativity and cognitive skills of undergraduate and postgraduate students of India. Earlier the similar project was implemented by Stanford University, USA. They have implemented the student assessment for various countries such as USA, China, Russia and India. For India, they have selected 167 technical institutes for their study.
Student Learning Assessment Project (SLA) is to evaluate technical students of India and to assess their overall qualitative and quantitative growth during the course of study in order to get suitable employment. All India Council for Technical Education (AICTE) SLA (PARAKH) project has been designed to measure the benchmark levels and gains in academic and higher-order thinking skills of students and faculties to understand the various factors that affect skill development in technical institutes across India.
Gathering and analysing data about student’s achievement is only worthwhile if the information is utilized to improve outcomes for students. The data gathered by the project is used to evaluate the performance of lower level (academic gain) and higher-order thinking skills gains and provide the enhancement methods by which the Indian students can lead for a better opportunity in their profession and personal graph.
All India Council for Technical Education (AICTE) is going to implement a large-scale program to assess and improve the skills of engineering students in India in AICTE approved Technical Institutions across the country. In respect of analysis, each of the online assessments (including those testing academic skills and those testing higher order thinking skills) may be used for comparing student outcomes. More specifically, each of the online assessments will be considered as unidimensional, reliable and good at measuring a range of student ability. The vast majority of the items should also demonstrate psychometric characteristics of students.
Vision of AICTE SLA (PARAKH) is to motivate bridging the gap between academics and industry by providing a platform for self-assessment of knowledge and 21st century skill capabilities in students and faculty members to ensure global competitiveness.
AICTE SLA (PARAKH) will enable policymakers and institutions to assess global competitiveness of students, faculty members and stakeholders to trigger necessary interventions creating a more effective system of education in the country.
India's higher education system is the third largest in the world, next to the United States and China. As of 2021, India has over 1000 universities, with a break up of 154 central universities, 438 state universities, 126 deemed universities, 395 private universities, 7 institutes under State Legislature Act and 159 Institutes of National Importance which include IIMs, AIIMS, IITs, IIITs, IISERs and NITs among others. Other institutions include 52627 colleges as government degree colleges, private colleges, standalone institutes and post-graduate research institutions.
Indian higher education is radical in terms of accessibility, and needs reforms in standards, providing values and pacing. A focus on enforcing both streamlining and holding higher standards of curriculum, value-oriented and innovative, personalization of the sector for students to gain immediate and valid transferable credentials in their own pace, empowering students to enter the work-force with necessary building blocks of knowledge that leads to set of skills from an academic fields. India can be a world leader by creating skilled technical persons who have good academic knowledge and are able to apply academic information to innovate new research applications by the critical, analytical and cognitive skills. Prior to this project, very less work has been done in India where cognitive skills are assessed to enhance growth for the students.
So, through this project AICTE would be assessing the quality of students and faculty members by evaluating their academic, social, cognitive, critical and behavioral development during their course of study. Student Learning Assessment is likely to be enhanced further as this information will be used by faculty members and the institutions to:
(If you have any comments / suggestions on the above content, please post them here)
|
english
|
use
{
crate :: { JoinHandle, SpawnHandle, LocalSpawnHandle, YieldNow } ,
futures_task :: { SpawnError, FutureObj, LocalFutureObj } ,
futures_util :: { future::{ FutureExt }, task::{ SpawnExt, LocalSpawnExt } } ,
futures_executor :: { LocalSpawner } ,
};
impl<Out: 'static + Send> SpawnHandle<Out> for LocalSpawner
{
fn spawn_handle_obj( &self, future: FutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError>
{
let (fut, handle) = future.remote_handle();
self.spawn( fut )?;
Ok( JoinHandle::remote_handle(handle))
}
}
impl<Out: 'static> LocalSpawnHandle<Out> for LocalSpawner
{
fn spawn_handle_local_obj( &self, future: LocalFutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError>
{
let (fut, handle) = future.remote_handle();
self.spawn_local( fut )?;
Ok( JoinHandle::remote_handle(handle) )
}
}
#[ cfg( feature = "timer" ) ]
//
#[ cfg_attr( nightly, doc(cfg(all( feature = "timer", feature = "async_global" ))) ) ]
//
impl crate::Timer for LocalSpawner
{
fn sleep( &self, dur: std::time::Duration ) -> futures_core::future::BoxFuture<'static, ()>
{
futures_timer::Delay::new( dur ).boxed()
}
}
impl YieldNow for LocalSpawner {}
|
rust
|
---
layout: post
title: "Development of An Android Application for Object Detection Based on Color, Shape, or Local Features"
date: 2017-03-10 21:39:49
categories: arXiv_CV
tags: arXiv_CV Object_Detection Face Detection Recognition
author: <NAME>, <NAME>, <NAME>
mathjax: true
---
* content
{:toc}
##### Abstract
Object detection and recognition is an important task in many computer vision applications. In this paper an Android application was developed using Eclipse IDE and OpenCV3 Library. This application is able to detect objects in an image that is loaded from the mobile gallery, based on its color, shape, or local features. The image is processed in the HSV color domain for better color detection. Circular shapes are detected using Circular Hough Transform and other shapes are detected using Douglas-Peucker algorithm. BRISK (binary robust invariant scalable keypoints) local features were applied in the developed Android application for matching an object image in another scene image. The steps of the proposed detection algorithms are described, and the interfaces of the application are illustrated. The application is ported and tested on Galaxy S3, S6, and Note1 Smartphones. Based on the experimental results, the application is capable of detecting eleven different colors, detecting two dimensional geometrical shapes including circles, rectangles, triangles, and squares, and correctly match local features of object and scene images for different conditions. The application could be used as a standalone application, or as a part of another application such as Robot systems, traffic systems, e-learning applications, information retrieval and many others.
##### Abstract (translated by Google)
##### URL
[https://arxiv.org/abs/1703.03848](https://arxiv.org/abs/1703.03848)
##### PDF
[https://arxiv.org/pdf/1703.03848](https://arxiv.org/pdf/1703.03848)
|
markdown
|
["Saudara-saudara! Pada waktu saya datang kepadamu dan memberitakan kepadamu tentang rencana Allah yang belum diketahui oleh dunia, saya tidak memakai kebijaksanaan dunia ini atau berbicara dengan kata yang muluk-muluk.","Sebab saya sudah bertekad bahwa selama saya ada bersama kalian, saya tidak akan mengemukakan apa-apa, selain mengenai Yesus Kristus; khususnya bahwa Ia sudah mati disalib.","Ketika saya berada dengan kalian, saya lemah dan gemetar ketakutan.","Berita yang saya sampaikan kepadamu tidak saya sampaikan dengan kata-kata yang memikat menurut kebijaksanaan manusia. Saya menyampaikan itu dengan cara yang membuktikan bahwa <NAME> berkuasa.","Saya berbuat begitu, supaya kepercayaanmu kepada Kristus tidak berdasarkan kebijaksanaan manusia, melainkan berdasarkan kuasa Allah.","Walaupun begitu, di antara orang-orang yang kehidupan rohaninya sudah matang, saya memang berbicara mengenai kebijaksanaan. Tetapi kebijaksanaan ini bukanlah kebijaksanaan dunia, atau kebijaksanaan penguasa-penguasa zaman ini, yang kekuasaannya akan lenyap.","Kebijaksanaan yang saya kemukakan itu ialah kebijaksanaan dari Allah. Kebijaksanaan itu tidak diketahui oleh dunia, tetapi Allah sudah menyediakannya untuk kebahagiaan kita sebelum dunia ini dijadikan.","Tidak seorang pun dari penguasa-penguasa zaman ini yang tahu tentang kebijaksanaan itu. Sebab, seandainya mereka sudah mengetahuinya, tentu mereka tidak akan menyalibkan Tuhan yang mulia itu.","Sebaliknya hal itu adalah seperti yang tertulis dalam Alkitab, \"Apa yang tidak pernah dilihat atau didengar oleh manusia, dan tidak pernah pula timbul dalam pikiran manusia, itulah yang disediakan Allah untuk orang-orang yang mengasihi-Nya.\"","Tetapi Allah sudah menyatakannya kepada kita dengan perantaraan Roh-Nya. Roh Allah itu menyelidiki segala sesuatu, sampai kepada rencana-rencana Allah yang paling tersembunyi sekalipun.","Sebab yang mengetahui isi hati seseorang adalah roh orang itu sendiri, bukan? Begitu juga mengenai Allah. Yang mengetahui isi hati Allah hanyalah Roh Allah sendiri!","Dan kita tidak diberi roh dunia ini, melainkan Roh yang dari Allah, supaya kita mengetahui semua yang telah dianugerahkan Allah kepada kita.","Sebab itu, bila kami menjelaskan hal-hal mengenai Allah kepada orang-orang yang mempunyai Roh Allah, kami tidak mengemukakannya menurut kebijaksanaan manusia, melainkan menurut ajaran Roh Allah.","Orang yang tidak mempunyai Roh Allah, tidak dapat menerima apa yang dinyatakan oleh Roh itu. Sebab bagi orang itu hal-hal tersebut seperti suatu kebodohan saja. Orang itu tidak dapat mengertinya, sebab hal-hal itu hanya dapat dinilai secara rohani.","Orang yang mempunyai Roh Allah dapat menilai segala sesuatu, tetapi tidak seorang pun berhak menilai Dia.","Dalam Alkitab tertulis, \"Siapakah yang tahu pikiran Tuhan? Dan siapakah dapat menasihati-Nya?\" Kitalah yang mempunyai pikiran yang sama dengan Kristus!"]
|
json
|
.column {
float: left;
padding-left: 25px;
padding-left: 25px;
}
canvas {
width: 100%;
height: 100%;
}
td {
padding-right: 10px;
}
.menubar {
padding-left: 25px;
}
.menubar input[type=button],
.menubar select {
font-family: monospace;
min-height: 25px;
min-width: 75px;
}
#memoryCanvasContainer {
height: 100%;
}
.body-error-banner {
font-family: monospace;
height: 1em;
width: 100%;
text-align: center;
font-size: 120%;
color: black;
background-color: #fff363;
margin: 5px;
padding: 5px;
}
|
css
|
#!/usr/bin/env python
#
# Requires autopep8 to be installed.
# Script for cleaning up most PEP8 related errors checked by the pre-commit hook.
#
import os
import subprocess
import sys
# don't fill in both of these
# good codes
select_codes = ["E111", "E101",
"E201", "E202", "E203", "E221", "E222", "E223", "E224", "E225",
"E226", "E227", "E228", "E231", "E241", "E242", "E251",
"E303", "E304",
"E502",
"E711", "E712", "E713", "E714", "E721",
"E741", "E742", "E743",
"W191",
"W291", "W293", "W292",
"W391",
"W602", "W603",
]
ignore_codes = []
# Add things like "--max-line-length=120" below
overrides = ["--max-line-length=120",
]
def system(*args, **kwargs):
kwargs.setdefault('stdout', subprocess.PIPE)
proc = subprocess.Popen(args, **kwargs)
out, err = proc.communicate()
return out
def main():
cwd = os.getcwd()
if '.git' not in os.listdir(cwd):
print('Must be run from the root of the repository.')
sys.exit(1)
files = system('git', 'diff', '--cached', '--name-only').decode("utf-8")
files = [file.strip() for file in files.split('\n') if file.strip().endswith('.py')]
if not files:
sys.exit(0)
args = ['autopep8', '--in-place']
if select_codes and ignore_codes:
print('Error: select and ignore codes are mutually exclusive')
sys.exit(1)
elif select_codes:
args.extend(('--select', ','.join(select_codes)))
elif ignore_codes:
args.extend(('--ignore', ','.join(ignore_codes)))
args.extend(overrides)
args.extend(files)
output = system(*args, cwd=cwd)
if output:
print(output.decode("utf-8"),)
sys.exit(1)
sys.exit(0)
if __name__ == '__main__':
main()
|
python
|
Beyond the personal opportunism, politics of poverty and frictions of race, two ideas are at war in the small north-eastern state of Tripura which will elect a new government next Sunday. The Marxist head of the ruling Left Front, Manik Sarkar, described as the “cleanest and poorest chief minister in the country”, is almost the sole standard-bearer left in India today of a radical alternative to the politics of class, caste and capital.
He may be in danger of being swept away by the saffron wave represented by the BJP in alliance with the Indigenous Peoples’ Front of Tripura (IPFT) and a group of Congress turncoats who flirted with Mamata Banerjee’s Trinamool Congress before finding refuge in the Hindutva camp.
Capturing Tripura would be a major step in fulfilling Amit Shah’s dream of bringing all eight north-eastern states into the NDA’s fold. No wonder the BJP has deployed all its heavy artillery from Narendra Modi to Smriti Irani for the contest for 60 assembly seats. It already rules Assam, Arunachal Pradesh and Manipur; its partners in the North-East Democratic Alliance govern Nagaland and Sikkim. The BJP is also making a strong bid for Meghalaya and Nagaland which are going to the polls this month. A Congress-mukt Mizoram will be the last challenge for Modi and Shah.
Of course, neither Hindutva nor the Marxist revolution that never was is ever mentioned in this battle of ideologies. The ostensible emphasis is on poverty alleviation. The BJP’s Vision Document 2018 promises prosperity while the party panders to local sentiment by saying it will highlight the former royal family’s achievements, rename Agartala airport after its creator, Maharaja Bir Bikram Manikya Kishore Deb Barman, and upgrade it to international status. Sarkar, unique among chief ministers in not owning a house or car and not being guarded by security personnel, seems rather a mild antagonist for a life-or-death struggle that is crucial to the BJP’s ambitions.
Barring five years from 1988 to 1993, his Left Front has been in power since 1978 and dominates the assembly with 51 MLAs. Tripura boasts the country’s highest literacy rate and highest concentration of schools. It claims creditable paddy production, extensive rural electrification and a network of blood banks. But unemployment is high, with more than six lakhs registered as unemployed in a population of about 38 lakhs. That is one grievance. Another is the on-again, off-again tribal demand for a separate state.
The challenge of jobs, capsuled into the popular “Ten-three-two-three” crisis, acquired dramatic poignancy last March when the Supreme Court cancelled the appointment of 10,323 government school teachers. This was a major blow in a small state with few industries where the government is still the biggest employer. Sarkar’s government made the appointments in December 2013 on the basis of “merit” and “need” through an open-interview process without written tests.
There were more than a lakh of applicants and the unsuccessful ones went to court accusing the government of violating the Right to Education Act as well as the National Council for Teachers’ Education’s guidelines. The Tripura High Court ruled in their favour, the Supreme Court agreeing that appropriate recruitment rules were not followed.
The controversy played into the hands of the BJP which holds out the promise of a “one-time relaxation” of appointment norms to save jobs. Prakash Javadekar, the Union Human Resource Development Minister, reportedly told a delegation of Tripura teachers that the Centre would amend the Right to Education Act to help them. Sudip Roy Barman, one of the Congress-to-Trinamool-to-BJP defectors went even further. He is quoted as saying a generous NDA government in New Delhi would save the jobs irrespective of “whether the BJP or the Left comes to power” in Tripura.
The Left Front is hard put to it to counter such magnanimity. “We are a pro-poor government” pleads the CPI(M)’s state general secretary, Bijan Dhar, pointing out that the appointments were made “to help backward sections of society” in accordance with rules that the first Left Front formulated in 1978. The courts haven’t mentioned corruption, he adds. But the courts have frustrated plans to recruit 12,000 “non-teaching staff”, presumably to accommodate the 10,323 teachers threatened with unemployment.
The irony is that while the two sides are fighting ostensibly to create jobs and more than 30 per cent of the inhabitants are tribals, the 297 candidates are among the richest in the land. Of the 35 crorepatis in the fray, 18 are from the BJP, their assets averaging Rs 1. 35 crores per head. The average individual worth of the 59 Congress candidates – nine of them crorepatis -- is Rs 53. 16 lakhs. The chief minister may be poor and honest but four of his Marxist candidates are worth more than a crore each.
With factions at every stage – among tribals, among unemployed teachers, among legislators – battle lines are somewhat blurred as Sarkar defends India’s last red fort against the saffron assault.
(Mr Datta-Ray is a journalist and author of several books. He has been editor of The Statesman. Views are personal)
|
english
|
export * from './compodoc';
|
typescript
|
from selenium.common.exceptions import NoSuchElementException, TimeoutException
class DomHelper(object):
driver = None
waiter = None
def open_page(self, url):
self.driver.get(url)
def reload_page(self):
self.driver.refresh()
def print_el(self, element):
print('tag: ' + element.tag_name + ' id: ' + element.get_attribute('id') + ' class: ' + element.get_attribute('class') + ' text: ' + element.text)
def get_el(self, selector):
if isinstance(selector, str):
return self.driver.find_element_by_css_selector(selector)
else:
return selector
def get_els(self, selector):
if isinstance(selector, str):
return self.driver.find_elements_by_css_selector(selector)
else:
return selector
def get_child_el(self, parent, selector):
try:
return parent.find_element_by_css_selector(selector)
except NoSuchElementException:
return None
def get_child_els(self, parent, selector):
return parent.find_elements_by_css_selector(selector)
def is_el_present(self, selector):
try:
self.driver.find_element_by_css_selector(selector)
return True
except NoSuchElementException:
return False
def verify_el_present(self, selector):
if not self.is_el_present(selector):
raise Exception('Element %s not found' % selector)
def is_el_visible(self, selector):
return self.get_el(selector).is_displayed()
def click_button(self, selector):
if self.driver.name == 'iPhone':
self.driver.execute_script('$("%s").trigger("tap")' % (selector))
else:
self.get_el(selector).click()
def enter_text_field(self, selector, text):
text_field = self.get_el(selector)
text_field.clear()
text_field.send_keys(text)
def select_checkbox(self, selector, name, deselect=False):
found_checkbox = False
checkboxes = self.get_els(selector)
for checkbox in checkboxes:
if checkbox.get_attribute('name') == name:
found_checkbox = True
if not deselect and not checkbox.is_selected():
checkbox.click()
if deselect and checkbox.is_selected():
checkbox.click()
if not found_checkbox:
raise Exception('Checkbox %s not found.' % (name))
def select_option(self, selector, value):
found_option = False
options = self.get_els(selector)
for option in options:
if option.get_attribute('value') == str(value):
found_option = True
option.click()
if not found_option:
raise Exception('Option %s not found' % (value))
def get_selected_option(self, selector):
options = self.get_els(selector)
for option in options:
if option.is_selected():
return option.get_attribute('value')
def is_option_selected(self, selector, value):
options = self.get_els(selector)
for option in options:
if option.is_selected() != (value == option.get_attribute('value')):
print(option.get_attribute('value'))
return False
return True
def is_text_equal(self, selector, text):
return self.get_el(selector).text == text
def verify_inputs_checked(self, selector, checked):
checkboxes = self.get_els(selector)
for checkbox in checkboxes:
name = checkbox.get_attribute('name')
if checkbox.is_selected() != (name in checked):
raise Exception('Input isnt checked as expected - %s' % (name))
def verify_option_selected(self, selector, value):
if not self.is_option_selected(selector, value):
raise Exception('Option isnt selected as expected')
def verify_radio_value(self, selector, value):
value = str(value)
radios = self.get_els(selector)
for radio in radios:
radio_value = radio.get_attribute('value')
if radio.is_selected() and radio_value != value:
raise Exception('Radio with value %s is checked and shouldnt be' % radio_value)
elif not radio.is_selected() and radio_value == value:
raise Exception('Radio with value %s isnt checked and should be' % radio_value)
def verify_text_field(self, selector, text):
text_field = self.get_el(selector)
value = text_field.get_attribute('value')
if value != text:
raise Exception('Text field contains %s, not %s' % (value, text))
def verify_text_value(self, selector, value):
text_field = self.get_el(selector)
if text_field.get_attribute('value') != value:
raise Exception('Value of %s not equal to "%s" - instead saw "%s"' % (selector, value, text_field.get_attribute('value')))
def verify_text_of_el(self, selector, text):
if not self.is_text_equal(selector, text):
raise Exception('Text of %s not equal to "%s" - instead saw "%s"' % (selector, text, self.get_el(selector).text))
def verify_text_in_els(self, selector, text):
els = self.get_els(selector)
found_text = False
for el in els:
if text in el.text:
found_text = True
if not found_text:
raise Exception('Didnt find text: %s' % (text))
def verify_text_not_in_els(self, selector, text):
els = self.get_els(selector)
found_text = False
for el in els:
if text in el.text:
found_text = True
if found_text:
raise Exception('Found text: %s' % (text))
def is_button_enabled(self, selector):
return (self.get_el(selector).get_attribute('disabled') == 'false')
def check_title(self, title):
return self.driver.title == title or self.driver.title == 'eatdifferent.com: ' + title
def wait_for(self, condition):
self.waiter.until(lambda driver: condition())
def check_num(self, selector, num):
els = self.get_els(selector)
return len(els) == num
def wait_for_num_els(self, selector, num):
try:
self.waiter.until(lambda driver: self.check_num(selector, num))
except TimeoutException:
raise Exception('Never saw %s number of els for %s' % (num, selector))
def wait_for_visible(self, selector):
try:
self.waiter.until(lambda driver: self.is_el_visible(selector))
except TimeoutException:
raise Exception('Never saw element %s become visible' % (selector))
def wait_for_hidden(self, selector):
try:
self.waiter.until(lambda driver: not self.is_el_visible(selector))
except TimeoutException:
raise Exception('Never saw element %s become hidden' % (selector))
def wait_for_button(self, selector):
try:
self.waiter.until(lambda driver: self.is_button_enabled(selector))
except TimeoutException:
raise Exception('Never saw button %s enabled' % (selector))
def wait_for_text(self, selector, text):
try:
self.waiter.until(lambda driver: self.is_text_equal(selector, text))
except TimeoutException:
raise Exception('Never saw text %s for %s' % (text, selector))
def wait_for_el(self, selector):
try:
self.waiter.until(lambda driver: self.is_el_present(selector))
except TimeoutException:
raise Exception('Never saw element %s' % (selector))
def wait_for_title(self, title):
try:
self.waiter.until(lambda driver: self.check_title(title))
except TimeoutException:
raise Exception('Never saw title change to %s' % (title))
def __init__(self, driver, waiter):
self.driver = driver
self.waiter = waiter
|
python
|
PM Modi said development of any vaccines is generally a time-taking process but vaccines against Covid-19 have been developed in record time.
By India Today Web Desk: Launching the nationwide Covid-19 vaccination drive on Saturday, Prime Minister Narendra Modi congratulated scientists and researchers who were engaged in development of the vaccines and said this shows India's scientific talent.
PM Modi said development of any vaccine is generally a time-taking process but vaccines against Covid-19 have been developed in record time.
"In such a short time span, India has been able to develop two vaccines against Covid-19. This is a testimony to the scientific talent of our country," PM Modi said.
In a televised address to the nation, the prime minister said people need to maintain patience during the vaccination drive.
"This is the first time in history that a vaccination drive is being conducted at such large scale. There are over 100 countries whose population is less than 3 crore, while in the first phase of the vaccination itself, India would be vaccinating 3 crore people," PM Modi said.
He added that this figure will be increased to 30 crore by the time the second phase of vaccination is over.
The prime minister said only China, India and the US have a population of more than 30 crore and the number of people who would be vaccinated in the first two phases outline the scale of India's vaccination drive.
Seeking to address concerns over vaccine safety, the PM said India's vaccine infrastructure enjoys global credibility and people should guard themselves against propaganda and misinformation.
, ,
"We have earned our credibility through our track record. Most children in the world get their vaccine shots from the vaccines made in India. The world's trust is on our 'Made in India' vaccines will rise soon. The Indian Covid-19 vaccines are cheaper than foreign shots and are also easy to use. Some foreign vaccines cost close to Rs 5,000 per dose and need to be stored at -70 degrees Celsius," he said.
PM Modi launched the pan India rollout of Covdi-19 vaccination drive at 10:30 am via video conferencing.
A total of 3,006 session sites across all states and UTs will be virtually connected during the launch. Around 100 people will be vaccinated at each session site on the inaugural day.
The vaccination drive is being conducted on the basis identifying priority groups that should receive the vaccine first. Healthcare workers, both in government and private sectors, will receive the vaccine in the first phase of the drive.
As per a press release issued by the government, the nationwide vaccination programme will use Co-WIN, an online digital platform developed by Union Ministry of Health and Family Welfare, which will facilitate real time information of vaccine stocks, storage temperature and individualized tracking of beneficiaries for Covid-19 vaccine.
This digital platform will assist programme managers across all levels while conducting vaccination sessions.
"A dedicated 24x7 call centre - 1075 - has also been established for addressing the queries related to Covid-19 pandemic, vaccine rollout and the Co-WIN software," the press release said.
|
english
|
<filename>assembly/tsconfig.json
{
"extends": "../../../.config/yarn/global/node_modules/assemblyscript/std/assembly.json",
"include": [
"./**/*.ts"
]
}
|
json
|
New Customer?
English (United States)
Français (Canada)
Français (France)
Deutsch (Deutschland)
हिंदी (भारत)
Italiano (Italia)
Português (Brasil)
Español (España)
Español (México)
She won the Best Rookie Voice Actress award at the 8th Seiyuu Awards.
She is a fan of the baseball team, Fukuoka SoftBank Hawks.
As a voice actress, she admires veteran voice actress, Kikuko Inoue.
She completed her studies in narration school during 2009. Upon graduation, she made her debut as a voice actress in the OVA Boku, Otari-man as an office employee.
She debuted as a singer under Pony Canyon on April 2014 with the song Soushou no Innocence. The lead song of the single was also used as the opening theme of Akuma no Riddle.
She also appeared in Hikounin Sentai Akibaranger as Hiroyo Hakase aka Shuri Toyozuki aka Hiroyo Tsuzuki, the voice actress for the character Aoi Ichikawa for the in-universe series Z-Cune Aoi.
In April 2010, she signed to voice talent agency I'm Enterprise.
She opened her fanclub in April 2018; her fanclub's name is "LIFE IS LIKE A SUNNY DAY".
Who Are the 75th Primetime Emmys Acting Nominees?
|
english
|
Vijay Sethupathi completes next!
Actor Vijay Sethupathi was last seen in Tamil in the Su Arunkumar directed Sindhubaadh which released after facing several financial issues and delays and the movie fell short of expectations. He was recently seen making his Malayalam debut with Marconi Mathaai.
The actor was shooting for his next movie Sanga Tamizhan which is directed by Sketch and Vaalu maker Vijay Chandar and produced by Vijaya Productions and the movie was being shot in Karaikudi. Now it has been revealed that with this schedule, the film has been wrapped.
The film's heroine Raashi Khanna shared photos from the last day of shoot on her social media handle, and announced that the movie has completed shoot. Sanga Tamizhan will have Vijay Sethupathi playing dual roles and also star Nivetha Pethuraj, Soori, Sriman, Asutosh Rana and many others.
Follow us on Google News and stay updated with the latest!
|
english
|
R Madhavan is all set for his debut directorial film Rocketry: The Nambi Effect. Apart from directing the film, Madhavan also essays the protagonist Nambi Narayanan. Rocketary: The Nambi Effect will release in Hindi, Telugu, Malayalam, Tamil, English and Kannada languages.
Madhavan said, “Viewers have started enjoying regional cinemas as they get value for money by the crisp content delivered by great actors and great scripts. However, with crisp subtitles and exquisite dubbing, regional cinema has now become more adaptable and more audience-friendly. The scenarios post-COVID 19 has changed the game to the next level and the acceptability of regional languages is seen across the globe and this, according to me, is a beginning of the ‘new normal’ for regional movies. "
Talking about embracing OTT space at a very early stage, he said, “I have been exploring the OTT space for a long time now and what I enjoy about the space is the fact that they have opened gates for independent films that weren’t available to the audiences earlier. It is wonderful that so many gems are being appreciated for their talent and storyline, and it’s no more about big budgets but exhilarating stories. For an artist personally it’s always the script and I see through OTT we’ve been able to encourage young talent and that’s what I appreciate. And believe that as the audience is evolving with new experiences, as an artist I need to also explore these new realms to form a connection and tell my story. I feel like this is the future of the entertainment industry to move beyond mainstream storytelling and that excites me. "
Madhavan, who was diagnosed with Covid-19 earlier this year, spoke about his recovery. “The doctors have been no less than angels who are struggling constantly in order to save lives, even if that means putting their own lives at risk. As a society, it’s time for us to rise together and extend our own hand of care towards our doctors’ community for all they have done for us and our loved ones. A humble request to all my fans to be safe and sound and to stay indoors and encourage each one of you to use sanitizer and wear a mask while going out. "
He continued, “The past year has been tough for all of us across the world but has also taught us the importance of community and humanity and that has brought us together even more. I think the extraordinary care of our doctors and healthcare workers during this time and always, has given a new meaning to humanity for me personally. In all the chaos, uncertainty, and stress that the virus brought upon us, my belief that family always stands with you has only been strengthened and the love and care of family and friends around me has helped me stay positive. It has also made me realise the things that are important in life - quality time with family and learning new things. It’s been a time where I feel I can challenge myself to venture into new areas and that’s been the biggest learning, to be agile even in these uncertain times. "
Dr Dnyaneshwar Bhosale’s story has touched millions of hearts. What’s your personal takeaway from the short film and what inspired you to join the campaign? He said, “COVID has been difficult on each one of us but it is our Doctors and healthcare workers who’ve been our strength. The third edition of Vicks Touch Of Care campaign recognizes the powerful impact of this care through the real-life story of late Dr Dnyaneshwar Bhosale. The film moved me to relive not only what the doctors go through but also their families and that moved me to tears. The film made me realise how selfless care can transform and save lives. This had inspired me to stand in support and lend my voice to this campaign, seeing Mrs Bhosale display immense courage after everything she’s been through to ensure her husband’s story is alive among the little children of Latur. Had me thinking that we should also do our small bit in keeping their care alive, even if it is by just ensuring our loved ones are safe and cared for. "
He added, “While this whole year has been a time of uncertainty, it surely has been a time of recognizing care as the essence of humanity and how it has helped our nation survive. I can’t fathom the strength and courage our health workers and medical community have shown while being brave for all of us. I remember when I tested positive for Covid-19 and had immediately quarantined myself and realized how difficult it is for everyone to stay away from their families. But our medical workers have been doing this for more than a year now, ensuring that our care is above their own and that’s touched my heart personally. Wearing the PPE kit for hours and taking care of us relentlessly while leaving their families behind is truly courageous and inspiring. Even when I was isolated, it was the virtual consulting that I received from family doctors that helped in my speedy recovery. "
The short film is based on the inspiring journey of Dr Bhosale’s selfless acts of care as he left no stone unturned to ensure many less fortunate children received life-saving medical attention during the pandemic. Dr Bhosale left behind his wife, kids and his dreams of building his own pediatric hospital. The short film is a solemn reminder that like Dr Bhosale, hundreds of doctors lost their lives during the pandemic leaving their families and dreams behind.
Read all the Latest News, Breaking News and Coronavirus News here.
|
english
|
<reponame>gravity-addiction/nstack-monorepo
import { CommonModule } from '@angular/common';
import { Component, Input, NgModule, OnInit } from '@angular/core';
import { NgxSpinnerModule, NgxSpinnerService } from 'ngx-spinner';
@Component({
selector: 'app-spinner',
templateUrl: './spinner.component.html',
styleUrls: ['spinner.component.scss'],
})
export class SpinnerComponent implements OnInit {
@Input() showSpinner = true;
@Input() textSpinner = '';
constructor(
private spinner: NgxSpinnerService
) { }
ngOnInit() {
if (this.showSpinner) {
this.spinner.show();
}
}
}
@NgModule({
imports: [
CommonModule,
NgxSpinnerModule,
],
declarations: [
SpinnerComponent,
],
exports: [
SpinnerComponent,
],
})
export class SpinnerComponentModule { }
|
typescript
|
import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
const propTypes = {
/** Aggiunge un ombra per enfatizzare il componente rispetto alla pagina in cui è contenuto */
shadow: PropTypes.bool,
/** Classi addizionali per il componente Headers */
className: PropTypes.string
}
const defaultProps = {
shadow: false
}
const Headers = ({ className, shadow, ...attributes }) => {
const classes = classNames(
'it-header-wrapper',
{
'it-shadow': shadow
},
className
)
return <div className={classes} {...attributes}></div>
}
Headers.propTypes = propTypes
Headers.defaultProps = defaultProps
export default Headers
|
javascript
|
<filename>src/components/Editor/Editor.module.css<gh_stars>0
.Editor {
position: relative;
display: flex;
flex-flow: row nowrap;
align-items: flex-start;
width: 290px;
background: #ffffff;
border: 1px solid #c5d0db;
border-radius: 4px;
}
.EditorInput {
font-style: normal;
font-weight: normal;
font-size: 13px;
line-height: 18px;
width: calc(100% - 36px);
min-height: 36px;
max-height: 150px;
overflow-y: scroll;
padding: 9px;
outline: none;
}
.EditorInput:empty:after {
content: attr(data-placeholder);
color: #939393;
}
.EditorInput::-webkit-scrollbar {
width: 6px;
height: 100%;
margin-right: 4px;
}
.EditorInput::-webkit-scrollbar-thumb {
background: #dae2ea;
border-radius: 3px;
}
.EditorInput * {
cursor: text;
}
.EditorInput a {
color: #2a5885;
}
.EditorInput img[data-type="emoji"] {
width: 16px;
height: 16px;
overflow: hidden;
vertical-align: -3px;
margin: 0 1.5px;
}
.EditorButtonEmoji {
position: relative;
display: flex;
justify-content: center;
align-items: center;
width: 36px;
height: 36px;
padding: 6px;
cursor: pointer;
}
.EditorButtonEmoji:hover .EditorButtonIcon {
fill: #99a2ad;
}
.EditorButtonIcon {
fill: #c5d0db;
}
|
css
|
NEW DELHI: Amid efforts by the Trinamool Congress to expand its influence nationally, especially in the Northeast, after it held of a massive BJP attempt to dethrone it West Bengal in the 2021 elections has raised questions whether it can replicate its success in Tripura. However, the BJP is unfazed at the Mamata Banerjee party's efforts.
BJP national general secretary and Tripura in-charge, Vinod Sonkar weighed in whether the Trinamool offers a challenge in the State, and whether the party's recent trend of changing Chief Ministers in Karnataka, Uttarakhand and Gujarat will be repeated by in Tripura as well.
Following are excerpts of the interview:
Q: The Trinamool has announced it will contest the upcoming civic polls in Tripura? How big a threat do you think it will turn out to be?
A: Everyone has the right to contest elections in a democracy. The Trinamool is not contesting elections in Tripura for the first time. It has previously contested elections in the State during 2018 as well as in 2019 wherein it lost its deposit. Now if the Trinamool wants to contest elections once again, it is free to contest next year, too. It poses no real threat to the BJP.
Q: But the Trinamool is making claims of wresting power in Tripura. Sushmita Dev, once known as a party leader close to the Congress high command, recently joined it. Party supremo Mamata Banerjee has given the responsibility of increasing the support base in Tripura to her nephew Abhishek Banerjee?
A: I will reiterate again that in a democracy any person is free to contest elections anywhere. Everyone has the right to dream. The Trinamool had previously fought elections in Tripura with full preparation but its party candidates lost their deposit on all seats they had contested. In Tripura, a corruption-free, crime-free and development-driven BJP government is functioning under the leadership of Chief Minister Biplab Deb. The Trinamool stands no chance of winning the upcoming polls in Tripura.
Q: Prashant Kishor, who is a master election strategist, has been roped in by the Trinamool who defeated the BJP in West Bengal. Now with the help of Kishor, Mamata Banerjee wants to defeat the ruling BJP in Tripura as well?
A: BJP has come to power in Tripura by defeating the Communist Party of India-Marxist which ruled the State for the last 25 years. Now the saffron party is ready to fight Prashant Kishor. Let us see whether the combination of party organisation and the state government wins the elections or any particular individual.
Q: The BJP is going through a massive churn these days. The BJP governments have also changed sitting Chief Ministers in several Dtates. In Tripura too, such speculation is cropping up. What would you say on this?
Also Watch:
|
english
|
The Ambani Ganesh Chaturthi celebrations witnessed the presence of many of the biggest Bollywood stars, including Ajay Devgn, Rekha, Karisma Kapoor, and many others.
The Ambanis hosted a grand puja and get-together at their Mumbai residence Antilia on September 19, Tuesday, on the auspicious occasion of Ganesh Chaturthi. The lavish celebrations was attended by some of the biggest names from the political, and business industry, and almost all big names from the Hindi cinema industry. As reported earlier, Bollywood's biggest stars including Shah Rukh Khan and Salman Khan were seen arriving at the event along with their families. Many others, including Ajay Devgn, director Rohit Shetty, and senior actor Anil Kapoor, were also a part of the celebrations.
The action superstar of Hindi cinema, who is usually never seen at Bollywood parties and get-togethers, made a rare public appearance at the Ganesh Chaturthi celebrations organized by the Ambani family. Interestingly, Ajay Devgn, who looked dashing as always in a white kurta and a matching pair of trousers, was seen posing with his close friend and frequent collaborator, director Rohit Shetty.
Rekha, the legendary actress was also spotted at the Ambani Ganesh Chaturthi celebrations, and she was seen posing with the renowned designer and her close friend, Manish Malhotra. The veteran star looked gorgeous as ever in a dark maroon kanjeevaram silk saree and matching blouse. She completed her look with traditional temple jewellery ornaments, her signature red-lips make-up look, and a golden potli bag.
Have a look at the pictures below:
Many other famous stars of B'town including Karisma Kapoor, Anil Kapoor, Arjun Kapoor, Riteish Deshmukh and Genelia D'Souza, Aamir Khan's children Ira Khan and Junaid Khan, and others were also spotted at the Ambani Ganesh Chaturthi puja on Tuesday night. Karisma looked gorgeous in a red and white heavily embellished kurta-sharara set. She completed her look with a gajra-claded hairdo and a statement clutch.
Anil Kapoor was seen arriving with his younger son-in-law Karan Boolani at the event and looked dapper as always in an off-white ethnic outfit. The senior superstar completed his look with a pair of statement eyeglasses and brown leather shoes. Arjun Kapoor opted for an all-black look as he made an appearance at the puja. Riteish Deshmukh and Genelia D'Souza walked hand-in-hand and looked perfect together as always. Ira Khan and Junaid Khan, the children of superstar Aamir Khan were also spotted at the event.
Check out the pictures below:
NET Worth: ~ 41.7 MN USD (RS 345 cr)
|
english
|
Free Fire is one of the most popular battle royale games in the world, and its player base continues to grow exponentially every day.
Each player has a unique user ID in Free Fire, which is assigned to them when they create their account. While many regular players are familiar with the ways to find this ID, a number of new players do not know how to find it. Finding your Free Fire ID is pretty simple and can be done in just a few steps.
In this article, we discuss how players can find out their Free Fire ID.
Players must follow the steps given below to find their Free Fire ID:
Step 1: Open Free Fire and click on the profile banner present on the top-left corner of the main menu.
Step 2: The profile of the player opens up.
Step 3: You would then be able to find your Free Fire ID below the username.
If you want to copy the ID, you can simply click on the ‘Copy’ button beside it.
Players require their Free Fire ID for redeem codes, top-up websites as well as to add friends in the game.
Here’s how players can find their friends using the ID:
- Step 1: Open Free Fire and click on the ‘Friends’ icon located on the top of the screen.
- Step 2: Press on the ‘ADD’ tab.
- Step 3: Click on the search bar and paste the Free Fire ID of the respective player.
- Step 4: Press on the ‘+’ present beside the name.
The player will be added to the list of in-game friends after they accept the friend request.
Check out the latest Free Fire MAX redeem codes here.
|
english
|
Anupam Kher took late friend Satish Kaushik's daughter Vanshika out on a lunch to her favourite hotel, and even pouted for her while posing for the camera.
Anupam Kher pays David Dhawan a visit, recalls ‘Varun used to be in half pants'
Anupam Kher gave David Dhawan a surprise visit at his home and shared a video from the place. He talked about how his wife still makes egg bhurji for him.
Anupam Kher injured on film set, Neena says 'Oh what have you done? '
Days after announcing his new film Vijay 69, Anupam Kher suffered injuries. He talked about his mother's reaction as well as Shah Rukh Khan and Hrithik Roshan.
Over two months after Satish Kaushik's death, Anupam Kher shared a photo with his late friend. Satish died on March 8 following a cardiac arrest.
The Kashmir Files actor Anupam Kher talked about the ongoing controversy around The Kerala Story.
Anupam Kher announces his next film; fans think he 'looks like Naseeruddin Shah'
Anupam Kher announced his next project Vijay 69 with YRF. He also shared a poster and fans think he 'looks like Naseeruddin Shah'.
Here are today’s top news, analysis, and opinion. Know all about the latest news and other news updates from Hindustan Times.
Anupam Kher recently talked about his association with present government in India. He called himself 'India centric. '
Anupam Kher recently talked about why celebrities might not want to talk about their political ideologies. He said that he won't be joining any political party.
Anupam Kher said he was a village boy, while Kirron Kher was already a star, when the two met for the first time. They married in 1985.
Anupam Kher on Laal Singh Chaddha boycott calls: 'It wasn't a great film'
Laal Singh Chaddha co-starring Aamir Khan and Kareena Kapoor was released last year amid boycott calls. Now, Anupam Kher has spoken about why the film failed.
Anupam Kher has shared a cryptic tweet about ‘respect’ hours after the Filmfare Awards on Thursday where The Kashmir Files did not win any award.
Anupam Kher and Kangana Ranaut paid their tributes to Tarek Fatah. Anupam called him the ‘most fearless and kind hearted man'. See their posts here.
IB 71 trailer: Vidyut Jammwal unearths India's ‘most confidential mission'
IB 71 trailer: Vidyut Jammwal and Anupam Kher play prominent roles in this espionage thriller that tells the story of India's ‘most confidential mission’.
Here are today’s top news, analysis, and opinion. Know all about the latest news and other news updates from Hindustan Times.
Anupam Kher teases Anil Kapoor as he takes oxygen therapy: Chand pe ja rahe ho?
Anupam Kher teased Anil Kapoor as he took oxygen therapy. As he lay inside a chamber, Anupam asked Anil if he was going to the moon.
Anupam Kher was part of a video also featuring Vanshika, late Satish Kaushik's daughter. He revealed that she said her late dad was a ‘better dancer’ than him.
Anupam Kher, Ajay Devgn, Anushka Sharma and Sanjay Dutt have condoled the death of singer, writer and Yash Chopra's wife Pamela Chopra.
Anil Kapoor could not help but break into tears at the recent memorial of his friend Satish Kaushik, hosted by Anupam Kher.
Here are today’s top news, analysis, and opinion. Know all about the latest news and other news updates from Hindustan Times.
Anupam Kher recalled his conversation with Satish Kaushik hours before his death. At the event hosted for Satish, both Anupam and Anil Kapoor broke down.
Roop Ki Rani Choron Ka Raja was the first film Satish Kaushik directed, but the film did not make a mark.
Anupam Kher was joined by friends and family members of Satish Kaushik as all of them celebrated his birthday.
Anupam Kher has penned a note for his late friend Satish Kaushik on his birth anniversary. A special evening is planned in Mumbai on the occasion.
Anupam Kher has reacted and also shared a video after Anurag Basu made anda dosa for him on Metro In Dino. Watch the video as Anupam gorged on the dosa.
Anupam Kher recently met a 72-year-old background artiste on his film set. He was inspired by her joyful nature and went on to dance with her.
Actor Anupam Kher talks about finding good work even after the age of 60, and what defines a ‘hero’ today.
Here are today’s top news, analysis, and opinion. Know all about the latest news and other news updates from Hindustan Times.
Anupam Kher posted a throwback photograph of a film magazine cover where he is transformed into a woman. It was done for an April Fool's issue in 1991.
|
english
|
<gh_stars>1-10
import sys
sys.path.append('./')
import shutil
import os
from Utilities.file_io.files_load_save import load_yaml
print('Importing dlc takes a while')
from deeplabcut import analyze_videos, filterpredictions
import yaml
import pandas as pd
import cv2
import warnings
import os
computer = "desk"
if computer == "desk":
from database.TablesDefinitionsV4 import *
warnings.warn("\n\n\nCOMPUTER IS: {}\n\n\n".format(computer))
class SetUpTracking:
dlc_proj_name = "DecisionMaze-Federico-2019-10-15\\config.yaml"
def __init__(self, video_folder, pose_folder):
"""[For each video in video folder check if there is a corresponding pose file, if there isn't analyse it with the correct
dlc model [info about dlc models is in database.dlcmodels]]
Arguments:
video_folder {[str]} -- [path to video folder]
pose_folder {[str]} -- [path to pose folder]
"""
if computer == "desk":
self.temp_fld = 'M:\\' # ? on main computer
self.nets_folder = "D:\\Dropbox (UCL - SWC)\\Rotation_vte\\DLC_nets\\Nets"
else:
self.temp_fld = "D:\\Fede"
self.nets_folder = "W:\\branco\\Federico\\raw_behaviour\\maze\\DLC_nets"
self.move_video = True
self.video_folder = video_folder
self.pose_folder = pose_folder
self.video_to_process = self.get_videos_to_process()
self.process()
def get_videos_to_process(self):
# Get all the pose files and then returns a list of video files that don't have a corresponding pose file
# pose_files = [f.split('.')[0][:-5] for f in os.listdir(self.pose_folder) if '.h5' in f]
# return [f for f in os.listdir(self.video_folder) if 'tdms' not in f and f.split('.')[0] not in pose_files
# and os.path.getsize(os.path.join(self.video_folder, f)) > 2000]
return load_yaml("Utilities/file_io/files_to_track.yml")
# return [os.path.join(self.video_folder, tt) for tt in to_track]
def process(self):
"""
dlc analyze_video for each video file with the correct dlc model
rename and move .h5 and .pickle file to the pose_file folder
"""
def move_video(complete_path, move_video_path):
print('Moving video over')
try:
shutil.copy(complete_path, move_video_path)
except:
raise FileNotFoundError('Could not move {} to {}'.format(complete_path, move_video_path))
else:
print(' file moved correctly')
for i, video in enumerate(self.video_to_process):
print('Processing video {} of {}'.format(i+1, len(self.video_to_process)))
# Get the DLC model config path
config_path = os.path.join(self.nets_folder, self.dlc_proj_name)
# Move video to local HD: otherwise analysis breaks if internet connection is unstable
complete_path = os.path.join(self.video_folder, video)
if not os.path.isfile(complete_path):
print("!!! could not find file: ", complete_path)
continue
if os.path.getsize(complete_path) < 2000: continue # Check that video has frames
if self.move_video:
move_video_path = os.path.join(self.temp_fld, video)
if os.path.isfile(move_video_path):
# Video already there, but is it complete
if not os.path.getsize(move_video_path) == os.path.getsize(complete_path):
# Nope, move it
os.remove(move_video_path)
move_video(complete_path, move_video_path)
else:
move_video(complete_path, move_video_path)
# Check that moving video worked correctly
if not os.path.getsize(complete_path) == os.path.getsize(move_video_path): raise ValueError('Smth went wrong while moving the video')
# store the path on the moved video so that we can delete it at the end of the processing
self.move_video_path = move_video_path
try:
cap = cv2.VideoCapture(move_video_path)
if not cap.isOpened(): raise ValueError
except:
print("The video was not moved, analysing the orignal on winstore")
cap = cv2.VideoCapture(complete_path)
if not cap.isOpened():
raise ValueError('Original video file might be corrupted', complete_path)
move_video_path = complete_path # copy variable to be used below
# Run DLC analysis
print("""
Video: {}
Config: {}
""".format(move_video_path, config_path))
analyze_videos(config_path, [move_video_path], gputouse=0, save_as_csv=False)
filterpredictions(config_path, [move_video_path], videotype="mp4", save_as_csv=False, filtertype='median')
# Rename and move .h5 and .pickle
analysis_output = [f for f in os.listdir(self.temp_fld) if 'filtered.h5' in f]
for f in analysis_output:
origin = os.path.join(self.temp_fld, f)
name, ext = f.split('.')
correct_name = f.split('DLC')[0]+'_pose'
dest = os.path.join(self.pose_folder, correct_name+'.'+ext)
try:
shutil.move(origin, dest)
except:
raise FileExistsError('Could not move pose file from {} to {}'.format(origin, dest))
# Remove video file moved to local harddrive
# os.remove(move_video_path)
# All done, on to the next
def cleanup(self):
# Remove the video we moved over to clean up disk
os.remove(self.move_video_path)
if __name__ == "__main__":
if computer != "desk":
paths = load_yaml('paths_spike1.yml')
else:
paths = load_yaml('paths.yml')
SetUpTracking(os.path.join(paths['raw_data_folder'], paths['raw_video_folder']), paths['tracked_data_folder'])
|
python
|
package com.alibaba.bytekit.asm.interceptor;
public class ExceptionInterceptor {
}
|
java
|
Bangladesh star Shakib Al Hasan, Pakistan finisher Asif Ali and Namibia all-rounder David Wiese have all been nominated by the International Cricket Council (ICC) for their Player of the Month award for October.
All three had been in terrific form in the 2021 T20 World Cup in October. In the press release for the Player of the Month award, the ICC wrote:
"Bangladesh's Shakib Al Hasan, Pakistan's Asif Ali and Namibia's David Wiese are the trio nominated for October's accolade, all enjoying fine starts to the tournament in UAE and Oman."
Shakib Al Hasan was among the top run-scorers as well as top wicket-takers in the World Cup, at one point leading both charts, before an injury ruled him out for the rest of the event. He finished the tournament with 131 runs and 11 wickets.
Asif Ali played two brilliant knocks down the order for Pakistan, helping them get two key wins against New Zealand and Afghanistan. Against New Zealand, he hit an unbeaten 27 off 12 deliveries. Ali also smashed four sixes in the penultimate over against Afghanistan, with Pakistan needing 24 to win off the final two overs.
David Wiese played a key role in Namibia's dream run in the T20 World Cup. He played two match-winning knocks to help them progress from the Group Stage to the Super 12s. He has scored 162 runs in the tournament. Wiese was also handy with the ball, picking five wickets.
The Player of the Month award will be decided by public vote.
The ICC also announced the nominees for the Women's Player of the Month award.
Zimbabwe's Mary-Ann Musonda was nominated for the award along with the Irish duo of Laura Delany and Gaby Lewis. The ICC wrote:
"Zimbabwe's Mary-Anne Musonda joins Ireland duo Laura Delany and Gaby Lewis as Player of the Month nominees for October, after a pulsating ODI series between the teams. Led by the nominated pair, Ireland came back from 1-0 down to win the four-match series 3-1."
In the three matches that Ireland won, Gaby Lewis scored 65, 96* and 78. Laura Delany earned a nomination as she scored 189 runs in the series at an average of 63 as she led the team to a series win.
Meanwhile, Mary-Anne Musonda scored 103 in the first match to help Zimbabwe secure a win in their first-ever Women's ODI.
|
english
|
{"name":"<NAME>","dna":[{"code":2.5314,"color":"#FE2712","scale":0.5314},{"code":2.8915,"color":"#FE2712","scale":0.8915},{"code":1.9637,"color":"#FB9902","scale":0.9637},{"code":1.2887,"color":"#FABC02","scale":0.2887},{"code":0.0021,"color":"#696969","scale":0.0021},{"code":1.6233,"color":"#66B032","scale":0.6233},{"code":1.1859,"color":"#0392CE","scale":0.1859},{"code":1.7313,"color":"#3D01A4","scale":0.7313},{"code":1.9867,"color":"#8601AF","scale":0.9867}],"attributes":[{"trait_type":"Speed","value":6},{"trait_type":"Stamina","value":9},{"trait_type":"Strength","value":10},{"trait_type":"Aggression","value":4},{"trait_type":"Creativity","value":1},{"trait_type":"Luck","value":7},{"trait_type":"Focus","value":3},{"trait_type":"Influence","value":8},{"trait_type":"Reflexes","value":10},{"trait_type":"Phobia","value":"Buffets"},{"trait_type":"Vice","value":"Chips, Warmth"},{"trait_type":"Role","value":"Superfan"},{"trait_type":"Personality","value":"Focused"},{"trait_type":"Class","value":"Fair-weather"},{"trait_type":"Affinity","value":"Body"}],"image":""}
|
json
|
{
"name": "com.tymski.scene-reference",
"displayName": "Scene Reference",
"description": "Scene Reference Unity",
"version": "0.0.1",
"unity": "2017.1",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/Tymski/SceneReference.git"
},
"author": {
"name": "Tymski"
}
}
|
json
|
<reponame>team-xitij/xitij16
{
"name": "xitij16",
"short_name": "xitij16",
"description": "Xitij16 Website",
"start_url": "/",
"display": "standalone"
}
|
json
|
Shares of Sun TV slumped 13 per cent after the Enforcement Directorate attached assets worth Rs 742.58 crore in the name of former Telecom Minister Dayanidhi Maran, his brother Kalanithi and other family members in connection with money laundering probe in Aircel-Maxis deal.
Reacting to this, shares of the company tanked 11.36 per cent to Rs 402.25 on the BSE today. On the NSE, it plunged 13.19 per cent to Rs 395.85.
The ED had on Wednesday last week attached Rs 742.58 crore assets of Marans in the Aircel-Maxis deal.
Stock markets were closed on Thursday and Friday for holidays.
Amongst the assets attached are a huge amount of fixed deposits (FDs) and mutual funds held largely by his brother and Sun TV MD Kalanithi. Some assets of Kalanithi’s wife Kaveri have also been attached.
The individual assets include FDs held by Dayanidhi and others worth Rs 7.47 crore, FD worth Rs 100 crore and mutual funds worth Rs 2.78 crore held by Kalanithi. His wife’s FDs worth Rs 1.30 crore and mutual funds of Rs 1.78 crore were also put under attachment.
ED registered its criminal case in this deal in 2012 taking cognisance of an earlier CBI FIR.
|
english
|
<filename>examples/typescript-react/src/components/TodoForm/TodoForm.utils.tsx
import common from 'utils/common';
import taskConstants from '../../constants/task';
import {AddType} from '../../hooks/useTodos/useTodos';
export const separateBadgesAndTask = (task: string): AddType => {
if (!task) {
return null;
}
const splitted = task.split(taskConstants.displayDelimiter.badges);
const title = splitted[0].trim();
if (!title.length) {
return null;
}
const values = splitted.slice(1).reduce((filtered, badge) => {
const text = badge.trim();
return text.length ? [...filtered, text] : filtered;
}, []);
return {
title,
badges: common.removeDuplicates(values)
};
};
|
typescript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.