இது உலக நாடுகளின் ஒரு அகரமுதற் பட்டியலாகும். நீங்கள் நாடுகளை தலைநகரம்வாரியாகவோ, கண்டங்கள் வாரியாகவோ, மக்கள்தொகை வாரியாகவோ, பரப்பளவு வாரியாகவோ, மக்கள்தொகை அடர்த்தி வாரியாகவோ, நேர வலயம் வாரியாகவோ கூட உலவலாம்.
விக்கித் திட்டம் நாடுகள் திட்டமானது தமிழ் விக்கியில் காணப்படும் மற்றும் இனி வரவிருக்கும் நாடுகள் பற்றிய கட்டுரைகள் ஒரு சீர்தரத்துக்குள் கொண்டுவரும் நோக்கில் அமைந்தது.
மேலதிக மூலங்களுக்கு புவியியல் குறிப்புகளைப் பார்க்கவும்.
{| id="toc" border="0"
! :
அ ஆ இ ஈ உ ஊ எ ஏ ஐ ஒ ஓ க ச ட த ந ப ம ய ர ல வ ஹ ஸ ஜ
|}
நாடுவாரியான பட்டியல்
அ
(ஐக்கிய அமெரிக்க நாடுகள்)
ஆ
இ
ஈ
உ
ஊ
எ
ஏ
ஐ
ஒ
ஒல்லாந்து நெதர்லாந்து பார்க்கவும்.
ஓ
க
(முன்னர் ஸயர்)
2
ச
1 (தாய்வான்)
ட
ட்ரினிடாட்டும் டொபாகோவும்
டொங்கா
டொமினிக்கா
டொமினிகன் குடியரசு
டோகோ
த
தாய்வான் (பார் சீனக் குடியரசு1)
தான்ஸானியா
தாஜிக்ஸ்தான்
திமோர் லெஸ்தே (பார் கிழக்குத் திமோர்)
துருக்மெனிஸ்தான்
துவாலு
துனீசியா
தென் கொரியா
தென்னாபிரிக்கா
ந
2
ப
பர்மா (இப்பொழுது மியன்மார்)
(பார் மேற்குக் கரை)
3
ம
6
மேற்கு சமோவா(இப்பொழுது சமோவா)
5
ய
யேமன்
யப்பான்
ர
ரஷ்யா
ருமேனியா
ருவாண்டா
ல
லெய்செஸ்டீன்(Liechtenstein)
வ
4 (Holy See)
ஹ
ஹங்கேரி
ஹைத்தி
ஹொண்டூராஸ்
ஸ
ஸ்பெயின்
சிலவாக்கியா
சிலவேனியா
சாம்பியா
ஸயர் (இப்பொழுது கொங்கோ ஜனநாயகக் குடியரசு)
ஸிம்பாப்வே
ஜ
ஜமேக்கா
ஜிபூட்டி
ஜெர்மனி
ஜோர்தான்
ஜோர்ஜியா
குறிப்புகள்
இங்கு பட்டியலிடப்பட்டுள்ள நாடுகளின் நிலைமை / இறைமை பற்றிய விபரங்கள்.
1 சீனக் குடியரசு(தாய்வான்): Political status of Taiwan பார்க்கவும்.
2 குக் தீவுகளும் நியூவும்: நியூசிலாந்துடனான ஒரு free கூட்டு (association); Niue Constitution Act 1974 (NZ) ஐயும் பார்க்கவும்.
3 பலஸ்தீனம்: "பலத்தீன் நாடு" 1988 ஆம் ஆண்டு பிரகடனப்படுத்தப்பட்டுப் பல அரபு மற்றும் முஸ்லிம் நாடுகளால் அங்கீகரிக்கப்பட்டுள்ளது. proposals for a Palestinian state ஐயும் Palestinian territories ஐயும் பார்க்கவும். காஸா Strip, மேற்குக் கரை, இஸ்ரேல் என்பவற்றுக்குப்பலஸ்தீனப் பிரதேசம் தொடர்பில் கட்டுரைகள் உள்ளன.
4 வத்திக்கான்: Holy See பார்க்கவும்.
5 மேற்கு சஹாரா: Politics of Western Sahara பார்க்கவும்.
6 மசிடோனியக் குடியரசு: "முன்னாள் யூகோஸ்லாவியாவின் மசிடோனியக் குடியரசாக" அனைத்துலக அளவில் பரிச்சயமானது. **http://www.un.org/documents/ga/res/47/a47r225.htm ஐப் பார்க்கவும்.
தொடர்புள்ள தலைப்புகள்
ஐ.எசு.ஓ 3166-1
இறைமையுள்ள நாடு
உலக நாடுகள் பட்டியல் (கண்டங்கள் வாரியாக)
பன்னாட்டுத் தலைநகரங்களின் பட்டியல்
உலக நாடுகளின் மரபுச் சின்னங்கள்
ஏற்கப்படாத நாடுகள்
சார்பு மண்டலம்
நாடுகள் தொடர்பான பட்டியல்கள்
nds:Land#Länner
sv:Världsgeografi#Lista över länder
Maria, a Judia ou Maria, a Profetisa, é uma antiga filósofa grega e famosa alquimista que viveu no Egipto por volta do ano 273 a.C..
Alguns a situam na época de Aristóteles (384–322 a.C.), uma vez que a concepção aristotélica dos quatro elementos formadores do mundo (o fogo, o ar, a terra e a água) condiz bastante com as idéias alquimistas de Maria, como o axioma de Maria: «o Um torna-se Dois, o Dois torna-se Três, e do terceiro nasce o Um como Quatro». Segundo Aristóteles, o enxofre era considerado a expressão do elemento fogo, e Maria o tomou como base para os principais processos que estudou. Ela menciona o enxofre em frases sempre misteriosas, como «uma pedra que não é pedra» e «tão comum que ninguém a consegue identificar». Maria conta que Deus lhe revelou uma maneira de calcinar cobre com enxofre para produzir ouro. Esse enxofre era obtido do disulfeto de arsênico, que é achado em minas de ouro. Talvez tenha sido essa a origem da lenda da transformação de metais menos nobres em ouro.
Dentre as invenções de Maria estão o kerotakis, uma espécie de barril fechado e o banho de vapor: para um aquecimento lento e gradual dos experimentos, em vez de manipular as substâncias diretamente no fogo, ela descobriu que era possível controlar melhor a temperatura se fosse por meio da água - que até hoje chamamos de banho-maria. Para além disso dois equipamentos de destilação (alambique), com duas ou três saídas para destilados — o dibikos e o tribikos — e um aparelho para sublimação, sendo-lhe ainda atribuída a descoberta do ácido clorídrico. A maior parte das suas escrituras foram conservadas por Zósimo de Panópolis (300 d.C.).
Fontes
Não existem elementos concretos sobre o tempo e lugar de sua vida. Ela é mencionada pelos primeiros alquimistas da história, sempre como uma autoridade e respeito extremo. Os alquimistas do passado acreditava que ela era Miriã, irmã de Moisés e Arão, o profeta, mas há evidências que apoiam que esta reivindicação é falsa.
A menção mais concreta de Maria, a Judia no contexto da alquimia é por Zósimo de Panópolis, que escreveu no século IV os livros alquimistas mais antigos conhecidos . Zósimo descreve vários de seus experimentos e instrumentos. Em seus escritos, Maria é quase sempre citada como tendo vivido no passado e citou-a como uma das "sábias".
Jorge Sincelo, um cronista bizantino do século VIII, apresenta Maria como uma professora de Demócrito, a quem ela conheceu em Mênfis, Egito na época de Péricles. No século X Kitab al-Fihrist de Ibn al-Nadim cita-a como uma das cinqüenta e duas mais famosas alquimistas, sabendo da preparação do caput mortuum. O filósofo romano Morieno chamou de "Maria, a profetisa" e os árabes a conheciam como a "Filha de Platão", um nome que em ocidentais textos alquímicos foi reservada para o enxofre branco.
No livro de Alexandre (2 ª parte) do poeta persa Nizami, Maria, uma princesa síria, visita o Tribunal de Alexandre, o Grande, e aprende a partir de Aristóteles (384 aC - 322 aC), entre outras coisas, a arte de fazer ouro.
Trabalhos
Escrituras
Sabe-se que Maria escreveu vários textos sobre alquimia. Embora nenhum de seus escritos ter sobrevivido em sua forma original, os seus ensinamentos foram amplamente citados por autores posteriores herméticos. Seu trabalho principal sobrevivente é um extrato feito por um anônimo filósofo cristão, chamado O Diálogo de Maria e Aros sobre o Magistério de Hermes, em que são descritas e nomeadas operações que seriam mais tarde a base da Alquimia, leucose (branqueamento) e xanthosis (amarelecimento). Uma foi feita por moagem e do outro por calcinação. Este trabalho descreve pela primeira vez um sal de ácido e outros ácidos que podem ser identificados com ácido acético. Há também várias receitas para fazer ouro, até mesmo de vegetais de raiz como o Mandragora.
Vários enigmáticos preceitos alquímicos têm sido atribuídas a Maria. Ela supostamente disse da união dos opostos:
Esta outra vem do Axiom de Maria
Invenções
Maria era uma trabalhadora respeitada, que inventou aparelhos complicados de laboratório para a destilação e sublimação de materiais químicos. Maria disse ter descoberto o ácido clorídrico, embora isso não seja aceito pela maioria dos textos científicos .
Também são atribuídas a ela a invenção dos aparelhos de alquimia conhecidos como tribikos, kerotakis e o banho-maria.
Tribikos
Maria aperfeiçoou a câmara de destilação de três braços. O tribikos era uma espécie de alambique com três braços que foi utilizado para obter as substâncias purificadas por destilação. Ninguém sabe ao certo se Maria, a Judia foi sua inventora, mas Zósimo credita que a primeira descrição deste instrumento para ela. Em seus escritos (citado por Zósimo), ela recomenda que o cobre ou bronze utilizados para criar os tubos sejam da espessura de uma frigideira, e a junção entre estes tubos deve ainda ser selada com farinha de colar na cabeça
Kerotakis
O kerotakis é a invenção mais importante de Maria, a Judia, um dispositivo usado para aquecer substâncias utilizadas na alquimia e recolher os vapores. É um recipiente hermético com uma folha de cobre suspensa no topo. Quando funciona corretamente, todas as articulações são no vácuo apertado. O uso de tais recipientes fechados nas artes herméticas levaram ao termo "hermeticamente fechada". Maria e seus colegas acreditavam que a reação que se dá no kerotakis era uma reconstituição do processo de formação do ouro que acontecia nas entranhas da terra. Mais tarde, este instrumento foi modificado pelo alemão Franz von Soxhlet em 1879 para criar o extrator que leva seu nome, Soxhlet.
Banho-maria
Ver também
Mulheres na ciência
Alquimia
Judaísmo
Moisés
Miriã
Banho-maria
Bibliografía
GREENBERG, Arthur, Chemical History Tour, Picturing Chemistry from Alchemy to Modern Molecular Science. Wiley-Interscience 2000, ISBN 0-471-35408-2
STROHMEIER, Renate, Lexikon der Naturwissenschaftlerinnen und naturkundigen Frauen Europas. Von der Antike bis zum 20. Jahrhundert. Verlag Harri Deutsch, 1998, ISBN 3-8171-1567-9
Ligações externas
Inventoras
Alquimistas
Inventores
Filósofos da Grécia Antiga
Mulheres da Grécia Antiga
Filósofas
Mulheres na ciência
Gregos do século III a.C.
Mulheres do século III a.C.
!Mais Teoria da História na Wiki (Mulheres)
!Mais Teoria da História na Wiki (Wikiconcurso de edição)
'use strict';
const _ = require('lodash');
const fs = require('fs-extra');
const glob = require('glob');
const path = require('path');
const minify = require('../common/minify.js');
/*----------------------------------------------------------------------------*/
/**
* Creates a [fs.copy](https://github.com/jprichardson/node-fs-extra#copy)
* function with `srcPath` and `destPath` partially applied.
*
* @memberOf file
* @param {string} srcPath The path of the file to copy.
* @param {string} destPath The path to copy the file to.
* @returns {Function} Returns the partially applied function.
*/
function copy(srcPath, destPath) {
return _.partial(fs.copy, srcPath, destPath);
}
/**
* Creates an object of base name and compiled template pairs that match `pattern`.
*
* @memberOf file
* @param {string} pattern The glob pattern to be match.
* @returns {Object} Returns the object of compiled templates.
*/
function globTemplate(pattern) {
return _.transform(glob.sync(pattern), (result, filePath) => {
const key = path.basename(filePath, path.extname(filePath));
result[key] = _.template(fs.readFileSync(filePath, 'utf8'));
}, {});
}
/**
* Creates a `minify` function with `srcPath` and `destPath` partially applied.
*
* @memberOf file
* @param {string} srcPath The path of the file to minify.
* @param {string} destPath The path to write the file to.
* @returns {Function} Returns the partially applied function.
*/
function min(srcPath, destPath) {
return _.partial(minify, srcPath, destPath);
}
/**
* Creates a [fs.writeFile](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback)
* function with `filePath` and `data` partially applied.
*
* @memberOf file
* @param {string} destPath The path to write the file to.
* @param {string} data The data to write to the file.
* @returns {Function} Returns the partially applied function.
*/
function write(destPath, data) {
return _.partial(fs.writeFile, destPath, data);
}
/*----------------------------------------------------------------------------*/
module.exports = {
copy,
globTemplate,
min,
write
};
Berthold Konrad Hermann Albert Speer (Mannheim, 19 maart 1905 – Londen, 1 september 1981) was een Duits architect en stedenbouwkundige. Tijdens de naziheerschappij over Duitsland (1933-1945) was hij vanaf 1937 rijksarchitect en vanaf 1942 rijksminister van Bewapening en Munitie. Door zijn vriendschap met Adolf Hitler en zijn ministerschap gold hij als een van de machtigste mannen van het Derde Rijk. Na de oorlog werd Speer in Neurenberg veroordeeld tot twintig jaar gevangenisstraf.
Voor 1933
Het gezin waarin Speer werd geboren, was wat ze in het Duits noemen grossbürgerlich; in Nederlandse termen gegoede burgerij of bourgeoisie. Zijn vader en grootvader waren beiden architecten. Om financiële redenen studeerde Speer aanvankelijk in Karlsruhe. Van de lente van 1924 tot de zomer van 1925 zette hij zijn studie vervolgens voort aan de technische hogeschool van München. In de herfst van 1925 verhuisde hij naar Berlijn en probeerde hij vergeefs aan de Technische Hogeschool in Berlijn-Charlottenburg in het seminarie van Hans Poelzig toegelaten te worden. In 1926 ontving Heinrich Tessenow, een architect van de behoudende school met een zeer bescheiden en niet megalomane stijl, een leerstoel. Speer werd in dat jaar een van zijn studenten. Na zijn diploma te hebben behaald in 1927 bleef Speer nog meerdere jaren, als Tessenows assistent, aan de hogeschool verbonden.
Architect in dienst van Hitler
Speer was niet bijzonder geïnteresseerd in politiek. Hij werd echter reeds in januari 1931 lid van de NSDAP nadat hij in december 1930 een toespraak van Adolf Hitler had bijgewoond in de Berlijnse Hasenheide. Deze toespraak had een diepe indruk gemaakt op Speer. Zelf schreef hij dat hij een maand had getwijfeld, maar dat hij uiteindelijk toch besloten had om lid te worden, omdat Hitler helemaal niet stereotiep was overgekomen in de toespraak. Het was een zeer rustige toespraak waarin het woord 'Jood' niet één keer was gevallen.
In 1932 verliet Speer Berlijn en ging terug naar Mannheim. Hij vestigde zich daar als architect, maar hij kreeg geen opdrachten. In 1934 werd hem gevraagd de meivieringen van de partij vorm te geven. Speers originele idee was om rond het veld in Neurenberg waar de parades werden afgenomen een reeks zoeklichten recht omhoog te laten schijnen. Hierdoor ontstond een mooi lichtspel wat een koepel van licht boven het paradeveld veroorzaakte. Hitler was hierover zeer enthousiast en zo werd Speer Hitlers huisarchitect.
Toen Hitlers toenmalige Hofarchitekt, de uit München afkomstige Paul Ludwig Troost, in 1934 overleed, nam Speer diens taken over, waarmee hij zijn formele leidinggevende Rudolf Hess feitelijk snel overschaduwde in macht en ook in aanzien bij Hitler. Speer ontwierp talrijke gebouwen in klassieke stijl, die als doel hadden de pracht en de macht van het Derde Rijk te tonen en te onderstrepen. In het Deutsche Arbeitsfront (DAF) leidde hij de afdeling Schönheit der Arbeit. Verder werd hij de chef van de onderafdeling van de Rijkspropagandaleiding en verantwoordelijk voor de stedenbouw in de staf van Rudolf Hess.
Voor de wereldtentoonstelling van 1937 in Parijs ontwierp hij het Duitse paviljoen. Het hoofdbestanddeel bestond uit een enorme toren in classicistische stijl met een grote Duitse adelaar erop. Speer kreeg er de Grand Prix met een gouden medaille voor.
De belangrijkste gebouwen en de aanleg van urbane ruimtes voor het Derde Rijk ontwierp Speer echter in Berlijn en Nürnberg. Berlijn als rijkshoofdstad en bestuurscentrum lag voor de hand. In Nürnberg werden voor de machtsovername al diverse zogenaamde partijdagen gehouden, propagandistische massabijeenkomsten georganiseerd door de NSDAP, om het nationaalsocialisme te etaleren aan de Duitse kiezers. Deze Beierse stad lag niet ver van München, de bakermat van de nazipartij, en was daarbij goed bereikbaar via een uitgebreid verkeersnetwerk en bezat als toeristische trekpleister voldoende hotels om veel volk onderdak te bieden. Nürnberg kozen de nazi's ook meer symbolisch als zijnde een belangrijke vroegere rijksstad van het Heilige Roomse Rijk, de plek waar men destijds de rituele symbolen van de keizerlijke macht bewaarde zoals de rijksappel, de scepter en de kroon. De nazi's zetten met de keuze van Nürnberg een eeuwenoude traditie van jaarmarkten, machtige keizers en kastelen voort door daar de nazipartijdagen te laten plaatsvinden. Na de verkiezingsoverwinning in 1933 ging het terrein van de partijdagen grondig op de schop en werd in opdracht van Hitler flink uitgebreid.
Berlijn
In 1937 werd hij benoemd tot regeringscommissaris voor de bouw in de staf van de Führer en inspecteur-generaal voor de bouwnijverheid in Berlijn. Zijn ontwerpen waren naar de smaak van Hitler die hield van gebouwen in een neoclassicistische stijl met een minimalistische uitstraling maar dan vergroot tot buitensporige afmetingen. Voor de spaarzame aankleding wilde Hitler het liefst de klassieke Arische beelden gebruiken van de hand van de door Hitler bewonderde Arno Breker. Vooral voor Berlijn had Hitler grootse plannen. Deze stad zou na de Endsieg herdoopt worden in Germania (overigens is Speer de enige bron die dit beweerde). Met talloze statige bouwwerken en brede boulevards wilde Hitler aan zijn hoofdstad een enorme grandeur geven. Hitlers en Speers megalomane motto was: 'hoe groter hoe beter'. Speer ordonneerde stabiliteitstesten in de moerassige grond van Berlijn om na te gaan of deze het enorme gewicht van de geplande gebouwen kon dragen. Daartoe bouwde de firma Dyckerhoff & Widmann AG in 1941 tegen de prijs van 400 000 Reichsmark aan de rand van Berlijn het Schwerbelastungskörper. Het betrof een betonnen 12 360 ton wegende cilinder met een diameter van 21 m. De nog intact zijnde kolos veroorzaakte volgens Speers metingen een verzakking van 19 cm. De Berlijnse ondergrond was bijgevolg geschikt voor het bouwen van dergelijke grootschalige bouwwerken. Tevens werd een begin gemaakt met het aanleggen van de weids opgezette boulevards. In 1938 en 1939 werd in recordtijd de bouw van de nieuwe Rijkskanselarij aan de Wilhelmstrasse en de Voßstraße voltooid. Speer toonde zich hier al als een goede bouworganisator. Het bouwwerk met gigantische afmetingen (het geheel mat 200 ha) was voor Hitler een representatieve plaats om de buitenlandse gasten en diplomaten te ontvangen. Zij moesten op deze wijze onder de indruk raken van de grootsheid van het Duitse Rijk. Het merkwaardigste onderdeel van het geheel betrof een lange rechte galerij van 146 m lengte, twee maal zo lang als de spiegelzaal in Versailles van 73 meter, met een spiegelgladde vloer die leidde naar de persoonlijke ontvangstruimten van Hitler; deze "straat" werd "der lange Marsch der Diplomaten" genoemd. Sommigen maakten de opmerking dat de gladde vloer eigenlijk wel gevaarlijk was om op te lopen. Hitler wimpelde deze bezwaren weg met de woorden: “Diplomaten zijn wel gewend om zich op glad ijs te begeven”. Door het uitbreken van de oorlog moesten verdere plannen echter opgeschort worden. Gereed kwamen wel het vliegveld Tempelhof dat nog steeds een van de grootste luchthavengebouwen ter wereld heeft. Ook het nog steeds gebruikte Olympisch Stadion van 1936 was een onderdeel van de herbouw van Berlijn. Hitlers nieuwe kanselarij werd tijdens de eindstrijd in 1945 zwaar beschadigd en kort na de oorlog afgebroken.
Nürnberg
In deze vroegere Rijksstad, in het Nederlands wordt de stad meestal Neurenberg genoemd, ontwierp Speer vanaf 1934 een aantal gebouwen op het Reichsparteitagsgelände (de terreinen van de rijkspartijdagen) vertrekkende van het masterplan van architect-urbanist Paul Ludwig Troost. Troost kreeg van de partij opdracht om een recreatiegebied aan de stadsrand om te vormen tot een geschikte locatie voor een massa-evenement het zogenoemde Reichtsparteigelände, een gebied van 11 km². Men verplaatste daartoe de dierentuin en de vuurtoren brak men af. Men voorzag in een Große Straße van 1,5 km lengte en 50 m breed die visueel aansloot op de middeleeuwse keizerlijke burcht van Nürnberg. Gevangenen van het concentratiekamp Flossenbürg en Mauthausen kapten het graniet voor de 6 000 tegels waarover de soldaten zouden marcheren. Langs deze lange straatas plande men de Luitpoldarena, het Zeppelinveld, het Deutsches Stadion, een Hitlerjugendstadion, een Marsveld en twee treinstations. Slechts het Zeppelinveld met dito tribune naar een ontwerp van Speer werd afgewerkt. De kosten van de oorlogsindustrie beletten de verdere uitbouw van al deze megalomane plannen. Voor de tribune met een lengte van 360 m stond het antieke kleinschaligere Pergamonaltaar model. 320 000 toeschouwers konden de parades op het Zeppelinfeld volgen. Bij nacht schenen 250 grote spots de lucht in als een van ver te ziene lichtkathedraal. Nu is de plek herschapen tot een ruïne en op eigen risico te betreden. Via Google Earth kan men inzoomen op het Zeppelinveld en krijgt men een beeld van de huidige vervallen toestand.
Op deze plek filmde Leni Riefenstahl Hitlers propagandafilm Triumph des Willens over de aldaar gehouden Rijkspartijdag van 5 september 1934. Neurenberg is ook bekend van de Rassenwetten van Neurenberg en het ontnemen van burgerrechten van Joden. In deze stad vonden ook de naoorlogse processen van Neurenberg plaats. Door misleiding van het tribunaal wist Speer aan de doodstraf te ontkomen.
Speer als organisator en minister van bewapening vanaf 1942
Toen Hitler later meer en meer door de oorlog werd opgeslokt, verminderde zijn aandacht voor Speer maar hij verloor Speer omwille van zijn goede managerskwaliteiten niet echt uit het oog. Op 8 februari 1942 werd Speer, ondanks (of misschien wel dankzij) zijn vrij geringe politieke aspiraties, door Hitler benoemd als opvolger van de bij een vliegtuigongeluk omgekomen rijksminister voor Bewapening en Munitie, Fritz Todt. Speer gebruikte al zijn organisatietalent, reorganiseerde de productie van wapens en munitie.
Het Endspiel
Hitlers laatste bevelen aan Speer
In de laatste weken van de oorlog weigerde hij Hitlers bizarre bevelen nog langer uit te voeren. Hitler wist dat de oorlog verloren was en wilde het Duitse volk, dat in zijn ogen in zijn missie gefaald had, met hem mee de afgrond in sleuren in een soort Götterdämmerung met het Nero-bevel. Dit moest bereikt worden door het vernietigen van de nog overgebleven, vitale delen van Duitsland en de bezette gebieden: de tactiek van de verschroeide aarde. Speer dacht al aan het overleven van de bevolking en de wederopbouw van Duitsland na de oorlog en gaf Hitlers bevelen niet meer door aan de afdeling die voor de uitvoering moest zorgen. Een eerder voorbeeld was Hitlers bevel in 1944 om Parijs te vernietigen toen de geallieerden de stad naderden. Doordat de Duitse commandant van Parijs (luitenant-generaal Dietrich von Choltitz) hier niet aan meewerkte en ook door de zeer snelle omsingeling en verovering van Parijs werd dit verhinderd.
Arrestatie
Op 24 april 1945 vloog Speer, die Berlijn al was ontvlucht, speciaal terug om in de bunker onder de Rijkskanselarij afscheid van zijn Führer te kunnen nemen. Hitler pleegde uiteindelijk op 30 april zelfmoord, samen met Eva Braun die even tevoren met hem getrouwd was, en liet zijn instortende "Derde Rijk" in totale chaos achter. Op 23 mei 1945 werd Speer samen met Karl Dönitz (door Hitler per testament aangewezen als zijn opvolger) gearresteerd in Flensburg, van waaruit verschillende nazileiders, die niet in Berlijn waren gebleven, tevergeefs vredesonderhandelingen met de geallieerden trachtten te voeren.
Proces van Neurenberg en gevangenschap
Op 1 oktober 1946 werd Speer op het Proces van Neurenberg veroordeeld tot twintig jaar gevangenisstraf, vooral vanwege het feit dat onder zijn leiding één miljoen van de in totaal zes miljoen dwangarbeiders uit de bezette gebieden tijdens de oorlogsjaren in de wapenindustrie te werk waren gesteld. Van alle veroordeelde nazikopstukken was hij de enige die zich "verantwoordelijk" verklaarde voor de misdrijven van de nazistaat. Desondanks pleitte hij niet schuldig met als argument dat hij nooit persoonlijk opdrachten ondertekend had om gevangenen te deporteren. Speer schoof zijn volledige schuld af op de Minister van Arbeid, Fritz Sauckel die wel werd opgehangen. Zijn straf zat hij grotendeels uit in de Spandaugevangenis in Berlijn. Op 1 oktober 1966 kwam hij vrij.
Speer als de “nette nazi”
Speer heeft tijdens het proces in Neurenberg als enige top-nazi bekend medeverantwoordelijk te zijn aan de misdaden die tijdens het Derde Rijk zijn begaan. Dit medeschuldig zijn werd door hemzelf echter weer snel gebagatelliseerd: hij schilderde zichzelf af als iemand die verblind was door Hitlers megalomane dromen. Vooral de mogelijkheid om zijn gigantische architectonische ontwerpen, met behulp van Hitlers steun, onbegrensd te kunnen verwezenlijken had Speer, naïef als hij toen volgens zichzelf was, over de streep getrokken. Met deze zienswijze suggereerde Speer dat zijn medewerking aan het regime toch enigszins buiten zijn schuld om was gebeurd: hij wist niet beter. Van de gruwelijke toestanden in de vernietigingskampen en de Jodenvervolging had Speer (naar eigen zeggen) sowieso keine Ahnung (geen weet).
Verder schreef hij, om zich te verdedigen tijdens het Neurenberg-proces, nog enkele "goede" maatregelen op zijn naam; zo verklaarde hij bij het zien van de slaapplaatsen van de dwangarbeiders in de steenhouwerijen en fabrieken van V2-raketten voor betere verblijfplaatsen te hebben gezorgd.
Na 'Spandau' en Speers overlijden
Speer woonde na zijn vrijlating in de villa in Heidelberg die zijn vader in 1905 had laten bouwen. Hij trad daarna niet echt meer in de openbaarheid, op een enkel interview na, en besteedde zijn tijd aan het uitwerken van zijn aantekeningen en het publiceren ervan in verscheidene boeken. Door de inkomsten van zijn boeken en, zoals later bleek, ook door de heimelijke verkoop van tijdens de oorlog geroofde schilderijen kon Speer tot zijn dood een welgesteld leven leiden. In 1981, tijdens een bezoek aan Londen, overleed Speer vrij onverwacht aan een herseninfarct.
Nalatenschap en het einde van de mythe
Speer liet tekeningen en een hoeveelheid dagboekaantekeningen na, die uit de gevangenis waren gesmokkeld. Deze werden in 1969 in boekvorm uitgegeven onder de titel Spandauer Tagebücher (later vertaald in het Engels onder de titel Spandau – the secret diaries). Zijn levensverhaal vertelt hij in Erinnerungen (Herinneringen). Ook over de rol van de SS schreef hij een boek: Der Sklavenstaat: Meine Auseinandersetzungen mit der SS. Tot slot is ook het boek Technik und Macht min of meer van zijn hand, namelijk Speers woorden, vastgelegd door Adelbert Reif.
Niet lang voor Speers onverwachte dood kwamen Duitse onderzoekers op het spoor van Speers werkelijke verantwoordelijkheid voor oorlogsmisdrijven. Speers vroegere medewerker Wolters was een fanatiek nazi gebleven en was zo verontwaardigd over Speers "verraad" van Hitler dat hij op zijn beurt onthullingen deed over Speer. Zo was het Speer die regelde dat tijdens de voorbereidingen voor de aanleg van de brede boulevards in Berlijn de Duitse bewoners van 23 765 onteigende woningen de woningen van Joden kregen toegewezen. Joseph Pearce, De doodsteek voor de 'goede nazi''', in: De Morgen, 26 september 2018. De Joodse bewoners werden op transport gezet naar de concentratiekampen. Albert Speer heeft zijn ontmaskering niet meer meegemaakt.
Onderzoek dat na de dood van Speer door Matthias Schmidt werd gepubliceerd, toonde aan dat Speer een zorgvuldig web van misleiding rond zijn werkelijke aandeel in de oorlogsmisdaden had geweven. Nauwkeurig historisch onderzoek van de Duitse historicus Magnus Brechtken ontkracht systematisch de door Speer geschapen mythe van Hitlers onwetende architect. Speer stelde onder meer niet aanwezig te zijn geweest bij de beruchte rede in Posen waarin Heinrich Himmler de nazileiders betrok bij de massamoord op de Joden. Himmler sprak op de geluidsopname daarentegen rechtstreeks tot Speer, dat wil zeggen, alsof Speer aanwezig was. Ook een document waarop materiaal voor de bouw van crematieovens en lijkenkelders in een concentratiekamp werd vrijgegeven met Speers handtekening van goedkeuring erop was voor Speer zeer belastend. In overleg met SS leider Heinrich Himmler besprak en leidde Speer als Generalbauinspektor de uitbreiding van het concentratiekamp Auschwitz. De kampen Sachsenhausen en Mauthausen ontstonden op aansturen van Speer om slavenarbeiders te leveren voor de ontginning van graniet, nodig voor Speers monumentale nazibouwwerken.
Speer heeft zijn medeplichtige Rudolf Wolters na de oorlog opdracht gegeven om belastende documenten te vernietigen. In de memoires liegt Speer over zijn bezigheden vlak voor de val van het Derde Rijk. Speer heeft een kostbare collectie romantische schilderijen, gestolen of afgeperst uit Joods bezit, verborgen. Na zijn vrijlating heeft hij de schilderijen voorzichtig en anoniem verkocht. De contant uitbetaalde opbrengst werd weggesluisd, waarschijnlijk naar zijn jonge maîtresse. De kunstwerken brachten een miljoen mark op. De opbrengst van de speculatie met een van de Joodse bankierserfgename Marie-Anne von Goldschmidt-Rothschild afgeperst stuk kostbare bouwgrond aan de oever van Schwanenwerder bij Berlijn moest Speer restitueren. Dat heeft hij ondanks een veroordeling nooit gedaan.
Gesprekken met Gitta Sereny leidden tot een boek van haar hand. Ze portretteerde Speer als een man die niet met zichzelf in het reine kon komen.
Perspectief voor Speers architectuur
Speer bedacht het Ruinenwert-principe. Dit hield in dat de ontwerper een gebouw zo moest vormgeven dat het ook als ruïne mooi zou ogen. De aftakeling van Speers gebouwen startte vlugger dan voorzien. De tribune van het Zeppelinveld van het Reichsparteigelände in Nürnberg brokkelde af vanaf de jaren zestig van de twintigste eeuw. Het stadsbestuur moest daartoe in 1967 een deel van de bouwvallige zuilengalerij afbreken. De tienduizenden toeristen die de gebouwen jaarlijks bezoeken maken nu hun selfies op eigen risico.Het grootschalige karakter van Speers bouwwerken en de prominente aanwezigheid ervan vooral in Nürnberg, plaatsen de Duitsers voor een dilemma hoe om te gaan met dit beladen erfgoed dat voortdurend herinnert aan de naziperiode. Het Neurenbergse stadsbestuur is vastberaden (2016) om het patrimonium ondanks de oplopende kosten in stand te houden en in te richten als plek van educatie en herinnering. Daartoe bouwde men in 2001 al een Dokumentationszentrum Reichsparteitagsgelände aan de noordelijk gelegen kop van het congrescentrum dat in 1935 gebouwd werd door architect Ludwig Ruff op het terrein. Aldaar ingerichte tentoonstellingen geven een beeld van de Ursachen, Zusammenhängen und Folgen der nationalsozialistischen Gewaltherrschaft. Besluit
Nauwkeurig en uitvoerig bronnenonderzoek leidt tot de conclusie dat Speer tijdens het twaalf jaar (1933-1945) durend nazi-bewind twee doelen nastreefde: de nationaalsocialistische leer helpen uitvoeren en zichzelf verrijken. Tijdens de Neurenbergse processen en nadien stelde Speer alles in het werk om dit te verdoezelen en zichzelf neer te zetten als een "nette onwetende technocraat" die slechts voor het regime burgerlijke bouwwerken bedacht en uitvoerde. Daarbij kreeg hij uitgebreide hulp van journalist/historicus Joachim Fest en betrokken partij uitgeverij Siedler. De Duitse historicus Magnus Brechtken, directeur van het Institut für Zeitgeschichte in München, deed in dit verband een oproep om memoires, gedenkboeken en interviews nooit meer aan te wenden bij geschiedschrijving. Zij vormen in het slechtste geval een slinks samenstel van afleidingstrucs, retorische rookgordijnen en onversneden leugens. Een alarmbel in tijden van alom aanwezig nepnieuws.
Wetenswaardig
Albert Speer had zes kinderen. Een van zijn zonen, Albert Speer jr. (1934-2017), was eveneens een bekend architect en stadsplanner en ontwerper van voetbalstadions in Qatar voor het WK van 2022.
Speers publicaties Die neue Reichskanzlei, 1940. Een propagandaboek over de nieuwe Rijkskanselarij die hij voor Hitler gebouwd heeft.Neue deutsche Baukunst, 1941.Erinnerungen, 1969. Een boek dat is samengesteld uit de verschillende notities op onder meer wc-papier die Speer gemaakt heeft tijdens zijn gevangenisperiode in Spandau.Die Spandauer Tagebücher, 1975. Dagboek van Speers gevangenistijd.Der Sklavenstaat. Meine Auseinandersetzungen mit der SS, 1981. Nederlandse vertaling: De slavenstaat. Himmlers SS: de multinational van het Derde Rijk, Elsevier, 1981. Over Speers ervaringen met en zijn verhouding tot Himmlers SS.Alles was ich weiß, 1999. Postume getuigenis van Speer.
Literatuur
Magnus Brechtken, Albert Speer. Eine deutsche Karriere, 2017. (Nederlandse vertaling door Hans E. van Riemsdijk: Albert Speer. Een Duitse carrière, 2018)
Heinrich Breloer: Unterwegs zur Familie Speer Joachim Fest: Die unbeantwortbaren Fragen. Notizen über Gespräche mit Albert Speer zwischen Ende 1966 und 1981 Interviews met Speer. (vertaling Gerda Meijerink, 2006, Onbeantwoordbare vragen, De Bezige Bij, 256 blz.)
Joachim Fest: Speer, architect van Hitler, Aula, Amsterdam, 2004, vertaald uit het Duits.
Joachim Fest: Speer, Eine biographie, Berlin 1999, uitgever Alexander Fest Verlag in Berlijn. .
Lars Olof Larsson: Albert Speer, Le plan de Berlin, 1937-1943, Brussel, Archives d'Architecture Moderne, 1983.
Maarten Mahieu, Op de ruïnes van het Derde Rijk. Overblijfselen van de rijkspartijdagen in Neurenberg, in: Eos. Geschiedenis nr 1, najaar 2016.
Margret Nissen: Sind Sie die Tochter Speer? Matthias Schmidt: Albert Speer, das Ende eines Mythos. De onthulling van achtergehouden documenten over Speers daden in Berlijn en zijn woningpolitiek aldaar, 1982.
Heinrich Schwendemann: Albert Speer. Architekt des Todes. Speer als de organisator van Duitslands oorlogsindustrie.
Gitta Sereny: Das Ringen mit der Wahrheit (1995). Vertaald uit het Engels: Albert Speer - His struggle for truth.
Ulrich Schlie: Die Kransberg-Protokolle 1945 Dan van der Vat: Der gute Nazi. Analyse van Speer als Anständiger nazi.
Arnoud Veilbrief Kristallnacht? Viel me niet op, in NRC Handelsblad, Cultureel Supplement, 1 september 2006.
Esther Villar: Speer. (toneelstuk)
Verder bestaat er een boek Die intelligente Stadt, auteur Albert Speer, maar in dit geval betreft het Speers oudste zoon.
Film
Inside the Third Reich (1982): een film gebaseerd op het boek Die Spandauer Tagebücher met Rutger Hauer in de hoofdrol.
Speer en Hitler (oorspronkelijke titel Speer und Er): een gedramatiseerde documentaire over Albert Speer uit 2004 door Heinrich Breloer.
Der Untergang'': oorlogsfilm uit 2004, gespeeld door Heino Ferch.
Duits architect
Duits minister van Economie
Duits persoon in de Tweede Wereldoorlog
Minister van nazi-Duitsland
NSDAP-lid
;(function(window) {
'use strict';
/** The base path of the lodash builds. */
var basePath = '../';
/** The lodash build to load. */
var build = (build = /build=([^&]+)/.exec(location.search)) && decodeURIComponent(build[1]);
/** The module loader to use. */
var loader = (loader = /loader=([^&]+)/.exec(location.search)) && decodeURIComponent(loader[1]);
/** The `ui` object. */
var ui = {};
/*--------------------------------------------------------------------------*/
// Initialize controls.
addEventListener('load', function() {
function eventHandler(event) {
var buildIndex = buildList.selectedIndex,
loaderIndex = loaderList.selectedIndex,
search = location.search.replace(/^\?|&?(?:build|loader)=[^&]*&?/g, '');
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
location.href =
location.href.split('?')[0] + '?' +
(search ? search + '&' : '') +
'build=' + (buildIndex < 0 ? build : buildList[buildIndex].value) + '&' +
'loader=' + (loaderIndex < 0 ? loader : loaderList[loaderIndex].value);
}
function init() {
var toolbar = document.getElementById('qunit-testrunner-toolbar');
if (!toolbar) {
setTimeout(init, 15);
return;
}
toolbar.insertBefore(span2, toolbar.lastChild);
toolbar.insertBefore(span1, span2);
buildList.selectedIndex = (function() {
switch (build) {
case 'lodash': return 1;
case 'lodash-core-dev': return 2;
case 'lodash-core': return 3;
case 'lodash-dev':
case null: return 0;
}
return -1;
}());
loaderList.selectedIndex = (function() {
switch (loader) {
case 'curl': return 1;
case 'dojo': return 2;
case 'requirejs': return 3;
case 'none':
case null: return 0;
}
return -1;
}());
buildList.addEventListener('change', eventHandler);
loaderList.addEventListener('change', eventHandler);
}
var span1 = document.createElement('span');
span1.innerHTML =
'' +
'';
var span2 = document.createElement('span');
span2.innerHTML =
'' +
'';
span1.style.cssText =
span2.style.cssText = 'display:inline-block;float:right;line-height:2.1em;margin-left:1em;margin-top:0;';
span1.firstChild.style.cssText =
span2.firstChild.style.cssText = 'display:inline-block;margin-right:.5em;';
var buildList = span1.lastChild,
loaderList = span2.lastChild;
setTimeout(function() {
ui.timing.loadEventEnd = +new Date;
}, 1);
init();
});
// The lodash build file path.
ui.buildPath = (function() {
var result;
switch (build) {
case 'lodash': result = 'dist/lodash.min.js'; break;
case 'lodash-core-dev': result = 'dist/lodash.core.js'; break;
case 'lodash-core': result = 'dist/lodash.core.min.js'; break;
case null: build = 'lodash-dev';
case 'lodash-dev': result = 'lodash.js'; break;
default: return build;
}
return basePath + result;
}());
// The module loader file path.
ui.loaderPath = (function() {
var result;
switch (loader) {
case 'curl': result = 'node_modules/curl-amd/dist/curl-kitchen-sink/curl.js'; break;
case 'dojo': result = 'node_modules/dojo/dojo.js'; break;
case 'requirejs': result = 'node_modules/requirejs/require.js'; break;
case null: loader = 'none'; return '';
default: return loader;
}
return basePath + result;
}());
// Used to indicate testing a core build.
ui.isCore = /\bcore(\.min)?\.js\b/.test(ui.buildPath);
// Used to indicate testing a foreign file.
ui.isForeign = RegExp('^(\\w+:)?//').test(build);
// Used to indicate testing a modularized build.
ui.isModularize = /\b(?:amd|commonjs|es|node|npm|(index|main)\.js)\b/.test([location.pathname, location.search]);
// Used to indicate testing in Sauce Labs' automated test cloud.
ui.isSauceLabs = location.port == '9001';
// Used to indicate that lodash is in strict mode.
ui.isStrict = /\bes\b/.test([location.pathname, location.search]);
ui.urlParams = { 'build': build, 'loader': loader };
ui.timing = { 'loadEventEnd': 0 };
window.ui = ui;
}(this));
log
===
A Rust library providing a lightweight logging *facade*.
[](https://github.com/rust-lang/log/actions)
[](https://crates.io/crates/log)
[](https://docs.rs/log)

* [`log` documentation](https://docs.rs/log)
A logging facade provides a single logging API that abstracts over the actual
logging implementation. Libraries can use the logging API provided by this
crate, and the consumer of those libraries can choose the logging
implementation that is most suitable for its use case.
## Minimum supported `rustc`
See the `rust-version` field in `Cargo.toml` for the current minimum Rust toolchain version.
This version is explicitly tested in CI and may be bumped in any release as needed. Maintaining compatibility with older compilers is a priority though, so the bar for bumping the minimum supported version is set very high. Any changes to the supported minimum version will be called out in the release notes.
## Usage
### In libraries
Libraries should link only to the `log` crate, and use the provided macros to
log whatever information will be useful to downstream consumers:
```toml
[dependencies]
log = "0.4"
```
```rust
use log::{info, trace, warn};
pub fn shave_the_yak(yak: &mut Yak) {
trace!("Commencing yak shaving");
loop {
match find_a_razor() {
Ok(razor) => {
info!("Razor located: {razor}");
yak.shave(razor);
break;
}
Err(err) => {
warn!("Unable to locate a razor: {err}, retrying");
}
}
}
}
```
### In executables
In order to produce log output, executables have to use a logger implementation compatible with the facade.
There are many available implementations to choose from, here are some options:
* Simple minimal loggers:
* [`env_logger`](https://docs.rs/env_logger/*/env_logger/)
* [`colog`](https://docs.rs/colog/*/colog/)
* [`simple_logger`](https://docs.rs/simple_logger/*/simple_logger/)
* [`simplelog`](https://docs.rs/simplelog/*/simplelog/)
* [`pretty_env_logger`](https://docs.rs/pretty_env_logger/*/pretty_env_logger/)
* [`stderrlog`](https://docs.rs/stderrlog/*/stderrlog/)
* [`flexi_logger`](https://docs.rs/flexi_logger/*/flexi_logger/)
* [`call_logger`](https://docs.rs/call_logger/*/call_logger/)
* [`std-logger`](https://docs.rs/std-logger/*/std_logger/)
* [`structured-logger`](https://docs.rs/structured-logger/latest/structured_logger/)
* [`clang_log`](https://docs.rs/clang_log/latest/clang_log)
* [`ftail`](https://docs.rs/ftail/latest/ftail/)
* Complex configurable frameworks:
* [`log4rs`](https://docs.rs/log4rs/*/log4rs/)
* [`logforth`](https://docs.rs/logforth/*/logforth/)
* [`fern`](https://docs.rs/fern/*/fern/)
* [`spdlog-rs`](https://docs.rs/spdlog-rs/*/spdlog/)
* Adaptors for other facilities:
* [`syslog`](https://docs.rs/syslog/*/syslog/)
* [`systemd-journal-logger`](https://docs.rs/systemd-journal-logger/*/systemd_journal_logger/)
* [`slog-stdlog`](https://docs.rs/slog-stdlog/*/slog_stdlog/)
* [`android_log`](https://docs.rs/android_log/*/android_log/)
* [`win_dbg_logger`](https://docs.rs/win_dbg_logger/*/win_dbg_logger/)
* [`db_logger`](https://docs.rs/db_logger/*/db_logger/)
* [`log-to-defmt`](https://docs.rs/log-to-defmt/*/log_to_defmt/)
* [`logcontrol-log`](https://docs.rs/logcontrol-log/*/logcontrol_log/)
* For WebAssembly binaries:
* [`console_log`](https://docs.rs/console_log/*/console_log/)
* For dynamic libraries:
* You may need to construct [an FFI-safe wrapper over `log`](https://github.com/rust-lang/log/issues/421) to initialize in your libraries.
* Utilities:
* [`log_err`](https://docs.rs/log_err/*/log_err/)
* [`log-reload`](https://docs.rs/log-reload/*/log_reload/)
* [`alterable_logger`](https://docs.rs/alterable_logger/*/alterable_logger)
* [`context-logger`](https://docs.rs/context-logger/*/context_logger)
Executables should choose a logger implementation and initialize it early in the
runtime of the program. Logger implementations will typically include a
function to do this. Any log messages generated before the logger is
initialized will be ignored.
The executable itself may use the `log` crate to log as well.
## Structured logging
If you enable the `kv` feature, you can associate structured data with your log records:
```rust
use log::{info, trace, warn};
pub fn shave_the_yak(yak: &mut Yak) {
// `yak:serde` will capture `yak` using its `serde::Serialize` impl
//
// You could also use `:?` for `Debug`, or `:%` for `Display`. For a
// full list, see the `log` crate documentation
trace!(target = "yak_events", yak:serde; "Commencing yak shaving");
loop {
match find_a_razor() {
Ok(razor) => {
info!(razor; "Razor located");
yak.shave(razor);
break;
}
Err(e) => {
// `e:err` will capture `e` using its `std::error::Error` impl
warn!(e:err; "Unable to locate a razor, retrying");
}
}
}
}
```
est un réalisateur, producteur, scénariste et monteur japonais, né le à Tokyo, où il est mort le . Il est considéré comme l’un des cinéastes les plus célèbres et influents de l’histoire du cinéma. En cinquante-sept ans de carrière cinématographique, il a réalisé plus de trente films.
Après une brève expérience de peintre, Akira Kurosawa entre dans l’industrie cinématographique japonaise en 1936 en tant qu’assistant réalisateur et scénariste. Il fait ses débuts en tant que réalisateur pendant la Seconde Guerre mondiale avec le film d’action populaire . Son huitième long métrage, , sort en 1948 et est acclamé par la critique, consolidant sa réputation. Ce film marque les débuts de sa collaboration avec l’acteur Toshirō Mifune, qui va tourner dans seize de ses films.
Pour , dont la première a lieu à Tokyo en , Akira Kurosawa reçoit le Lion d’or de la Mostra de Venise. Cette récompense inattendue permet au film d’être diffusé en Europe et en Amérique du Nord. Son succès public et critique ouvre les portes de l’Occident au cinéma japonais et permet à d’autres cinéastes japonais d’obtenir une reconnaissance internationale. Des au début des , Kurosawa réalise environ un film par an, dont , et . Au début des , il devient beaucoup moins prolifique, mais ses œuvres tardives continuent de remporter des prix, dont la Palme d’or au Festival de Cannes pour Kagemusha.
En 1990, il reçoit l’Oscar d’honneur décerné par l’ . En 1999, il est nommé à titre posthume « Personnalité asiatique du siècle » dans la catégorie « Arts, littérature, et culture » par le magazine Asiaweek et CNN, présenté comme .
Biographie
Enfance et éducation cinématographique (1910-1935)
Kurosawa naît le dans le quartier de Higashiōi (arrondissement de Shinagawa) à Tokyo. Son père Isamu, descendant d’une famille de samouraïs de la préfecture d’Akita, est directeur de l’école secondaire de l’Institut d’éducation physique de l’armée, tandis que sa mère vient d’une famille de marchands d’Osaka. Il est le benjamin d’une lignée de sept enfants. Deux d’entre eux sont presqu’adultes à sa naissance, et une de ses sœurs meurt peu de temps après. Kurosawa ne grandit alors qu’avec trois de ses frères et sœurs.
En plus de promouvoir l’exercice physique, son père, Isamu Kurosawa, considère la culture occidentale comme un point essentiel de l’éducation : le jeune Akira découvre le cinéma à l’âge de . Sous l’influence d’un de ses professeurs d’école élémentaire, , il se passionne pour la peinture et le dessin. À cette époque, il étudie également la calligraphie et le kendo.
L’enfance d’Akira Kurosawa est également très influencée par son frère Heigo, de quatre ans son aîné. Kurosawa rapporte qu’à la suite du séisme du Kantō de 1923, Heigo l’emmène dans les quartiers les plus détruits de la capitale et que lorsqu’il tente de détourner les yeux des cadavres jonchant les rues, son frère l’en empêche pour l’obliger à affronter ses peurs. Pour certains critiques, cet événement a fortement influencé la sensibilité de Kurosawa.
Heigo est un élève brillant, mais échoue à son examen d’entrée au lycée. À la suite de cet échec, il se détache peu à peu de sa famille, et se concentre sur la littérature étrangère. À la fin des années 1920, Heigo devient benshi (commentateur de films muets) et se fait connaître sous le nom de Suda Teimei. Akira, qui veut alors devenir peintre de style occidental, emménage avec son frère. Grâce à Heigo, Akira découvre non seulement le cinéma, mais également le théâtre et le cirque. Dans le même temps, il expose ses toiles et travaux dans le cadre des expositions de la Ligue des artistes prolétariens. Mais il n’arrive pas à vivre de sa peinture et finit par s’en lasser. Il se détourne aussi de la politique alors que la répression policière s’est accentuée.
Avec l’avènement du cinéma parlant au début des années 1930, il devient difficile pour les benshi comme Heigo de trouver du travail, et Akira retourne chez ses parents. En , Heigo se suicide avec sa compagne. Kurosawa décrit cette mort comme un sentiment durable de perte, et l’évoque dans le chapitre intitulé « Une histoire dont je ne veux pas parler » de son autobiographie. Seulement quatre mois après la mort de Heigo, son frère aîné meurt également.
Apprentissage de la réalisation (1935-1941)
En 1935, le nouveau studio de cinéma « Photo Chemical Laboratories » recherche des assistants réalisateurs. Bien qu’il n’ait jamais envisagé de travailler dans le cinéma et qu’il ait déjà un travail d’illustrateur de livres, Kurosawa répond à l’annonce du studio, qui demande aux candidats de rédiger un essai sur les défauts fondamentaux des films japonais et les moyens d’y remédier. Kurosawa explique dans son papier que si ces défauts sont fondamentaux, alors il n’y a aucun moyen de les corriger. Cette lettre au ton moqueur lui permet de passer les examens suivants. Le réalisateur Kajirō Yamamoto, qui fait partie des recruteurs, insiste pour que Kurosawa soit embauché. En , à l’âge de , Kurosawa entre chez PCL.
Au cours de ses cinq années en tant qu’assistant, Kurosawa travaille pour un nombre important de réalisateurs différents, mais celui qui lui apporte le plus reste Kajirō Yamamoto. Sur ses vingt-quatre films en tant qu’assistant réalisateur, dix-sept sont réalisés par Yamamoto, la plupart étant des comédies jouées par l’acteur Ken’ichi Enomoto, plus connu sous le nom de « Enoken ». Yamamoto cultive le talent de Kurosawa et le fait passer en une année de troisième assistant à « assistant réalisateur en chef ». Les responsabilités de Kurosawa s’accroissent, et son travail va de l’élaboration des scènes et du développement du film aux repérages des lieux de tournage, en passant par la finition du scénario, les répétitions, l’éclairage, le doublage, le montage et la direction de la seconde équipe. Dans son dernier film en tant qu’assistant réalisateur, , Kurosawa prend en charge l’essentiel de la production, Yamamoto étant déjà occupé par le tournage d’un autre film.
Yamamoto confie à Kurosawa qu’un bon réalisateur doit avant tout être un excellent scénariste. Kurosawa comprend alors qu’il peut être davantage rémunéré en écrivant des scénarios plutôt qu’en restant assistant réalisateur. Par la suite, il écrit ou coécrit tous ses films, et écrit fréquemment des scénarios pour d’autres réalisateurs, comme celui du film de Satsuo Yamamoto. L’écriture de scénarios pour d’autres réalisateurs est pour Kurosawa une activité lucrative, qui dure jusque dans les années 1960, bien après qu’il soit devenu célèbre.
Guerre, censure et mariage (1942-1945)
Durant les deux ans suivant la sortie de Cheval en 1941, Kurosawa est en quête d’une histoire qui pourrait lancer sa carrière de réalisateur. Vers la fin de l’année 1942, environ un an après le début de la guerre entre le Japon et les États-Unis, le romancier Tsuneo Tomita publie Sugata Sanshirō, un roman sur la naissance du judo écrit dans le style de Miyamoto Musashi. Intrigué par le livre, Kurosawa l’achète le jour de sa publication ; après l’avoir lu d’une traite, il demande immédiatement à la Tōhō d’en acquérir les droits d’adaptation. Son intuition s’est avérée juste puisque, en l’espace de quelques jours, trois autres grands studios japonais proposent également d’acheter les droits. La Tōhō finit par les obtenir, et Kurosawa entame la préproduction de son premier film en tant que réalisateur.
Le tournage de débute à Yokohama en . La production du film ne pose pas de problème, mais la censure, qui avait donné son accord en amont conformément à la loi sur le cinéma de 1939, juge le résultat du tournage trop . La Légende du grand judo doit finalement sa sortie le au réalisateur Yasujirō Ozu, qui défend le film. Néanmoins, dix-huit minutes de la version initiale sont censurées. La plupart de ces coupes sont aujourd’hui considérées comme définitivement perdues. La Légende du grand judo est un film caractéristique de l’idéologie de l’époque. Il exalte les vertus morales et l’abnégation du petit peuple, par opposition à l’égoïsme et à la méchanceté des bourgeois occidentalisés, représentés par le personnage de Gennosuke.
Kurosawa s’intéresse ensuite au sujet des femmes ouvrières en temps de guerre dans , un film de propagande tourné dans un style semi-documentaire au début de l’année 1944. Le scénario, écrit par Kurosawa, met en scène un groupe de jeunes ouvrières dans une usine de lentilles optiques à usage militaire qui fait tout son possible malgré les difficultés pour augmenter sa productivité. Pour obtenir des performances réalistes de la part des actrices, Kurosawa les fait vivre dans une véritable usine pendant le tournage, manger la nourriture de l’usine et s’appeler les unes les autres par les noms de leurs personnages. Il utilise des méthodes similaires avec ses interprètes tout au long de sa carrière.
Au cours de la production, Yōko Yaguchi, l’actrice interprétant la meneuse du groupe d’ouvrières, est choisie par ses collègues pour présenter à Kurosawa leurs exigences. Paradoxalement, alors qu’ils s’opposent en permanence, Yaguchi et Kurosawa se rapprochent. Ils se marient le , alors que Yōko est enceinte de deux mois. Ils restent mariés jusqu’à la mort de Yōko en 1985. Ils ont ensemble deux enfants : un fils, Hisao, né le , producteur de quelques-uns des derniers projets de son père, et une fille, Kazuko, née le , chef costumière.
Juste avant son mariage, Kurosawa est pressé par le studio de donner une suite à La Légende du grand judo. Le film de propagande sort en , et est souvent considéré comme l’une des œuvres les moins abouties de Kurosawa.
Dans le contexte de pénurie des derniers mois de la guerre, Kurosawa décide d’écrire le scénario d’un film moins onéreux à produire que les précédents. , basé sur la pièce de kabuki Kanjinchō, avec Enoken, est achevé en . À cette date, le Japon vient de capituler, et l’occupation du pays par les Alliés a commencé. Le système de censure mis en place par les Américains, à l’encontre de tous les films japonais réalisés pendant la guerre, bloque la diffusion du film, estimant qu’il défend des valeurs . Le film avait déjà été critiqué par les censeurs japonais en temps de guerre, qui le jugeaient trop occidental et . Ils regrettaient notamment le rôle du porteur comique interprété par Enoken. Le film n’aurait donc probablement pas vu le jour même si la guerre s’était poursuivie plus longtemps. Il ne sort finalement qu’en 1952, sept ans après son tournage.
Travaux d'après-guerre (1946-1950)
Au lendemain de la guerre, Kurosawa est inspiré par les idéaux démocratiques du nouveau régime né de l’occupation. Le premier film résultant de cette inspiration est , sorti en 1946, basé sur l’incident de Takigawa de 1933 et l’affaire de l’espion Hotsumi Ozaki, dans lequel le réalisateur critique le régime japonais d’avant-guerre. Le personnage central du film est une femme, Yukie (interprétée par Setsuko Hara), qui cherche sa place dans un contexte de crise politique. Le scénario original, écrit par Eijirō Hisaita, doit être revu et corrigé de façon importante en raison de ses thèmes politiques. Le film divise la critique, tant par son sujet controversé que par le sexe de son personnage principal. En revanche, le succès auprès du public est présent, et le titre du film devient une phrase culte d’après-guerre.
Son film suivant, , sort en et reçoit un accueil critique mitigé. Il s’agit de l’histoire d’amour relativement simple d’un couple appauvri par la guerre qui souhaite profiter de son jour de repos. Pour ce film, Kurosawa est influencé par les œuvres de Frank Capra, D. W. Griffith et F. W. Murnau, des cinéastes qu’il admire profondément. En 1947 sort , un film de Senkichi Taniguchi et écrit par Kurosawa. Ce film marque les débuts du jeune acteur Toshirō Mifune. C’est Kurosawa, avec l’aide de Yamamoto, qui insiste pour que le studio Tōhō engage Mifune.
L’année suivante sort . Bien que le scénario doive être réécrit à cause de la censure de l’occupation, Kurosawa a le sentiment de pouvoir enfin s’exprimer librement. Le film raconte l’histoire d’un médecin tentant de sauver un yakuza de la tuberculose. Il s’agit de la première collaboration entre le réalisateur et Mifune. Cette collaboration se poursuit durant les seize films suivants du cinéaste (hormis Vivre), où Mifune joue les premiers rôles. À l’origine, Mifune n’est pas censé jouer le personnage principal de L’Ange ivre, mais sa prestation de yakuza est telle qu’il domine le film et éclipse le rôle du docteur alcoolique tenu par Takashi Shimura. Kurosawa décide alors de ne pas gêner la montée en puissance du jeune acteur. Le jeu de rebelle de Mifune conquiert aussitôt le public. L’avant-première a lieu en , et le film est élu meilleur film de l’année par la prestigieuse revue Kinema Junpō. Au total, trois films de Kurosawa seront ainsi récompensés.
Avec le producteur Sōjirō Motoki et les réalisateurs Kajirō Yamamoto, Mikio Naruse et Senkichi Taniguchi, Kurosawa fonde l’. Pour les débuts de cette organisation, et pour son premier film pour Daiei, Kurosawa adapte avec Taniguchi une pièce contemporaine de Kazuo Kikuta. a pour tête d’affiche Toshirō Mifune en jeune médecin idéaliste luttant contre la syphilis. Il s’agit d’une tentative délibérée de Kurosawa de sortir Mifune des rôles de gangsters. Sorti en , le film est un succès au box-office, mais est généralement considéré comme l’un des moins bons du cinéaste.
Son second film de l’année 1949, également produit par l’Association artistique cinématographique et distribué par la Shintōhō, est , l’un de ses films les plus célèbres. Ce film policier raconte l’histoire d’un jeune détective (interprété par Mifune) obsédé par son pistolet volé par un démuni qui s’en sert pour commettre des crimes. Il est chargé d’assister le commissaire Sato, dont la perspicacité pour remonter jusqu’au coupable rappelle celle du commissaire Maigret. Adapté d’un roman de Kurosawa lui-même, et écrit dans le style de l’un de ses auteurs favoris , il s’agit avant tout de sa première collaboration avec le scénariste Ryūzō Kikushima. L’une des séquences les plus célèbres du film, d’une durée de huit minutes et sans dialogues, représente le jeune détective déguisé en pauvre vétéran errant dans les rues à la recherche de son arme ; cette séquence utilise des plans d’un documentaire sur la ville de Tokyo ravagée par la guerre, réalisé par Ishirō Honda, un ami de Kurosawa et futur réalisateur de .
, produit par la Shōchiku et sorti en , est inspiré d’une expérience personnelle du réalisateur avec la presse à scandale. Le film mêle drame judiciaire et problèmes sociaux sur fond de liberté d’expression et de responsabilités personnelles. Mais Kurosawa juge le travail flou et peu satisfaisant, rejoignant ce que s’accorde à dire la majorité des critiques. Cependant, c’est avec son second film de 1950, , que Kurosawa finit par gagner un tout nouveau public.
Reconnaissance internationale (1950-1958)
Après la sortie de Scandale, Kurosawa est approché par les studios Daiei, afin qu’il réalise un deuxième film pour eux après Le Duel silencieux. Le réalisateur choisit alors le script d’un jeune scénariste, Shinobu Hashimoto, basé sur la nouvelle de Ryūnosuke Akutagawa intitulée qui narre le meurtre d’un samouraï et le viol de sa femme. Kurosawa voit dans cette nouvelle un potentiel cinématographique, et décide de la développer avec l’aide de Hashimoto. Daiei accueille le projet avec enthousiasme d’autant que le budget requis semble faible avec ses deux uniques décors et un tournage majoritairement en extérieur. Matsutarō Kawaguchi, alors cadre à la Daiei, se plaindra plus tard auprès de Kurosawa d’avoir été roulé tant l’imposant décor de la porte Rashō a été couteux.
Le tournage de Rashōmon se déroule du au dans les grands espaces montagneux de la forêt de Nara puis dans la forêt qui longe le Konkai kōmyō-ji à Kyoto. La post-production du film dure une seule semaine, et est gênée par un incendie dans les studios. L’avant-première a lieu le au théâtre impérial de Tokyo, la sortie nationale le lendemain. Les critiques sont partagées, intriguées par le thème unique du film. Il s’agit néanmoins d’un succès financier modéré pour la société Daiei.
Le film suivant de Kurosawa, pour Shōchiku, est , une adaptation du roman de l’écrivain préféré du réalisateur, Fiodor Dostoïevski. Le cinéaste délocalise l’histoire de la Russie à Hokkaidō, mais reste très fidèle à l’œuvre originale, ce que de nombreuses critiques jugent dommageable pour le film. Jugé trop long, le film de Kurosawa est raccourci, passant de (près de ) à , ce qui rend l’histoire difficilement compréhensible. À sa sortie, les critiques sont très mauvaises, mais le film rencontre un succès modéré auprès du public, essentiellement grâce à la présence de Setsuko Hara.
Pendant ce temps, à l’insu de Kurosawa, Rashōmon est sélectionné à la Mostra de Venise grâce aux efforts de Giuliana Stramigioli, une représentante basée au Japon d’une société de production italienne. Le , Rashōmon reçoit la plus haute distinction du festival, le Lion d’or. Cette récompense surprend l’ensemble du monde du cinéma, qui à l’époque ignorait quasiment tout de la tradition cinématographique du Japon.
Daiei exploite alors brièvement le film à Los Angeles jusqu’à ce que RKO rachète les droits de distribution sur le sol des États-Unis. Le risque est grand pour RKO : à l’époque, un seul film sous-titré est sur le marché américain, et le seul film japonais ayant été distribué à New York, une comédie de Mikio Naruse en 1937, a été un échec critique et commercial. Pourtant, l’exploitation de Rashōmon est un succès, aidée par de nombreux critiques dont Ed Sullivan : lors des trois premières semaines, le film engrange , et ce dans un seul cinéma de New York. Le public français quant à lui découvre le film en salles en . Ce succès entraîne un regain d’intérêt pour les films japonais en Occident dans les , éclipsant le cinéma néoréaliste italien. Grâce à cette renommée, les films d’autres cinéastes japonais commencent à recevoir des récompenses et à être distribués en Occident, comme ceux de Kenji Mizoguchi, et plus tard ceux de Yasujirō Ozu, des cinéastes reconnus au Japon mais totalement inconnus dans cette partie du monde.
Sa carrière gonflée par sa reconnaissance internationale, Kurosawa retourne chez Tōhō et travaille sur son prochain film, . Le film met en scène Watanabe (Takashi Shimura), un fonctionnaire atteint d’un cancer qui cherche à donner un dernier sens à sa vie. Pour le scénario, Kurosawa s’allie à Hashimoto et à l’écrivain Hideo Oguni, avec qui il coécrit douze films. Malgré le sujet grave, les scénaristes abordent le récit d’une manière satirique, ce que certains comparent au travail de Bertolt Brecht. Cette stratégie leur a permis d’éviter ce sentimentalisme commun qui règne habituellement autour de personnages atteints de maladies incurables. Vivre sort en , Kurosawa est récompensé de son deuxième « meilleur film » de Kinema Junpō, et le film remporte un grand succès au box-office.
En , Kurosawa s’isole durant avec les deux scénaristes de Ikiru, Shinobu Hashimoto et Hideo Oguni. Ensemble, ils écrivent le scénario du prochain film du cinéaste, . Il s’agit du premier véritable chanbara de Kurosawa, genre pour lequel il est aujourd’hui le plus connu. L’histoire, celle d’un pauvre village de l’époque Sengoku qui fait appel à un groupe de samouraïs afin de se défendre des bandits, est traitée par Kurosawa d’une manière totalement épique, et l’action est méticuleusement détaillée durant les trois heures et demie. Le film s’appuie sur une distribution d’ensemble impressionnante, composée notamment d’acteurs ayant déjà tourné avec Kurosawa.
Trois mois sont nécessaires pour la préproduction, un mois pour les répétitions. Le tournage dure étalés sur près d’un an, interrompu entre autres par des difficultés de production et d’ordre financier, ainsi que par les problèmes de santé de Kurosawa. Le film sort finalement en , soit après la date prévue. Le film coûte trois fois plus que prévu, et devient alors le film japonais le plus cher jamais réalisé. Les critiques sont positives, et le succès au box-office permet de rentrer rapidement dans les frais. Après de nombreuses modifications, il est distribué sur le marché international. Au fil du temps, et grâce aux versions non modifiées diffusées par la suite, le film accroît sa notoriété. En 1979, un vote parmi des critiques japonais le classe comme étant le meilleur film japonais de tous les temps. Aujourd’hui encore, il est considéré comme tel par certains critiques.
En 1954, des tests nucléaires militaires dans le Pacifique créent des incidents aux conséquences désastreuses, comme celui impliquant le thonier japonais Daigo Fukuryū Maru. C’est dans cette anxiété ambiante que Kurosawa conçoit son film suivant, . Le propos porte sur un riche industriel (Toshirō Mifune) terrifié à l’idée d’une attaque nucléaire, et qui décide d’emmener sa famille dans une ferme au Brésil pour être en sécurité. La production est moins chaotique que lors du film précédent, mais à quelques jours de la fin du tournage, Fumio Hayasaka, compositeur et ami de Kurosawa, meurt de la tuberculose. La bande originale est alors achevée par l’assistant de Hayasaka, Masaru Satō, qui travaille sur les huit films suivants de Kurosawa. Vivre dans la peur sort en , mais l’accueil des critiques et du public est timide et réservé. Le film devient alors le premier de Kurosawa à ne pas rentrer dans ses frais durant son exploitation en salle. Aujourd’hui, il est considéré comme le meilleur film traitant des effets psychologiques de la paralysie nucléaire mondiale.
Le projet suivant de Kurosawa, , est une adaptation du Macbeth de William Shakespeare, dont l’histoire est transposée en Asie à l’époque Sengoku. Kurosawa donne pour instruction aux acteurs, et notamment à l’actrice principale Isuzu Yamada, d’agir et de jouer comme s’il s’agissait d’un classique de la littérature japonaise et non occidentale. Le jeu des acteurs s’apparente alors aux techniques et styles du théâtre nô. Le film est tourné en 1956 et sort en . Le succès en salle est légèrement moins mauvais que pour Vivre dans la peur. À l’étranger, le film devient rapidement une référence parmi les adaptations cinématographiques de Shakespeare.
La production d’une autre adaptation d’un classique européen suit immédiatement celle du Château de l’araignée. , adapté de la pièce du même nom de Maxime Gorki, est réalisé en mai et . Bien que l’adaptation soit très fidèle à la pièce de théâtre russe, l’exercice de transposition à l’époque d’Edo est considéré comme une réussite artistique. La première a lieu en , et le film reçoit un accueil partagé, similaire à celui reçu par Le Château de l’araignée. Certains critiques le classent parmi les œuvres les plus sous-estimées de Kurosawa.
Les trois films suivant Les Sept Samouraïs n’ont pas connu le même succès auprès du public japonais. Le travail de Kurosawa est de plus en plus sombre et pessimiste, et le réalisateur aborde les questions de la rédemption. Kurosawa, qui s’aperçoit de ces changements, décide délibérément de retourner à des films plus légers et divertissants. À cette même époque, le format écran large devient très populaire au Japon. En résulte , film d’action et d’aventure mettant en scène une princesse, son fidèle général et deux paysans devant traverser les lignes ennemies pour pouvoir rejoindre leurs foyers. Sorti en 1958, La Forteresse cachée est un énorme succès au box-office, et est chaudement accueilli par les critiques. Aujourd’hui, le film est considéré comme l’un des films les plus légers et accessibles de Kurosawa, mais reste très populaire pour ses nombreuses influences, notamment sur Star Wars, le de George Lucas sorti en 1977.
Naissance d'une entreprise et fin d'une ère (1959-1965)
Depuis Rashōmon, les films de Kurosawa atteignent un public plus large, et la fortune du réalisateur a
# Contributing to Lodash
Contributions are always welcome. Before contributing please read the
[code of conduct](https://github.com/openjs-foundation/cross-project-council/blob/main/CODE_OF_CONDUCT.md) &
[search the issue tracker](https://github.com/lodash/lodash/issues); your issue
may have already been discussed or fixed in `master`. To contribute,
[fork](https://help.github.com/articles/fork-a-repo/) Lodash, commit your changes,
& [send a pull request](https://help.github.com/articles/using-pull-requests/).
## Feature Requests
Feature requests should be submitted in the
[issue tracker](https://github.com/lodash/lodash/issues), with a description of
the expected behavior & use case, where they’ll remain closed until sufficient interest,
[e.g. :+1: reactions](https://help.github.com/articles/about-discussions-in-issues-and-pull-requests/),
has been [shown by the community](https://github.com/lodash/lodash/issues?q=label%3A%22votes+needed%22+sort%3Areactions-%2B1-desc).
Before submitting a request, please search for similar ones in the
[closed issues](https://github.com/lodash/lodash/issues?q=is%3Aissue+is%3Aclosed+label%3Aenhancement).
## Pull Requests
For additions or bug fixes you should only need to modify `lodash.js`. Include
updated unit tests in the `test` directory as part of your pull request. Don’t
worry about regenerating the `dist/` or `doc/` files.
Before running the unit tests you’ll need to install, `npm i`,
[development dependencies](https://docs.npmjs.com/files/package.json#devdependencies).
Run unit tests from the command-line via `npm test`, or open `test/index.html` &
`test/fp.html` in a web browser. The [Backbone](http://backbonejs.org/) &
[Underscore](http://underscorejs.org/) test suites are included as well.
## Contributor License Agreement
Lodash is a member of the [Open JS Foundation](https://openjsf.org/).
As such, we request that all contributors sign our
[contributor license agreement (CLA)](https://openjsf.org/cla).
For more information about CLAs, please check out Alex Russell’s excellent post,
[“Why Do I Need to Sign This?”](https://infrequently.org/2008/06/why-do-i-need-to-sign-this/).
## Coding Guidelines
In addition to the following guidelines, please follow the conventions already
established in the code.
- **Spacing**:
Use two spaces for indentation. No tabs.
- **Naming**:
Keep variable & method names concise & descriptive.
Variable names `index`, `array`, & `iteratee` are preferable to
`i`, `arr`, & `fn`.
- **Quotes**:
Single-quoted strings are preferred to double-quoted strings; however,
please use a double-quoted string if the value contains a single-quote
character to avoid unnecessary escaping.
- **Comments**:
Please use single-line comments to annotate significant additions, &
[JSDoc-style](http://www.2ality.com/2011/08/jsdoc-intro.html) comments for
functions.
Guidelines are enforced using [JSCS](https://www.npmjs.com/package/jscs):
```bash
$ npm run style
```
## Tips
You can opt-in to a pre-push git hook by adding an `.opt-in` file to the root of
the project containing:
```txt
pre-push
```
With that, when you `git push`, the pre-push git hook will trigger and execute
`npm run validate`.
> [!IMPORTANT]
> As announced on the [OpenJS Foundation blog](https://openjsf.org/blog/sta-supports-lodash), Lodash has received support from the Sovereign Tech Agency and will transition to the Feature-Complete maturity stage so that it remains stable, secure, and sustainable long-term. As part of this effort, Lodash is rebooting its governance. A draft charter will be published shortly. The upcoming Technical Steering Committee (TSC) is already at work. For transparency, its members are listed below.
# Lodash Governance
## Technical Steering Committee Members
The current Technical Steering Committee (TSC) members are:
- John-David Dalton ([@jdalton](https://github.com/jdalton)), _(Lodash creator)_
- Jon Church ([@jonchurch](https://github.com/jonchurch))
- Jordan Harband ([@ljharb](https://github.com/ljharb))
- Michał Lipiński ([@falsyvalues](https://github.com/falsyvalues))
- Tobie Langel ([@tobie](https://github.com/tobie))
- Ulises Gascón ([@ulisesgascon](https://github.com/UlisesGascon))
## Security Triage Team
The Security Triage Team is responsible for assessing and managing vulnerability and incident reports. Security triaging is currently handled by the [TSC](#technical-steering-committee-members).
## Release Team
The Release Team is solely responsible for publishing new versions of Lodash to npm. Its current member is:
- John-David Dalton ([@jdalton](https://github.com/jdalton))
(handling-files)=
# Handling Files
```{currentmodule} click
```
Click has built in features to support file and file path handling. The examples use arguments but the same principle
applies to options as well.
(file-args)=
## File Arguments
Click supports working with files with the {class}`File` type. Some notable features are:
- Support for `-` to mean a special file that refers to stdin when used for reading, and stdout when used for writing.
This is a common pattern for POSIX command line utilities.
- Deals with `str` and `bytes` correctly for all versions of Python.
Example:
```{eval-rst}
.. click:example::
@click.command()
@click.argument('input', type=click.File('rb'))
@click.argument('output', type=click.File('wb'))
def inout(input, output):
"""Copy contents of INPUT to OUTPUT."""
while True:
chunk = input.read(1024)
if not chunk:
break
output.write(chunk)
And from the command line:
.. click:run::
with isolated_filesystem():
invoke(inout, args=['-', 'hello.txt'], input=['hello'],
terminate_input=True)
invoke(inout, args=['hello.txt', '-'])
```
## File Path Arguments
For handling paths, the {class}`Path` type is better than a `str`. Some notable features are:
- The `exists` argument will verify whether the path exists.
- `readable`, `writable`, and `executable` can perform permission checks.
- `file_okay` and `dir_okay` allow specifying whether files/directories are accepted.
- Error messages are nicely formatted using {func}`format_filename` so any undecodable bytes will be printed nicely.
See {class}`Path` for all features.
Example:
```{eval-rst}
.. click:example::
@click.command()
@click.argument('filename', type=click.Path(exists=True))
def touch(filename):
"""Print FILENAME if the file exists."""
click.echo(click.format_filename(filename))
And from the command line:
.. click:run::
with isolated_filesystem():
with open('hello.txt', 'w') as f:
f.write('Hello World!\n')
invoke(touch, args=['hello.txt'])
println()
invoke(touch, args=['missing.txt'])
```
## File Opening Behaviors
The {class}`File` type attempts to be "intelligent" about when to open a file. Stdin/stdout and files opened for reading
will be opened immediately. This will give the user direct feedback when a file cannot be opened. Files opened for
writing will only be open on the first IO operation. This is done by automatically wrapping the file in a special
wrapper.
File open behavior can be controlled by the boolean kwarg `lazy`. If a file is opened lazily:
- A failure at first IO operation will happen by raising an {exc}`FileError`.
- It can help minimize resource handling confusion by lazily closing it. This is not needed for
parameters, but is necessary for manually prompting. For manual prompts with the {func}`prompt` function you do not
know if a stream like stdout was opened (which was already open before) or a real file was opened (that needs
closing).
Since files opened for writing will typically empty the file, the lazy mode should only be disabled if the developer is
absolutely sure that this is intended behavior.
It is also possible to open files in atomic mode by passing `atomic=True`. In atomic mode, all writes go into a separate
file in the same folder, and upon completion, the file will be moved over to the original location. This is useful if a
file regularly read by other users is modified.
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
/**\file
* Checks that test cases with identical name and tags are reported as error
*/
#include
TEST_CASE("A test case with duplicated name and tags", "[tag1][tag2]") {}
TEST_CASE("A test case with duplicated name and tags", "[tag1][tag2]") {}
# Security Policy
## Supported versions
The following table describes the versions of this project that are currently
supported with security updates:
| Version | Supported |
| ------- | ------------------ |
| 4.x | :white_check_mark: |
| 3.x | :x: |
| 2.x | :x: |
| 1.x | :x: |
## Threat Model
To better understand which classes of vulnerabilities are considered in-scope or out-of-scope for Lodash, please review the [Lodash Threat Model](./threat-model.md).
The threat model defines Lodash’s trust boundaries and clarifies how security issues are assessed for triage and disclosure.
## Responsible disclosure security policy
A responsible disclosure policy helps protect users of the project from publicly
disclosed security vulnerabilities without a fix by employing a process where
vulnerabilities are first triaged in a private manner, and only publicly disclosed
after a reasonable time period that allows patching the vulnerability and provides
an upgrade path for users.
We kindly ask you to refrain from malicious acts that put our users, the project,
or any of the project’s team members at risk.
## Reporting a security issue
We consider the security of Lodash a top priority. But no matter how much effort
we put into security, there can still be vulnerabilities present.
If you discover a security vulnerability, please report the security issue
directly to the Lodash maintainers through the [Security tab](https://github.com/lodash/lodash/security) of the Lodash
repository.
Your efforts to responsibly disclose your findings are sincerely appreciated.
## Escalation
If you do not receive an acknowledgement of your report within 6 business days, or if you cannot find a private security contact for the project, you may escalate to the OpenJS Foundation CNA at `security@lists.openjsf.org`.
If the project acknowledges your report but does not provide any further response or engagement within 14 days, escalation is also appropriate.
# Supporting Multiple Versions
If you are a library maintainer, you may want to support multiple versions of
Click. See the Pallets [version policy] for information about our version
numbers and support policy.
[version policy]: https://palletsprojects.com/versions
Most features of Click are stable across releases, and don't require special
handling. However, feature releases may deprecate and change APIs. Occasionally,
a change will require special handling.
## Use Feature Detection
Prefer using feature detection. Looking at the version can be tempting, but is
often more brittle or results in more complicated code. Try to use `if` or `try`
blocks to decide whether to use a new or old pattern.
If you do need to look at the version, use {func}`importlib.metadata.version`,
the standardized way to get versions for any installed Python package.
## Changes in 8.2
### `ParamType` methods require `ctx`
In 8.2, several methods of `ParamType` now have a `ctx: click.Context`
argument. Because this changes the signature of the methods from 8.1, it's not
obvious how to support both when subclassing or calling.
This example uses `ParamType.get_metavar`, and the same technique should be
applicable to other methods such as `get_missing_message`.
Update your methods overrides to take the new `ctx` argument. Use the
following decorator to wrap each method. In 8.1, it will get the context where
possible and pass it using the 8.2 signature.
```python
import functools
import typing as t
import click
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
def add_ctx_arg(f: F) -> F:
@functools.wraps(f)
def wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any:
if "ctx" not in kwargs:
kwargs["ctx"] = click.get_current_context(silent=True)
return f(*args, **kwargs)
return wrapper # type: ignore[return-value]
```
Here's an example ``ParamType`` subclass which uses this:
```python
class CommaDelimitedString(click.ParamType[str]):
@add_ctx_arg
def get_metavar(self, param: click.Parameter, ctx: click.Context | None) -> str:
return "TEXT,TEXT,..."
```
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
// 231-Cfg-OutputStreams.cpp
// Show how to replace the streams with a simple custom made streambuf.
// Note that this reimplementation _does not_ follow `std::cerr`
// semantic, because it buffers the output. For most uses however,
// there is no important difference between having `std::cerr` buffered
// or unbuffered.
#include
#include
#include
class out_buff : public std::stringbuf {
std::FILE* m_stream;
public:
out_buff(std::FILE* stream):m_stream(stream) {}
~out_buff() override;
int sync() override {
int ret = 0;
for (unsigned char c : str()) {
if (putc(c, m_stream) == EOF) {
ret = -1;
break;
}
}
// Reset the buffer to avoid printing it multiple times
str("");
return ret;
}
};
out_buff::~out_buff() { pubsync(); }
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wexit-time-destructors" // static variables in cout/cerr/clog
#endif
namespace Catch {
std::ostream& cout() {
static std::ostream ret(new out_buff(stdout));
return ret;
}
std::ostream& clog() {
static std::ostream ret(new out_buff(stderr));
return ret;
}
std::ostream& cerr() {
return clog();
}
}
TEST_CASE("This binary uses putc to write out output", "[compilation-only]") {
SUCCEED("Nothing to test.");
}
;(function() {
'use strict';
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
/** Used as the size to cover large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Used as a reference to the global object. */
var root = (typeof global == 'object' && global) || this;
/** Used for native method references. */
var arrayProto = Array.prototype;
/** Method and object shortcuts. */
var phantom = root.phantom,
argv = root.process && process.argv,
document = !phantom && root.document,
slice = arrayProto.slice,
WeakMap = root.WeakMap;
/** Math helpers. */
var add = function(x, y) { return x + y; },
isEven = function(n) { return n % 2 == 0; },
isEvenIndex = function(n, index) { return isEven(index); },
square = function(n) { return n * n; };
// Leak to avoid sporadic `noglobals` fails on Edge in Sauce Labs.
root.msWDfn = undefined;
/*--------------------------------------------------------------------------*/
/** Load QUnit and extras. */
var QUnit = root.QUnit || require('qunit-extras');
/** Load stable Lodash. */
var _ = root._ || require('../lodash.js');
var convert = (function() {
var baseConvert = root.fp || require('../fp/_baseConvert.js');
if (!root.fp) {
return function(name, func, options) {
return baseConvert(_, name, func, options);
};
}
return function(name, func, options) {
if (typeof name == 'function') {
options = func;
func = name;
name = undefined;
}
return name === undefined
? baseConvert(func, options)
: baseConvert(_.runInContext(), options)[name];
};
}());
var allFalseOptions = {
'cap': false,
'curry': false,
'fixed': false,
'immutable': false,
'rearg': false
};
var fp = root.fp
? (fp = _.noConflict(), _ = root._, fp)
: convert(_.runInContext());
var mapping = root.mapping || require('../fp/_mapping.js');
/*--------------------------------------------------------------------------*/
/**
* Skips a given number of tests with a passing result.
*
* @private
* @param {Object} assert The QUnit assert object.
* @param {number} [count=1] The number of tests to skip.
*/
function skipAssert(assert, count) {
count || (count = 1);
while (count--) {
assert.ok(true, 'test skipped');
}
}
/*--------------------------------------------------------------------------*/
if (argv) {
console.log('Running lodash/fp tests.');
}
QUnit.module('convert module');
(function() {
QUnit.test('should work with `name` and `func`', function(assert) {
assert.expect(2);
var array = [1, 2, 3, 4],
remove = convert('remove', _.remove),
actual = remove(isEven)(array);
assert.deepEqual(array, [1, 2, 3, 4]);
assert.deepEqual(actual, [1, 3]);
});
QUnit.test('should work with `name`, `func`, and `options`', function(assert) {
assert.expect(3);
var array = [1, 2, 3, 4],
remove = convert('remove', _.remove, allFalseOptions);
var actual = remove(array, function(n, index) {
return isEven(index);
});
assert.deepEqual(array, [2, 4]);
assert.deepEqual(actual, [1, 3]);
assert.deepEqual(remove(), []);
});
QUnit.test('should work with an object', function(assert) {
assert.expect(2);
if (!document) {
var array = [1, 2, 3, 4],
lodash = convert({ 'remove': _.remove }),
actual = lodash.remove(isEven)(array);
assert.deepEqual(array, [1, 2, 3, 4]);
assert.deepEqual(actual, [1, 3]);
}
else {
skipAssert(assert, 2);
}
});
QUnit.test('should work with an object and `options`', function(assert) {
assert.expect(3);
if (!document) {
var array = [1, 2, 3, 4],
lodash = convert({ 'remove': _.remove }, allFalseOptions),
actual = lodash.remove(array, isEvenIndex);
assert.deepEqual(array, [2, 4]);
assert.deepEqual(actual, [1, 3]);
assert.deepEqual(lodash.remove(), []);
}
else {
skipAssert(assert, 3);
}
});
QUnit.test('should work with lodash and `options`', function(assert) {
assert.expect(3);
var array = [1, 2, 3, 4],
lodash = convert(_.runInContext(), allFalseOptions),
actual = lodash.remove(array, isEvenIndex);
assert.deepEqual(array, [2, 4]);
assert.deepEqual(actual, [1, 3]);
assert.deepEqual(lodash.remove(), []);
});
QUnit.test('should work with `runInContext` and `options`', function(assert) {
assert.expect(3);
var array = [1, 2, 3, 4],
runInContext = convert('runInContext', _.runInContext, allFalseOptions),
lodash = runInContext(),
actual = lodash.remove(array, isEvenIndex);
assert.deepEqual(array, [2, 4]);
assert.deepEqual(actual, [1, 3]);
assert.deepEqual(lodash.remove(), []);
});
QUnit.test('should accept a variety of options', function(assert) {
assert.expect(8);
var array = [1, 2, 3, 4],
value = _.clone(array),
remove = convert('remove', _.remove, { 'cap': false }),
actual = remove(isEvenIndex)(value);
assert.deepEqual(value, [1, 2, 3, 4]);
assert.deepEqual(actual, [2, 4]);
remove = convert('remove', _.remove, { 'curry': false });
actual = remove(isEven);
assert.deepEqual(actual, []);
var trim = convert('trim', _.trim, { 'fixed': false });
assert.strictEqual(trim('_-abc-_', '_-'), 'abc');
value = _.clone(array);
remove = convert('remove', _.remove, { 'immutable': false });
actual = remove(isEven)(value);
assert.deepEqual(value, [1, 3]);
assert.deepEqual(actual, [2, 4]);
value = _.clone(array);
remove = convert('remove', _.remove, { 'rearg': false });
actual = remove(value)(isEven);
assert.deepEqual(value, [1, 2, 3, 4]);
assert.deepEqual(actual, [1, 3]);
});
QUnit.test('should respect the `cap` option', function(assert) {
assert.expect(1);
var iteratee = convert('iteratee', _.iteratee, { 'cap': false });
var func = iteratee(function(a, b, c) {
return [a, b, c];
}, 3);
assert.deepEqual(func(1, 2, 3), [1, 2, 3]);
});
QUnit.test('should respect the `rearg` option', function(assert) {
assert.expect(1);
var add = convert('add', _.add, { 'rearg': true });
assert.strictEqual(add('2')('1'), '12');
});
QUnit.test('should add a `placeholder` property', function(assert) {
assert.expect(2);
if (!document) {
var lodash = convert({ 'add': _.add });
assert.strictEqual(lodash.placeholder, lodash);
assert.strictEqual(lodash.add.placeholder, lodash);
}
else {
skipAssert(assert, 2);
}
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('method.convert');
(function() {
QUnit.test('should exist on unconverted methods', function(assert) {
assert.expect(2);
var array = [],
isArray = fp.isArray.convert({ 'curry': true });
assert.strictEqual(fp.isArray(array), true);
assert.strictEqual(isArray()(array), true);
});
QUnit.test('should convert method aliases', function(assert) {
assert.expect(1);
var all = fp.all.convert({ 'rearg': false }),
actual = all([0])(_.identity);
assert.strictEqual(actual, false);
});
QUnit.test('should convert remapped methods', function(assert) {
assert.expect(1);
var extendAll = fp.extendAll.convert({ 'immutable': false }),
object = {};
extendAll([object, { 'a': 1 }, { 'b': 2 }]);
assert.deepEqual(object, { 'a': 1, 'b': 2 });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('convert methods');
_.each(['fp.convert', 'method.convert'], function(methodName) {
var isFp = methodName == 'fp.convert',
func = isFp ? fp.convert : fp.remove.convert;
QUnit.test('`' + methodName + '` should work with an object', function(assert) {
assert.expect(3);
var array = [1, 2, 3, 4],
lodash = func(allFalseOptions),
remove = isFp ? lodash.remove : lodash,
actual = remove(array, isEvenIndex);
assert.deepEqual(array, [2, 4]);
assert.deepEqual(actual, [1, 3]);
assert.deepEqual(remove(), []);
});
QUnit.test('`' + methodName + '` should extend existing configs', function(assert) {
assert.expect(2);
var array = [1, 2, 3, 4],
lodash = func({ 'cap': false }),
remove = (isFp ? lodash.remove : lodash).convert({ 'rearg': false }),
actual = remove(array)(isEvenIndex);
assert.deepEqual(array, [1, 2, 3, 4]);
assert.deepEqual(actual, [2, 4]);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('method arity checks');
(function() {
QUnit.test('should wrap methods with an arity > `1`', function(assert) {
assert.expect(1);
var methodNames = _.filter(_.functions(fp), function(methodName) {
return fp[methodName].length > 1;
});
assert.deepEqual(methodNames, []);
});
QUnit.test('should have >= arity of `aryMethod` designation', function(assert) {
assert.expect(4);
_.times(4, function(index) {
var aryCap = index + 1;
var methodNames = _.filter(mapping.aryMethod[aryCap], function(methodName) {
var key = _.get(mapping.remap, methodName, methodName),
arity = _[key].length;
return arity != 0 && arity < aryCap;
});
assert.deepEqual(methodNames, [], '`aryMethod[' + aryCap + ']`');
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('method aliases');
(function() {
QUnit.test('should have correct aliases', function(assert) {
assert.expect(1);
var actual = _.transform(mapping.aliasToReal, function(result, realName, alias) {
result.push([alias, fp[alias] === fp[realName]]);
}, []);
assert.deepEqual(_.reject(actual, 1), []);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('method ary caps');
(function() {
QUnit.test('should have a cap of 1', function(assert) {
assert.expect(1);
var funcMethods = [
'curry', 'iteratee', 'memoize', 'over', 'overEvery', 'overSome',
'method', 'methodOf', 'rest', 'runInContext'
];
var exceptions = funcMethods.concat('mixin', 'nthArg', 'template'),
expected = _.map(mapping.aryMethod[1], _.constant(true));
var actual = _.map(mapping.aryMethod[1], function(methodName) {
var arg = _.includes(funcMethods, methodName) ? _.noop : 1,
result = _.attempt(function() { return fp[methodName](arg); });
if (_.includes(exceptions, methodName)
? typeof result == 'function'
: typeof result != 'function'
) {
return true;
}
console.log(methodName, result);
return false;
});
assert.deepEqual(actual, expected);
});
QUnit.test('should have a cap of 2', function(assert) {
assert.expect(1);
var funcMethods = [
'after', 'ary', 'before', 'bind', 'bindKey', 'curryN', 'debounce',
'delay', 'overArgs', 'partial', 'partialRight', 'rearg', 'throttle',
'wrap'
];
var exceptions = _.without(funcMethods.concat('matchesProperty'), 'delay'),
expected = _.map(mapping.aryMethod[2], _.constant(true));
var actual = _.map(mapping.aryMethod[2], function(methodName) {
var args = _.includes(funcMethods, methodName) ? [methodName == 'curryN' ? 1 : _.noop, _.noop] : [1, []],
result = _.attempt(function() { return fp[methodName](args[0])(args[1]); });
if (_.includes(exceptions, methodName)
? typeof result == 'function'
: typeof result != 'function'
) {
return true;
}
console.log(methodName, result);
return false;
});
assert.deepEqual(actual, expected);
});
QUnit.test('should have a cap of 3', function(assert) {
assert.expect(1);
var funcMethods = [
'assignWith', 'extendWith', 'isEqualWith', 'isMatchWith', 'reduce',
'reduceRight', 'transform', 'zipWith'
];
var expected = _.map(mapping.aryMethod[3], _.constant(true));
var actual = _.map(mapping.aryMethod[3], function(methodName) {
var args = _.includes(funcMethods, methodName) ? [_.noop, 0, 1] : [0, 1, []],
result = _.attempt(function() { return fp[methodName](args[0])(args[1])(args[2]); });
if (typeof result != 'function') {
return true;
}
console.log(methodName, result);
return false;
});
assert.deepEqual(actual, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('methods that use `indexOf`');
(function() {
QUnit.test('should work with `fp.indexOf`', function(assert) {
assert.expect(10);
var array = ['a', 'b', 'c'],
other = ['b', 'd', 'b'],
object = { 'a': 1, 'b': 2, 'c': 2 },
actual = fp.difference(array)(other);
assert.deepEqual(actual, ['a', 'c'], 'fp.difference');
actual = fp.includes('b')(array);
assert.strictEqual(actual, true, 'fp.includes');
actual = fp.intersection(other)(array);
assert.deepEqual(actual, ['b'], 'fp.intersection');
actual = fp.omit(other)(object);
assert.deepEqual(actual, { 'a': 1, 'c': 2 }, 'fp.omit');
actual = fp.union(other)(array);
assert.deepEqual(actual, ['a', 'b', 'c', 'd'], 'fp.union');
actual = fp.uniq(other);
assert.deepEqual(actual, ['b', 'd'], 'fp.uniq');
actual = fp.uniqBy(_.identity, other);
assert.deepEqual(actual, ['b', 'd'], 'fp.uniqBy');
actual = fp.without(other)(array);
assert.deepEqual(actual, ['a', 'c'], 'fp.without');
actual = fp.xor(other)(array);
assert.deepEqual(actual, ['a', 'c', 'd'], 'fp.xor');
actual = fp.pull('b')(array);
assert.deepEqual(actual, ['a', 'c'], 'fp.pull');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('cherry-picked methods');
(function() {
QUnit.test('should provide the correct `iteratee` arguments', function(assert) {
assert.expect(4);
var args,
array = [1, 2, 3],
object = { 'a': 1, 'b': 2 },
isFIFO = _.keys(object)[0] == 'a',
map = convert('map', _.map),
reduce = convert('reduce', _.reduce);
map(function() {
args || (args = slice.call(arguments));
})(array);
assert.deepEqual(args, [1]);
args = undefined;
map(function() {
args || (args = slice.call(arguments));
})(object);
assert.deepEqual(args, isFIFO ? [1] : [2]);
args = undefined;
reduce(function() {
args || (args = slice.call(arguments));
})(0)(array);
assert.deepEqual(args, [0, 1]);
args = undefined;
reduce(function() {
args || (args = slice.call(arguments));
})(0)(object);
assert.deepEqual(args, isFIFO ? [0, 1] : [0, 2]);
});
QUnit.test('should not support shortcut fusion', function(assert) {
assert.expect(3);
var array = fp.range(0, LARGE_ARRAY_SIZE),
filterCount = 0,
mapCount = 0;
var iteratee = function(value) {
mapCount++;
return value * value;
};
var predicate = function(value) {
filterCount++;
return isEven(value);
};
var map1 = convert('map', _.map),
filter1 = convert('filter', _.filter),
take1 = convert('take', _.take);
var filter2 = filter1(predicate),
map2 = map1(iteratee),
take2 = take1(2);
var combined = fp.flow(map2, filter2, fp.compact, take2);
assert.deepEqual(combined(array), [4, 16]);
assert.strictEqual(filterCount, 200, 'filterCount');
assert.strictEqual(mapCount, 200, 'mapCount');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('iteratee shorthands');
(function() {
var objects = [{ 'a': 1, 'b': 2 }, { 'a': 3, 'b': 4 }];
QUnit.test('should work with "_.matches" shorthands', function(assert) {
assert.expect(1);
assert.deepEqual(fp.filter({ 'a': 3 })(objects), [objects[1]]);
});
QUnit.test('should work with "_.matchesProperty" shorthands', function(assert) {
assert.expect(1);
assert.deepEqual(fp.filter(['a', 3])(objects), [objects[1]]);
});
QUnit.test('should work with "_.property" shorthands', function(assert) {
assert.expect(1);
assert.deepEqual(fp.map('a')(objects), [1, 3]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('placeholder methods');
(function() {
QUnit.test('should use `fp` as the default placeholder', function(assert) {
assert.expect(3);
var actual = fp.add(fp, 'b')('a');
assert.strictEqual(actual, 'ab');
actual = fp.fill(fp, 2)(1, '*')([1, 2, 3]);
assert.deepEqual(actual, [1, '*', 3]);
actual = fp.slice(fp, 2)(1)(['a', 'b', 'c']);
assert.deepEqual(actual, ['b']);
});
QUnit.test('should support `fp.placeholder`', function(assert) {
assert.expect(6);
_.each([[], fp.__], function(ph) {
fp.placeholder = ph;
var actual = fp.add(ph, 'b')('a');
assert.strictEqual(actual, 'ab');
actual = fp.fill(ph, 2)(1, '*')([1, 2, 3]);
assert.deepEqual(actual, [1, '*', 3]);
actual = fp.slice(ph, 2)(1)(['a', 'b', 'c']);
assert.deepEqual(actual, ['b']);
});
});
var methodNames = [
'bind',
'bindKey',
'curry',
'curryRight',
'partial',
'partialRight'
];
_.each(methodNames, function(methodName) {
var func = fp[methodName];
QUnit.test('fp.' + methodName + '` should have a `placeholder` property', function(assert) {
assert.expect(2);
assert.ok(_.isObject(func.placeholder));
assert.strictEqual(func.placeholder, fp.__);
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('setter methods');
(function() {
QUnit.test('should only clone objects in `path`', function(assert) {
assert.expect(11);
var object = { 'a': { 'b': 2, 'c': 3 }, 'd': { 'e': 4 } },
value = _.cloneDeep(object),
actual = fp.set('a.b.c.d', 5, value);
assert.ok(_.isObject(actual.a.b), 'fp.set');
assert.ok(_.isNumber(actual.a.b), 'fp.set');
assert.strictEqual(actual.a.b.c.d, 5, 'fp.set');
assert.strictEqual(actual.d, value.d, 'fp.set');
value = _.cloneDeep(object);
actual = fp.setWith(Object)('[0][1]')('a')(value);
assert.deepEqual(actual[0], { '1': 'a' }, 'fp.setWith');
value = _.cloneDeep(object);
actual = fp.unset('a.b')(value);
assert.notOk('b' in actual.a, 'fp.unset');
assert.strictEqual(actual.a.c, value.a.c, 'fp.unset');
value = _.cloneDeep(object);
actual = fp.update('a.b')(square)(value);
assert.strictEqual(actual.a.b, 4, 'fp.update');
assert.strictEqual(actual.d, value.d, 'fp.update');
value = _.cloneDeep(object);
actual = fp.updateWith(Object)('[0][1]')(_.constant('a'))(value);
assert.deepEqual(actual[0], { '1': 'a' }, 'fp.updateWith');
assert.strictEqual(actual.d, value.d, 'fp.updateWith');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.add and fp.subtract');
_.each(['add', 'subtract'], function(methodName) {
var func = fp[methodName],
isAdd = methodName == 'add';
QUnit.test('`fp.' + methodName + '` should not have `rearg` applied', function(assert) {
assert.expect(1);
assert.strictEqual(func('1')('2'), isAdd ? '12' : -1);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('object assignments');
_.each(['assign', 'assignIn', 'defaults', 'defaultsDeep', 'merge'], function(methodName) {
var func = fp[methodName];
QUnit.test('`fp.' + methodName + '` should not mutate values', function(assert) {
assert.expect(2);
var object = { 'a': 1 },
actual = func(object)({ 'b': 2 });
assert.deepEqual(object, { 'a': 1 });
assert.deepEqual(actual, { 'a': 1, 'b': 2 });
});
});
_.each(['assignAll', 'assignInAll', 'defaultsAll', 'defaultsDeepAll', 'mergeAll'], function(methodName) {
var func = fp[methodName];
QUnit.test('`fp.' + methodName + '` should not mutate values', function(assert) {
assert.expect(2);
var objects = [{ 'a': 1 }, { 'b': 2 }],
actual = func(objects);
assert.deepEqual(objects[0], { 'a': 1 });
assert.deepEqual(actual, { 'a': 1, 'b': 2 });
});
});
_.each(['assignWith', 'assignInWith', 'extendWith'], function(methodName) {
var func = fp[methodName];
QUnit.test('`fp.' + methodName + '` should provide the correct `customizer` arguments', function(assert) {
assert.expect(1);
var args;
func(function() {
args || (args = _.map(arguments, _.cloneDeep));
})({ 'a': 1 })({ 'b': 2 });
assert.deepEqual(args, [undefined, 2, 'b', { 'a': 1 }, { 'b': 2 }]);
});
});
_.each(['assignAllWith', 'assignInAllWith', 'extendAllWith', 'mergeAllWith'], function(methodName) {
var func = fp[methodName];
QUnit.test('`fp.' + methodName + '` should not mutate values', function(assert) {
assert.expect(2);
var objects = [{ 'a': 1 }, { 'b': 2 }],
actual = func(_.noop)(objects);
assert.deepEqual(objects[0], { 'a': 1 });
assert.deepEqual(actual, { 'a': 1, 'b': 2 });
});
QUnit.test('`fp.' + methodName + '` should work with more than two sources', function(assert) {
assert.expect(2);
var pass = false,
objects = [{ 'a': 1 }, { 'b': 2 }, { 'c': 3 }],
actual = func(function() { pass = true; })(objects);
assert.ok(pass);
assert.deepEqual(actual, { 'a': 1, 'b': 2, 'c': 3 });
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.castArray');
(function() {
QUnit.test('should shallow clone array values', function(assert) {
assert.expect(2);
var array = [1],
actual = fp.castArray(array);
assert.deepEqual(actual, array);
assert.notStrictEqual(actual, array);
});
QUnit.test('should not shallow clone non-array values', function(assert) {
assert.expect(2);
var object = { 'a': 1 },
actual = fp.castArray(object);
assert.deepEqual(actual, [object]);
assert.strictEqual(actual[0], object);
});
QUnit.test('should convert by name', function(assert) {
assert.expect(4);
var array = [1],
object = { 'a': 1 },
castArray = convert('castArray', _.castArray),
actual = castArray(array);
assert.deepEqual(actual, array);
assert.notStrictEqual(actual, array);
actual = castArray(object);
assert.deepEqual(actual, [object]);
assert.strictEqual(actual[0], object);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('curry methods');
_.each(['curry', 'curryRight'], function(methodName) {
var func = fp[methodName];
QUnit.test('fp.' + methodName + '` should only accept a `func` param', function(assert) {
assert.expect(1);
assert.raises(function() { func(1, _.noop); }, TypeError);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('curryN methods');
_.each(['curryN', 'curryRightN'], function(methodName) {
var func = fp[methodName];
QUnit.test('fp.' + methodName + '` should accept an `arity` param', function(assert) {
assert.expect(1);
var actual = func(1)(function(a, b) { return [a, b]; })('a');
assert.deepEqual(actual, ['a', undefined]);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.defaultTo');
(function() {
QUnit.test('should have an argument order of `defaultValue` then `value`', function(assert) {
assert.expect(2);
assert.strictEqual(fp.defaultTo(1)(0), 0);
assert.strictEqual(fp.defaultTo(1)(undefined), 1);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.difference');
(function() {
QUnit.test('should return the elements of the first array not included in the second array', function(assert) {
assert.expect(1);
var actual = fp.difference([2, 1], [2, 3]);
assert.deepEqual(actual, [1]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.differenceBy');
(function() {
QUnit.test('should have an argument order of `iteratee`, `array`, then `values`', function(assert) {
assert.expect(1);
var actual = fp.differenceBy(Math.floor, [2.1, 1.2], [2.3, 3.4]);
assert.deepEqual(actual, [1.2]);
});
QUnit.test('should provide the correct `iteratee` arguments', function(assert) {
assert.expect(1);
var args;
fp.differenceBy(function() {
args || (args = slice.call(arguments));
})([2.1, 1.2], [2.3, 3.4]);
assert.deepEqual(args, [2.3]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.differenceWith');
(function() {
QUnit.test('should have an argument order of `comparator`, `array`, then `values`', function(assert) {
assert.expect(1);
var actual = fp.differenceWith(fp.eq)([2, 1])([2, 3]);
assert.deepEqual(actual, [1]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.divide and fp.multiply');
_.each(['divide', 'multiply'], function(methodName) {
var func = fp[methodName],
isDivide = methodName == 'divide';
QUnit.test('`fp.' + methodName + '` should not have `rearg` applied', function(assert) {
assert.expect(1);
assert.strictEqual(func('2')('4'), isDivide ? 0.5 : 8);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.extend');
(function() {
QUnit.test('should convert by name', function(assert) {
assert.expect(2);
function Foo() {}
Foo.prototype = { 'b': 2 };
var object = { 'a': 1 },
extend = convert('extend', _.extend),
actual = extend(object)(new Foo);
assert.deepEqual(object, { 'a': 1 });
assert.deepEqual(actual, { 'a': 1, 'b': 2 });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.fill');
(function() {
QUnit.test('should have an argument order of `start`, `end`, then `value`', function(assert) {
assert.expect(1);
var array = [1, 2, 3];
assert.deepEqual(fp.fill(1)(2)('*')(array), [1, '*', 3]);
});
QUnit.test('should not mutate values', function(assert) {
assert.expect(2);
var array = [1, 2, 3],
actual = fp.fill(1)(2)('*')(array);
assert.deepEqual(array, [1, 2, 3]);
assert.deepEqual(actual, [1, '*', 3]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.findFrom methods');
_.each(['findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom'], function(methodName) {
var func = fp[methodName];
QUnit.test('fp.' + methodName + '` should provide the correct `predicate` arguments', function(assert) {
assert.expect(1);
var args;
func(function() {
args || (args = slice.call(arguments));
})(1)([1, 2, 3]);
assert.deepEqual(args, [2]);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.findFrom');
(function() {
function resolve(value) {
return fp.flow(fp.property('a'), fp.eq(value));
}
QUnit.test('should have an argument order of `value`, `fromIndex`, then `array`', function(assert) {
assert.expect(2);
var objects = [{ 'a': 1 }, { 'a': 2 }, { 'a': 1 }, { 'a': 2 }];
assert.strictEqual(fp.findFrom(resolve(1))(1)(objects), objects[2]);
assert.strictEqual(fp.findFrom(resolve(2))(-2)(objects), objects[3]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.findLastFrom');
(function() {
function resolve(value) {
return fp.flow(fp.property('a'), fp.eq(value));
}
QUnit.test('should have an argument order of `value`, `fromIndex`, then `array`', function(assert) {
assert.expect(2);
var objects = [{ 'a': 1 }, { 'a': 2 }, { 'a': 1 }, { 'a': 2 }];
assert.strictEqual(fp.findLastFrom(resolve(1))(1)(objects), objects[0]);
assert.strictEqual(fp.findLastFrom(resolve(2))(-2)(objects), objects[1]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.findIndexFrom and fp.indexOfFrom');
_.each(['findIndexFrom', 'indexOfFrom'], function(methodName) {
var func = fp[methodName],
resolve = methodName == 'findIndexFrom' ? fp.eq : _.identity;
QUnit.test('fp.' + methodName + '` should have an argument order of `value`, `fromIndex`, then `array`', function(assert) {
assert.expect(2);
var array = [1, 2, 3, 1, 2, 3];
assert.strictEqual(func(resolve(1))(2)(array), 3);
assert.strictEqual(func(resolve(2))(-3)(array), 4);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.findLastIndexFrom and fp.lastIndexOfFrom');
_.each(['findLastIndexFrom', 'lastIndexOfFrom'], function(methodName) {
var func = fp[methodName],
resolve = methodName == 'findLastIndexFrom' ? fp.eq : _.identity;
QUnit.test('fp.' + methodName + '` should have an argument order of `value`, `fromIndex`, then `array`', function(assert) {
assert.expect(2);
var array = [1, 2, 3, 1, 2, 3];
assert.strictEqual(func(resolve(2))(3)(array), 1);
assert.strictEqual(func(resolve(3))(-3)(array), 2);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.flatMapDepth');
(function() {
QUnit.test('should have an argument order of `iteratee`, `depth`, then `collection`', function(assert) {
assert.expect(2);
function duplicate(n) {
return [[[n, n]]];
}
var array = [1, 2],
object = { 'a': 1, 'b': 2 },
expected = [[1, 1], [2, 2]];
assert.deepEqual(fp.flatMapDepth(duplicate)(2)(array), expected);
assert.deepEqual(fp.flatMapDepth(duplicate)(2)(object), expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('flow methods');
_.each(['flow', 'flowRight'], function(methodName) {
var func = fp[methodName],
isFlow = methodName == 'flow';
QUnit.test('`fp.' + methodName + '` should support shortcut fusion', function(assert) {
assert.expect(6);
var filterCount,
mapCount,
array = fp.range(0, LARGE_ARRAY_SIZE);
var iteratee = function(value) {
mapCount++;
return square(value);
};
var predicate = function(value) {
filterCount++;
return isEven(value);
};
var filter = fp.filter(predicate),
map = fp.map(iteratee),
take = fp.take(2);
_.times(2, function(index) {
var combined = isFlow
? func(map, filter, fp.compact, take)
: func(take, fp.compact, filter, map);
filterCount = mapCount = 0;
if (WeakMap && WeakMap.name) {
assert.deepEqual(combined(array), [4, 16]);
assert.strictEqual(filterCount, 5, 'filterCount');
assert.strictEqual(mapCount, 5, 'mapCount');
}
else {
skipAssert(assert, 3);
}
});
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('forEach methods');
_.each(['forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight'], function(methodName) {
var func = fp[methodName];
QUnit.test('`fp.' + methodName + '` should provide `value` to `iteratee`', function(assert) {
assert.expect(2);
var args;
func(function() {
args || (args = slice.call(arguments));
})(['a']);
assert.deepEqual(args, ['a']);
args = undefined;
func(function() {
args || (args = slice.call(arguments));
})({ 'a': 1 });
assert.deepEqual(args, [1]);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.getOr');
(function() {
QUnit.test('should accept a `defaultValue` param', function(assert) {
assert.expect(1);
var actual = fp.getOr('default')('path')({});
assert.strictEqual(actual, 'default');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.gt and fp.gte');
_.each(['gt', 'gte'], function(methodName) {
var func = fp[methodName];
QUnit.test('`fp.' + methodName + '` should have `rearg` applied', function(assert) {
assert.expect(1);
assert.strictEqual(func(2)(1), true);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.inRange');
(function() {
QUnit.test('should have an argument order of `start`, `end`, then `value`', function(assert) {
assert.expect(2);
assert.strictEqual(fp.inRange(2)(4)(3), true);
assert.strictEqual(fp.inRange(-2)(-6)(-3), true);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.intersectionBy');
(function() {
QUnit.test('should have an argument order of `iteratee`, `array`, then `values`', function(assert) {
assert.expect(1);
var actual = fp.intersectionBy(Math.floor, [2.1, 1.2], [2.3, 3.4]);
assert.deepEqual(actual, [2.1]);
});
QUnit.test('should provide the correct `iteratee` arguments', function(assert) {
assert.expect(1);
var args;
fp.intersectionBy(function() {
args || (args = slice.call(arguments));
})([2.1, 1.2], [2.3, 3.4]);
assert.deepEqual(args, [2.3]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.intersectionWith');
(function() {
QUnit.test('should have an argument order of `comparator`, `array`, then `values`', function(assert) {
assert.expect(1);
var actual = fp.intersectionWith(fp.eq)([2, 1])([2, 3]);
assert.deepEqual(actual, [2]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.invoke');
(function() {
QUnit.test('should not accept an `args` param', function(assert) {
assert.expect(1);
var actual = fp.invoke('toUpperCase')('a');
assert.strictEqual(actual, 'A');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.invokeMap');
(function() {
QUnit.test('should not accept an `args` param', function(assert) {
assert.expect(1);
var actual = fp.invokeMap('toUpperCase')(['a', 'b']);
assert.deepEqual(actual, ['A', 'B']);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.invokeArgs');
(function() {
QUnit.test('should accept an `args` param', function(assert) {
assert.expect(1);
var actual = fp.invokeArgs('concat')(['b', 'c'])('a');
assert.strictEqual(actual, 'abc');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.invokeArgsMap');
(function() {
QUnit.test('should accept an `args` param', function(assert) {
assert.expect(1);
var actual = fp.invokeArgsMap('concat')(['b', 'c'])(['a', 'A']);
assert.deepEqual(actual, ['abc', 'Abc']);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.isEqualWith');
(function() {
QUnit.test('should provide the correct `customizer` arguments', function(assert) {
assert.expect(1);
var args,
iteration = 0,
objects = [{ 'a': 1 }, { 'a': 2 }],
stack = { '__data__': { '__data__': [objects, objects.slice().reverse()], 'size': 2 }, 'size': 2 },
expected = [1, 2, 'a', objects[0], objects[1], stack];
fp.isEqualWith(function() {
if (++iteration == 2) {
args = _.map(arguments, _.cloneDeep);
}
})(objects[0])(objects[1]);
args[5] = _.omitBy(args[5], _.isFunction);
args[5].__data__ = _.omitBy(args[5].__data__, _.isFunction);
assert.deepEqual(args, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.isMatchWith');
(function() {
QUnit.test('should provide the correct `customizer` arguments', function(assert) {
assert.expect(1);
var args,
objects = [{ 'a': 1 }, { 'a': 2 }],
stack = { '__data__': { '__data__': [], 'size': 0 }, 'size': 0 },
expected = [2, 1, 'a', objects[1], objects[0], stack];
fp.isMatchWith(function() {
args || (args = _.map(arguments, _.cloneDeep));
})(objects[0])(objects[1]);
args[5] = _.omitBy(args[5], _.isFunction);
args[5].__data__ = _.omitBy(args[5].__data__, _.isFunction);
assert.deepEqual(args, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.iteratee');
(function() {
QUnit.test('should return a iteratee with capped params', function(assert) {
assert.expect(1);
var func = fp.iteratee(function(a, b, c) { return [a, b, c]; }, 3);
assert.deepEqual(func(1, 2, 3), [1, undefined, undefined]);
});
QUnit.test('should convert by name', function(assert) {
assert.expect(1);
var iteratee = convert('iteratee', _.iteratee),
func = iteratee(function(a, b, c) { return [a, b, c]; }, 3);
assert.deepEqual(func(1, 2, 3), [1, undefined, undefined]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.lt and fp.lte');
_.each(['lt', 'lte'], function(methodName) {
var func = fp[methodName];
QUnit.test('`fp.' + methodName + '` should have `rearg` applied', function(assert) {
assert.expect(1);
assert.strictEqual(func(1)(2), true);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.mapKeys');
(function() {
QUnit.test('should only provide `key` to `iteratee`', function(assert) {
assert.expect(1);
var args;
fp.mapKeys(function() {
args || (args = slice.call(arguments));
}, { 'a': 1 });
assert.deepEqual(args, ['a']);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.maxBy and fp.minBy');
_.each(['maxBy', 'minBy'], function(methodName) {
var array = [1, 2, 3],
func = fp[methodName],
isMax = methodName == 'maxBy';
QUnit.test('`fp.' + methodName + '` should work with an `iteratee` argument', function(assert) {
assert.expect(1);
var actual = func(function(num) {
return -num;
})(array);
assert.strictEqual(actual, isMax ? 1 : 3);
});
QUnit.test('`fp.' + methodName + '` should provide the correct `iteratee` arguments', function(assert) {
assert.expect(1);
var args;
func(function() {
args || (args = slice.call(arguments));
})(array);
assert.deepEqual(args, [1]);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.mergeWith');
(function() {
QUnit.test('should provide the correct `customizer` arguments', function(assert) {
assert.expect(1);
var args,
stack = { '__data__': { '__data__': [], 'size': 0 }, 'size': 0 },
expected = [[1, 2], [3], 'a', { 'a': [1, 2] }, { 'a': [3] }, stack];
fp.mergeWith(function() {
args || (args = _.map(arguments, _.cloneDeep));
})({ 'a': [1, 2] })({ 'a': [3] });
args[5] = _.omitBy(args[5], _.isFunction);
args[5].__data__ = _.omitBy(args[5].__data__, _.isFunction);
assert.deepEqual(args, expected);
});
QUnit.test('should not mutate values', function(assert) {
assert.expect(2);
var objects = [{ 'a': [1, 2] }, { 'a': [3] }],
actual = fp.mergeWith(_.noop, objects[0], objects[1]);
assert.deepEqual(objects[0], { 'a': [1, 2] });
assert.deepEqual(actual, { 'a': [3, 2] });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.mergeAllWith');
(function() {
QUnit.test('should provide the correct `customizer` arguments', function(assert) {
assert.expect(1);
var args,
objects = [{ 'a': [1, 2] }, { 'a': [3] }],
stack = { '__data__': { '__data__': [], 'size': 0 }, 'size': 0 },
expected = [[1, 2], [3], 'a', { 'a': [1, 2] }, { 'a': [3] }, stack];
fp.mergeAllWith(function() {
args || (args = _.map(arguments, _.cloneDeep));
})(objects);
args[5] = _.omitBy(args[5], _.isFunction);
args[5].__data__ = _.omitBy(args[5].__data__, _.isFunction);
assert.deepEqual(args, expected);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.mixin');
(function() {
var source = { 'a': _.noop };
QUnit.test('should mixin static methods but not prototype methods', function(assert) {
assert.expect(2);
fp.mixin(source);
assert.strictEqual(typeof fp.a, 'function');
assert.notOk('a' in fp.prototype);
delete fp.a;
delete fp.prototype.a;
});
QUnit.test('should not assign inherited `source` methods', function(assert) {
assert.expect(2);
function Foo() {}
Foo.prototype.a = _.noop;
fp.mixin(new Foo);
assert.notOk('a' in fp);
assert.notOk('a' in fp.prototype);
delete fp.a;
delete fp.prototype.a;
});
QUnit.test('should not remove existing prototype methods', function(assert) {
assert.expect(2);
var each1 = fp.each,
each2 = fp.prototype.each;
fp.mixin({ 'each': source.a });
assert.strictEqual(fp.each, source.a);
assert.strictEqual(fp.prototype.each, each2);
fp.each = each1;
fp.prototype.each = each2;
});
QUnit.test('should not export to the global when `source` is not an object', function(assert) {
assert.expect(2);
var props = _.without(_.keys(_), '_');
_.times(2, function(index) {
fp.mixin.apply(fp, index ? [1] : []);
assert.ok(_.every(props, function(key) {
return root[key] !== fp[key];
}));
_.each(props, function(key) {
if (root[key] === fp[key]) {
delete root[key];
}
});
});
});
QUnit.test('should convert by name', function(assert) {
assert.expect(3);
var object = { 'mixin': convert('mixin', _.mixin) };
function Foo() {}
Foo.mixin = object.mixin;
Foo.mixin(source);
assert.ok('a' in Foo);
assert.notOk('a' in Foo.prototype);
object.mixin(source);
assert.ok('a' in object);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.nthArg');
(function() {
QUnit.test('should return a curried function', function(assert) {
assert.expect(2);
var func = fp.nthArg(1);
assert.strictEqual(func(1)(2), 2);
func = fp.nthArg(-1);
assert.strictEqual(func(1), 1);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.over');
(function() {
QUnit.test('should not cap iteratee args', function(assert) {
assert.expect(2);
_.each([fp.over, convert('over', _.over)], function(func) {
var over = func([Math.max, Math.min]);
assert.deepEqual(over(1, 2, 3, 4), [4, 1]);
});
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.omitBy and fp.pickBy');
_.each(['omitBy', 'pickBy'], function(methodName) {
var func = fp[methodName];
QUnit.test('`fp.' + methodName + '` should provide `value` and `key` to `iteratee`', function(assert) {
assert.expect(1);
var args;
func(function() {
args || (args = slice.call(arguments));
})({ 'a': 1 });
assert.deepEqual(args, [1, 'a']);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('padChars methods');
_.each(['padChars', 'padCharsStart', 'padCharsEnd'], function(methodName) {
var func = fp[methodName],
isPad = methodName == 'padChars',
isStart = methodName == 'padCharsStart';
QUnit.test('fp.' + methodName + '` should truncate pad characters to fit the pad length', function(assert) {
assert.expect(1);
if (isPad) {
assert.strictEqual(func('_-')(8)('abc'), '_-abc_-_');
} else {
assert.strictEqual(func('_-')(6)('abc'), isStart ? '_-_abc' : 'abc_-_');
}
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('partial methods');
_.each(['partial', 'partialRight'], function(methodName) {
var func = fp[methodName],
isPartial = methodName == 'partial';
QUnit.test('fp.' + methodName + '` should accept an `args` param', function(assert) {
assert.expect(1);
var expected = isPartial ? [1, 2, 3] : [0, 1, 2];
var actual = func(function(a, b, c) {
return [a, b, c];
})([1, 2])(isPartial ? 3 : 0);
assert.deepEqual(actual, expected);
});
QUnit.test('fp.' + methodName + '` should convert by name', function(assert) {
assert.expect(2);
var expected = isPartial ? [1, 2, 3] : [0, 1, 2],
par = convert(methodName, _[methodName]),
ph = par.placeholder;
var actual = par(function(a, b, c) {
return [a, b, c];
})([1, 2])(isPartial ? 3 : 0);
assert.deepEqual(actual, expected);
actual = par(function(a, b, c) {
return [a, b, c];
})([ph, 2])(isPartial ? 1 : 0, isPartial ? 3 : 1);
assert.deepEqual(actual, expected);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.propertyOf');
(function() {
QUnit.test('should be curried', function(assert) {
assert.expect(2);
var object = { 'a': 1 };
assert.strictEqual(fp.propertyOf(object, 'a'), 1);
assert.strictEqual(fp.propertyOf(object)('a'), 1);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.pull');
(function() {
QUnit.test('should not mutate values', function(assert) {
assert.expect(2);
var array = [1, 2, 3],
actual = fp.pull(2)(array);
assert.deepEqual(array, [1, 2, 3]);
assert.deepEqual(actual, [1, 3]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.pullAll');
(function() {
QUnit.test('should not mutate values', function(assert) {
assert.expect(2);
var array = [1, 2, 3],
actual = fp.pullAll([1, 3])(array);
assert.deepEqual(array, [1, 2, 3]);
assert.deepEqual(actual, [2]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.pullAt');
(function() {
QUnit.test('should not mutate values', function(assert) {
assert.expect(2);
var array = [1, 2, 3],
actual = fp.pullAt([0, 2])(array);
assert.deepEqual(array, [1, 2, 3]);
assert.deepEqual(actual, [2]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.random');
(function() {
var array = Array(1000);
QUnit.test('should support a `min` and `max` argument', function(assert) {
assert.expect(1);
var min = 5,
max = 10;
assert.ok(_.some(array, function() {
var result = fp.random(min)(max);
return result >= min && result <= max;
}));
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('range methods');
_.each(['range', 'rangeRight'], function(methodName) {
var func = fp[methodName],
isRange = methodName == 'range';
QUnit.test('fp.' + methodName + '` should have an argument order of `start` then `end`', function(assert) {
assert.expect(1);
assert.deepEqual(func(1)(4), isRange ? [1, 2, 3] : [3, 2, 1]);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('rangeStep methods');
_.each(['rangeStep', 'rangeStepRight'], function(methodName) {
var func = fp[methodName],
isRange = methodName == 'rangeStep';
QUnit.test('fp.' + methodName + '` should have an argument order of `step`, `start`, then `end`', function(assert) {
assert.expect(1);
assert.deepEqual(func(2)(1)(4), isRange ? [1, 3] : [3, 1]);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.rearg');
(function() {
function fn(a, b, c) {
return [a, b, c];
}
QUnit.test('should be curried', function(assert) {
assert.expect(1);
var rearged = fp.rearg([1, 2, 0])(fn);
assert.deepEqual(rearged('c', 'a', 'b'), ['a', 'b', 'c']);
});
QUnit.test('should return a curried function', function(assert) {
assert.expect(1);
var rearged = fp.rearg([1, 2, 0], fn);
assert.deepEqual(rearged('c')('a')('b'), ['a', 'b', 'c']);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('reduce methods');
_.each(['reduce', 'reduceRight'], function(methodName) {
var func = fp[methodName],
isReduce = methodName == 'reduce';
QUnit.test('`fp.' + methodName + '` should provide the correct `iteratee` arguments when iterating an array', function(assert) {
assert.expect(1);
var args;
func(function() {
args || (args = slice.call(arguments));
})(0)([1, 2, 3]);
assert.deepEqual(args, isReduce ? [0, 1] : [3, 0]);
});
QUnit.test('`fp.' + methodName + '` should provide the correct `iteratee` arguments when iterating an object', function(assert) {
assert.expect(1);
var args,
object = { 'a': 1, 'b': 2 },
isFIFO = _.keys(object)[0] == 'a';
var expected = isFIFO
? (isReduce ? [0, 1] : [2, 0])
: (isReduce ? [0, 2] : [1, 0]);
func(function() {
args || (args = slice.call(arguments));
})(0)(object);
assert.deepEqual(args, expected);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.remove');
(function() {
QUnit.test('should not mutate values', function(assert) {
assert.expect(2);
var array = [1, 2, 3],
actual = fp.remove(fp.eq(2))(array);
assert.deepEqual(array, [1, 2, 3]);
assert.deepEqual(actual, [1, 3]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.restFrom');
(function() {
QUnit.test('should accept a `start` param', function(assert) {
assert.expect(1);
var actual = fp.restFrom(2)(function() {
return slice.call(arguments);
})('a', 'b', 'c', 'd');
assert.deepEqual(actual, ['a', 'b', ['c', 'd']]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.reverse');
(function() {
QUnit.test('should not mutate values', function(assert) {
assert.expect(2);
var array = [1, 2, 3],
actual = fp.reverse(array);
assert.deepEqual(array, [1, 2, 3]);
assert.deepEqual(actual, [3, 2, 1]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.runInContext');
(function() {
QUnit.test('should return a converted lodash instance', function(assert) {
assert.expect(1);
assert.strictEqual(typeof fp.runInContext({}).curryN, 'function');
});
QUnit.test('should convert by name', function(assert) {
assert.expect(1);
var runInContext = convert('runInContext', _.runInContext);
assert.strictEqual(typeof runInContext({}).curryN, 'function');
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.set');
(function() {
QUnit.test('should not mutate values', function(assert) {
assert.expect(2);
var object = { 'a': { 'b': 2, 'c': 3 } },
actual = fp.set('a.b')(3)(object);
assert.deepEqual(object, { 'a': { 'b': 2, 'c': 3 } });
assert.deepEqual(actual, { 'a': { 'b': 3, 'c': 3 } });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.setWith');
(function() {
QUnit.test('should provide the correct `customizer` arguments', function(assert) {
assert.expect(1);
var args;
fp.setWith(function() {
args || (args = _.map(arguments, _.cloneDeep));
})('b.c')(2)({ 'a': 1 });
assert.deepEqual(args, [undefined, 'b', { 'a': 1 }]);
});
QUnit.test('should not mutate values', function(assert) {
assert.expect(2);
var object = { 'a': { 'b': 2, 'c': 3 } },
actual = fp.setWith(Object)('d.e')(4)(object);
assert.deepEqual(object, { 'a': { 'b': 2, 'c': 3 } });
assert.deepEqual(actual, { 'a': { 'b': 2, 'c': 3 }, 'd': { 'e': 4 } });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.spreadFrom');
(function() {
QUnit.test('should accept a `start` param', function(assert) {
assert.expect(1);
var actual = fp.spreadFrom(2)(function() {
return slice.call(arguments);
})('a', 'b', ['c', 'd']);
assert.deepEqual(actual, ['a', 'b', 'c', 'd']);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('trimChars methods');
_.each(['trimChars', 'trimCharsStart', 'trimCharsEnd'], function(methodName, index) {
var func = fp[methodName],
parts = [];
if (index != 2) {
parts.push('leading');
}
if (index != 1) {
parts.push('trailing');
}
parts = parts.join(' and ');
QUnit.test('`fp.' + methodName + '` should remove ' + parts + ' `chars`', function(assert) {
assert.expect(1);
var string = '-_-a-b-c-_-',
expected = (index == 2 ? '-_-' : '') + 'a-b-c' + (index == 1 ? '-_-' : '');
assert.strictEqual(func('_-')(string), expected);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.unionBy');
(function() {
QUnit.test('should have an argument order of `iteratee`, `array`, then `other`', function(assert) {
assert.expect(1);
var actual = fp.unionBy(Math.floor, [2.1], [1.2, 2.3]);
assert.deepEqual(actual, [2.1, 1.2]);
});
QUnit.test('should provide the correct `iteratee` arguments', function(assert) {
assert.expect(1);
var args;
fp.unionBy(function() {
args || (args = slice.call(arguments));
})([2.1], [1.2, 2.3]);
assert.deepEqual(args, [2.1]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.unionWith');
(function() {
QUnit.test('should have an argument order of `comparator`, `array`, then `values`', function(assert) {
assert.expect(1);
var actual = fp.unionWith(fp.eq)([2, 1])([2, 3]);
assert.deepEqual(actual, [2, 1, 3]);
});
QUnit.test('should provide the correct `comparator` arguments', function(assert) {
assert.expect(1);
var args;
fp.unionWith(function() {
args || (args = slice.call(arguments));
})([2, 1])([2, 3]);
assert.deepEqual(args, [1, 2]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.uniqBy');
(function() {
var objects = [{ 'a': 2 }, { 'a': 3 }, { 'a': 1 }, { 'a': 2 }, { 'a': 3 }, { 'a': 1 }];
QUnit.test('should work with an `iteratee` argument', function(assert) {
assert.expect(1);
var expected = objects.slice(0, 3),
actual = fp.uniqBy(_.property('a'))(objects);
assert.deepEqual(actual, expected);
});
QUnit.test('should provide the correct `iteratee` arguments', function(assert) {
assert.expect(1);
var args;
fp.uniqBy(function() {
args || (args = slice.call(arguments));
})(objects);
assert.deepEqual(args, [objects[0]]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.uniqWith');
(function() {
QUnit.test('should have an argument order of `comparator`, `array`, then `values`', function(assert) {
assert.expect(1);
var actual = fp.uniqWith(fp.eq)([2, 1, 2]);
assert.deepEqual(actual, [2, 1]);
});
QUnit.test('should provide the correct `comparator` arguments', function(assert) {
assert.expect(1);
var args;
fp.uniqWith(function() {
args || (args = slice.call(arguments));
})([2, 1, 2]);
assert.deepEqual(args, [1, 2]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.update');
(function() {
QUnit.test('should not convert end of `path` to an object', function(assert) {
assert.expect(1);
var actual = fp.update('a.b')(_.identity)({ 'a': { 'b': 1 } });
assert.strictEqual(typeof actual.a.b, 'number');
});
QUnit.test('should not convert uncloneables to objects', function(assert) {
assert.expect(2);
var object = { 'a': { 'b': _.constant(true) } },
actual = fp.update('a.b')(_.identity)(object);
assert.strictEqual(typeof object.a.b, 'function');
assert.strictEqual(object.a.b, actual.a.b);
});
QUnit.test('should not mutate values', function(assert) {
assert.expect(2);
var object = { 'a': { 'b': 2, 'c': 3 } },
actual = fp.update('a.b')(square)(object);
assert.deepEqual(object, { 'a': { 'b': 2, 'c': 3 } });
assert.deepEqual(actual, { 'a': { 'b': 4, 'c': 3 } });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.updateWith');
(function() {
QUnit.test('should provide the correct `customizer` arguments', function(assert) {
var args;
fp.updateWith(function() {
args || (args = _.map(arguments, _.cloneDeep));
})('b.c')(_.constant(2))({ 'a': 1 });
assert.deepEqual(args, [undefined, 'b', { 'a': 1 }]);
});
QUnit.test('should not mutate values', function(assert) {
assert.expect(2);
var object = { 'a': { 'b': 2, 'c': 3 } },
actual = fp.updateWith(Object)('d.e')(_.constant(4))(object);
assert.deepEqual(object, { 'a': { 'b': 2, 'c': 3 } });
assert.deepEqual(actual, { 'a': { 'b': 2, 'c': 3 }, 'd': { 'e': 4 } });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.unset');
(function() {
QUnit.test('should not mutate values', function(assert) {
assert.expect(2);
var object = { 'a': { 'b': 2, 'c': 3 } },
actual = fp.unset('a.b')(object);
assert.deepEqual(object, { 'a': { 'b': 2, 'c': 3 } });
assert.deepEqual(actual, { 'a': { 'c': 3 } });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.xorBy');
(function() {
QUnit.test('should have an argument order of `iteratee`, `array`, then `other`', function(assert) {
assert.expect(1);
var actual = fp.xorBy(Math.floor, [2.1, 1.2], [2.3, 3.4]);
assert.deepEqual(actual, [1.2, 3.4]);
});
QUnit.test('should provide the correct `iteratee` arguments', function(assert) {
assert.expect(1);
var args;
fp.xorBy(function() {
args || (args = slice.call(arguments));
})([2.1, 1.2], [2.3, 3.4]);
assert.deepEqual(args, [2.3]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.xorWith');
(function() {
QUnit.test('should have an argument order of `comparator`, `array`, then `values`', function(assert) {
assert.expect(1);
var actual = fp.xorWith(fp.eq)([2, 1])([2, 3]);
assert.deepEqual(actual, [1, 3]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('with methods');
_.each(['differenceWith', 'intersectionWith', 'xorWith'], function(methodName) {
var func = fp[methodName];
QUnit.test('`fp.' + methodName + '` should provide the correct `comparator` arguments', function(assert) {
assert.expect(1);
var args;
func(function() {
args || (args = slice.call(arguments));
})([2, 1])([2, 3]);
assert.deepEqual(args, [2, 2]);
});
});
/*--------------------------------------------------------------------------*/
QUnit.module('fp.zip');
(function() {
QUnit.test('should zip together two arrays', function(assert) {
assert.expect(1);
assert.deepEqual(fp.zip([1, 2])([3, 4]), [[1, 3], [2, 4]]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.zipAll');
(function() {
QUnit.test('should zip together an array of arrays', function(assert) {
assert.expect(1);
assert.deepEqual(fp.zipAll([[1, 2], [3, 4], [5, 6]]), [[1, 3, 5], [2, 4, 6]]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.zipObject');
(function() {
QUnit.test('should zip together key/value arrays into an object', function(assert) {
assert.expect(1);
assert.deepEqual(fp.zipObject(['a', 'b'])([1, 2]), { 'a': 1, 'b': 2 });
});
}());
/*--------------------------------------------------------------------------*/
QUnit.module('fp.zipWith');
(function() {
QUnit.test('should zip arrays combining grouped elements with `iteratee`', function(assert) {
assert.expect(1);
var array1 = [1, 2, 3],
array2 = [4, 5, 6],
actual = fp.zipWith(add)(array1)(array2);
assert.deepEqual(actual, [5, 7, 9]);
});
}());
/*--------------------------------------------------------------------------*/
QUnit.config.asyncRetries = 10;
QUnit.config.hidepassed = true;
if (!document) {
QUnit.config.noglobals = true;
QUnit.load();
QUnit.start();
}
}.call(this));
# Advanced Patterns
```{currentmodule} click
```
In addition to common functionality, Click offers some advanced features.
```{contents}
:depth: 1
:local: true
```
## Callbacks and Eager Options
Sometimes, you want a parameter to completely change the execution flow.
For instance, this is the case when you want to have a `--version`
parameter that prints out the version and then exits the application.
Note: an actual implementation of a `--version` parameter that is
reusable is available in Click as {func}`click.version_option`. The code
here is merely an example of how to implement such a flag.
In such cases, you need two concepts: eager parameters and a callback. An
eager parameter is a parameter handled before others, and a
callback is what executes after the parameter is handled. The eagerness
is necessary so that an earlier required parameter does not produce an
error message. For instance, if `--version` was not eager and a
parameter `--foo` was required and defined before, you would need to
specify it for `--version` to work. For more information, see
{ref}`callback-evaluation-order`.
A callback is a function invoked with three parameters: the
current {class}`Context`, the current {class}`Parameter`, and the value.
The context provides some useful features such as quitting the
application and gives access to other already processed parameters.
Here's an example for a `--version` flag:
```{eval-rst}
.. click:example::
def print_version(ctx, param, value):
if not value or ctx.resilient_parsing:
return
click.echo('Version 1.0')
ctx.exit()
@click.command()
@click.option('--version', is_flag=True, callback=print_version,
expose_value=False, is_eager=True)
def hello():
click.echo('Hello World!')
What it looks like:
.. click:run::
invoke(hello)
invoke(hello, args=['--version'])
```
The `expose_value` parameter prevents the pretty pointless `version`
parameter from being passed to the callback. If that was not specified, a
boolean would be passed to the `hello` script. The `resilient_parsing`
flag is applied to the context if Click wants to parse the command line
without any destructive behavior that would change the execution flow. In
this case, because we would exit the program, we instead do nothing.
## Callbacks for Validation
```{versionchanged} 2.0
```
If you want to apply custom validation logic, you can do this in the
parameter callbacks. These callbacks can both modify values and
raise errors if the validation does not work. The callback runs after
type conversion. It is called for all sources, including prompts.
In Click 1.0, you can only raise the {exc}`UsageError` but starting with
Click 2.0, you can also raise the {exc}`BadParameter` error, which has the
added advantage that it will automatically format the error message to
also contain the parameter name.
```{eval-rst}
.. click:example::
def validate_rolls(ctx, param, value):
if isinstance(value, tuple):
return value
try:
rolls, _, dice = value.partition("d")
return int(dice), int(rolls)
except ValueError:
raise click.BadParameter("format must be 'NdM'")
@click.command()
@click.option(
"--rolls", type=click.UNPROCESSED, callback=validate_rolls,
default="1d6", prompt=True,
)
def roll(rolls):
sides, times = rolls
click.echo(f"Rolling a {sides}-sided dice {times} time(s)")
.. click:run::
invoke(roll, args=["--rolls=42"])
println()
invoke(roll, args=["--rolls=2d12"])
println()
invoke(roll, input=["42", "2d12"])
```
## Parameter Modifications
Parameters (options and arguments) are forwarded to the command callbacks,
as you have seen. One common way to prevent a parameter from being passed
to the callback is the `expose_value` argument to a parameter which hides
the parameter entirely. The way this works is that the {class}`Context`
object has a {attr}`~Context.params` attribute which is a dictionary of
all parameters. Whatever is in that dictionary is being passed to the
callbacks.
This can be used to make up additional parameters. Generally, this pattern
is not recommended, but in some cases it can be useful. At the very least,
it's good to know that the system works this way.
```{eval-rst}
.. click:example::
import urllib.request
def open_url(ctx, param, value):
if value is not None:
ctx.params['fp'] = urllib.request.urlopen(value)
return value
@click.command()
@click.option('--url', callback=open_url)
def cli(url, fp=None):
if fp is not None:
click.echo(f"{url}: {fp.code}")
In this case the callback returns the URL unchanged but also passes a
second `fp` value to the callback.
.. caution::
Writing to :attr:`~click.Context.params` directly bypasses Click's
per-parameter pipeline: :meth:`~click.Context.get_parameter_source` returns
``None`` for it, the value is never run through any :class:`~click.ParamType`
conversion. And if the key collides with a declared parameter, then the
shared-name arbitration loses information about where the value came from.
Prefer the wrapper pattern below when any of those semantics matter.
What's more recommended is to pass the information in a wrapper, however:
.. click:example::
import urllib.request
class URL:
def __init__(self, url, fp):
self.url = url
self.fp = fp
def open_url(ctx, param, value):
if value is not None:
return URL(value, urllib.request.urlopen(value))
@click.command()
@click.option('--url', callback=open_url)
def cli(url):
if url is not None:
click.echo(f"{url.url}: {url.fp.code}")
```
## Token Normalization
```{versionadded} 2.0
```
Starting with Click 2.0, it's possible to provide a function used
for normalizing tokens. Tokens are option names, choice values, or command
values. This can be used to implement case-insensitive options, for
instance.
To use this feature, the context needs to be passed a function that
performs the normalization of the token. Such as a function that converts the
token to lowercase:
```{eval-rst}
.. click:example::
CONTEXT_SETTINGS = {'token_normalize_func': lambda x: x.lower()}
@click.command(context_settings=CONTEXT_SETTINGS)
@click.option('--name', default='Pete')
def cli(name):
click.echo(f"Name: {name}")
# And how it works on the command line:
.. click:run::
invoke(cli, prog_name='cli', args=['--NAME=Pete'])
```
## Invoking Other Commands
Sometimes, it might be interesting to invoke one command from another
command. This is a pattern generally discouraged with Click, but
possible nonetheless. For this, you can use the {func}`Context.invoke`
or {func}`Context.forward` methods.
They work similarly, but the difference is that {func}`Context.invoke` merely
invokes another command with the arguments you provide as a caller,
whereas {func}`Context.forward` fills in the arguments from the current
command. Both accept the command as the first argument, and everything else
is passed onwards as you would expect.
Example:
```{eval-rst}
.. click:example::
cli = click.Group()
@cli.command()
@click.option('--count', default=1)
def test(count):
click.echo(f'Count: {count}')
@cli.command()
@click.option('--count', default=1)
@click.pass_context
def dist(ctx, count):
ctx.forward(test)
ctx.invoke(test, count=42)
And what it looks like:
.. click:run::
invoke(cli, prog_name='cli', args=['dist'])
```
(forwarding-unknown-options)=
## Forwarding Unknown Options
In some situations, it is interesting to be able to accept all unknown
options for further manual processing. Click can generally do that as of
Click 4.0, but it has some limitations that lie in the nature of the
problem. The support for this is provided through a parser flag called
`ignore_unknown_options` which will instruct the parser to collect all
unknown options and to put them to the leftover argument instead of
triggering a parsing error.
This can generally be activated in two different ways:
1. It can be enabled on custom {class}`Command` subclasses by changing
the {attr}`~Command.ignore_unknown_options` attribute.
2. It can be enabled by changing the attribute of the same name on the
context class ({attr}`Context.ignore_unknown_options`). This is best
changed through the `context_settings` dictionary on the command.
For most situations, the easiest solution is the second. Once the behavior
is changed, something needs to pick up those leftover options (which at
this point are considered arguments). For this again, you have two
options:
1. You can use {func}`pass_context` to get the context passed. This will
only work if in addition to {attr}`~Context.ignore_unknown_options`
you also set {attr}`~Context.allow_extra_args` as otherwise the
command will abort with an error that there are leftover arguments.
If you go with this solution, the extra arguments will be collected in
{attr}`Context.args`.
2. You can attach an {func}`argument` with `nargs` set to `-1` which
will eat up all leftover arguments. In this case it's recommended to
set the `type` to {data}`UNPROCESSED` to avoid any string processing
on those arguments as otherwise they are forced into Unicode strings
automatically which is often not what you want.
In the end, the result looks something like this:
```{eval-rst}
.. click:example::
from subprocess import call
@click.command(context_settings={'ignore_unknown_options': True})
@click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')
@click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)
def cli(verbose, timeit_args):
"""A fake wrapper around Python's timeit."""
cmdline = ['echo', 'python', '-mtimeit', *timeit_args]
if verbose:
click.echo(f"Invoking: {' '.join(cmdline)}")
call(cmdline)
And the final output resembles the following:
.. click:run::
invoke(cli, prog_name='cli', args=['--help'])
println()
invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])
println()
invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])
```
As you can see, Click handles the verbosity flag and everything else
ends up in the `timeit_args` variable for further processing, which then
for instance, allows invoking a subprocess. There are a few things that
are important to know about how this ignoring of unhandled flag happens:
- Unknown long options are generally ignored and not processed at all.
So for instance if `--foo=bar` or `--foo bar` are passed they
generally end up like that. Note that because the parser cannot know
if an option will accept an argument or not, the `bar` part might be
handled as an argument.
- Unknown short options might be partially handled and reassembled if
necessary. For instance in the above example there is an option
called `-v` which enables verbose mode. If the command would be
invoked with `-va` then the `-v` part would be handled by Click
(as it is known) and `-a` would end up in the leftover parameters
for further processing.
- Depending on what you plan on doing you might have some success by
disabling interspersed arguments
({attr}`~Context.allow_interspersed_args`) which instructs the parser
to not allow arguments and options to be mixed. Depending on your
situation, this might improve your results.
Generally, combining the handling of options and arguments from your own
commands with those from another application is discouraged, and you
should avoid it if possible. It's a much better idea to have
everything below a subcommand be forwarded to another application than to
handle some arguments yourself.
## Managing Resources
It can be useful to open a resource in a group, to be made available to
subcommands. Many types of resources need to be closed or otherwise
cleaned up after use. The standard way to do this in Python is by using
a context manager with the `with` statement.
For example, the `Repo` class from {doc}`complex` might actually be
defined as a context manager:
```python
class Repo:
def __init__(self, home=None):
self.home = os.path.abspath(home or ".")
self.db = None
def __enter__(self):
path = os.path.join(self.home, "repo.db")
self.db = open_database(path)
return self
def __exit__(self, exc_type, exc_value, tb):
self.db.close()
```
Ordinarily, it would be used with the `with` statement:
```python
with Repo() as repo:
repo.db.query(...)
```
However, a `with` block in a group would exit and close the database
before it could be used by a subcommand.
Instead, use the context's {meth}`~click.Context.with_resource` method
to enter the context manager and return the resource. When the group and
any subcommands finish, the context's resources are cleaned up.
```python
@click.group()
@click.option("--repo-home", default=".repo")
@click.pass_context
def cli(ctx, repo_home):
ctx.obj = ctx.with_resource(Repo(repo_home))
@cli.command()
@click.pass_obj
def log(obj):
# obj is the repo opened in the cli group
for entry in obj.db.query(...):
click.echo(entry)
```
If the resource isn't a context manager, usually it can be wrapped in
one using something from {mod}`contextlib`. If that's not possible, use
the context's {meth}`~click.Context.call_on_close` method to register a
cleanup function.
```python
@click.group()
@click.option("--name", default="repo.db")
@click.pass_context
def cli(ctx, name):
ctx.obj = db = open_db(name)
@ctx.call_on_close
def close_db():
db.record_use()
db.save()
db.close()
```
```{versionchanged} 8.2
`Context.call_on_close` and context managers registered via `Context.with_resource`
will be closed when the CLI exits. These were previously not called on exit.
```
Aksjomat indukcji – aksjomat, a właściwie nieskończony przeliczalny zbiór aksjomatów pierwszego rzędu, pozalogicznych rozważany zwłaszcza w teorii arytmetyki liczb naturalnych. Jest on formalizacją zasady indukcji matematycznej.
Jego treść przedstawia się następująco:
gdzie oznacza: „dla każdego n” ⇒, to wynikanie (implikacja) oznacza „i”. Tak wyrażony aksjomat indukcji nie spełnia jednak założeń rozlicznych podejść, a w tym np. analizy Gödla niesprzeczności teorii matematycznych w szczególności arytmetyki. Problemem jest zupełna nieobliczalność relacji użytych do konstrukcji powyższego zdania: kwantyfikator ogólny „dla każdego n” nie da się bowiem zapisać jako funkcja obliczalna. Ponadto zdanie powyższe jest zdaniem drugiego rzędu z uwagi na użycie kwantyfikatora, co sprawia, że operuje ono obiektami niezdefiniowanymi w teorii (zbiorem liczb naturalnych n, z którego mamy wybierać wartości: nie można go skonstruować, zanim nie ustalimy listy aksjomatów i nie udowodnimy ich niesprzeczności).
Równoważnie aksjomat indukcji można zapisać jako koniunkcję zbioru aksjomatów w następującej postaci:
w której to notacji nie został użyty nieograniczony, a więc nieobliczalny (nierekurencyjny) kwantyfikator ogólny, wszystkie zdania są zaś pierwszego rzędu (wyrażają prawdy o zdefiniowanych wcześniej pojęciach pierwotnych arytmetyki, nie używając kwantyfikatora ogólnego). Uzyskujemy w ten sposób formalną poprawność sformułowania aksjomatu.
Aksjomaty indukcji są ważnym elementem teorii arytmetyki.
Znane są przykłady twierdzeń, w których chociaż znamy dowody twierdzenia dla każdego to twierdzenie nie może być dowiedzione w ramach arytmetyki liczb naturalnych (jest niedowiedlne), gdyż każdy z tych dowodów jest prowadzony za pomocą innych narzędzi i nie da się ich sprowadzić do kroku indukcyjnego (a więc rozumowania wykazującego ), zapisanego za pomocą języka arytmetyki i obejmującego wszystkie możliwe wartości (dla każdego n pojawia się pewien nowy element niewystępujący dla innych ).
Zobacz też
aksjomat nieskończoności
indukcja matematyczna
Bibliografia
Roman Murawski, Funkcje rekurencyjne i elementy metamatematyki. Problemy zupełności, rozstrzygalności, twierdzenia Gödla, Wydawnictwo Naukowe UAM, Poznań 1990.
Logika matematyczna
Annamocarya es un género monotípico de árboles de la familia Juglandaceae. Su única especie, Annamocarya sinensis es nativa del sudoeste de China (Guangxi, Guizhou, Yunnan) y norte de Vietnam. Se relaciona con Carya, y estaba incluida en el mismo género homónimo, como Carya sinensis, pero compartía ciertos caracteres con Juglans.
Descripción
Es un árbol de medio a grande, siempreverde de hasta 30 m de altura. Las hojas son de 3 a 5 dm de longitud, pinnadas con 7 a 11 folíolos que tienen márgenes enteros, distinguiéndose de Carya por tener bordes aserrados. Las flores tienen amentos producidos en primavera, con los amentos masculino en manojos de 5 a 8 juntos (simples en Carya). El fruto es una nuez de 6 a 8 cm de long. y 4 a 6 cm de ancho, con un prominente pico agudo en un extremo.
Taxonomía
El género fue descrito por Auguste Jean Baptiste Chevalier y publicado en Revue de Botanique Appliquée et d'Agriculture Tropicale, 21, p. 504 en el año 1941.
Sinonimia
Annamocarya indochinensis (A.Chev.) A. Chev.
Carya integrifoliolata (Kuang) Hjelmq.
Carya sinensis Dode
Carya tsiangiana Chun ex Lee
Carya tsiangii Chun ex Kuang & A.M.Lu
Juglandicarya integrifoliolata (Kuang) Hu
Juglans indochinensis A. Chev.
Rhamphocarya integrifoliolata Kuang
Referencias
Bibliografía
Flora of China Editorial Committee, 1999. Fl. China Vol. 4.
Enlaces externos
Annamocarya en eFlora''
Juglandaceae
Flora de China
Flora de Indochina
Flora de Asia continental
Aikido ( , , , ) is a modern Japanese martial art that is split into many different styles, including Iwama Ryu, Iwama Shin Shin Aiki Shuren Kai, Shodokan Aikido, Yoshinkan, Renshinkai, Aikikai and Ki Aikido. Aikido is now practiced in around 140 countries. It was originally developed by Morihei Ueshiba, as a synthesis of his martial studies, philosophy and religious beliefs. Ueshiba's goal was to create an art that practitioners could use to defend themselves while also protecting their attackers from injury. Aikido is often translated as "the way of unifying (with) life energy" or as "the way of harmonious spirit". According to the founder's philosophy, the primary goal in the practice of aikido is to overcome oneself instead of cultivating violence or aggressiveness. Morihei Ueshiba used the phrase to refer to this principle.
Aikido's fundamental principles include: (entering), , (breathing control), (triangular principle) and (turning) movements that redirect the opponent's attack momentum. Its curriculum comprises various techniques, primarily throws and joint locks. It also includes a weapons system encompassing the , and .
Aikido derives mainly from the martial art of Daitō-ryū Aiki-jūjutsu, but began to diverge from it in the late 1920s, partly due to Ueshiba's involvement with the Ōmoto-kyō religion. Ueshiba's early students' documents bear the term .
Ueshiba's senior students have different approaches to aikido, depending partly on when they studied with him. Today, aikido is found all over the world in a number of styles, with broad ranges of interpretation and emphasis. However, they all share techniques formulated by Ueshiba and most have concern for the well-being of the attacker.
Etymology and basic philosophy
The word "aikido" is formed of three kanji:
– – harmony, unifying
– – energy, spirit
– – way, path
The term does not readily appear in the Japanese language outside the scope of budō. This has led to many possible interpretations of the word.
() is mainly used in compounds to mean 'combine, unite, join together, meet', examples being (combined/united), (composition), (unite/combine/join together), (union/alliance/association), (combine/unify), and (mutual agreement). There is an idea of reciprocity, (to get to know one another), (talk/discussion/negotiation), and (meet by appointment).
() is often used to describe a feeling or emotive action, as in ('I feel X', as in terms of thinking but with less cognitive reasoning), and (feeling/sensation); it is used to mean energy or force, as in (electricity) and (magnetism); it can also refer to qualities or aspects of people or things, as in (spirit/trait/temperament). The characters aeteological history can be traced back to the much older Chinese character of () that is used extensively in Traditional Chinese medicine and acupunture.
The term in Aikido is found in many other Japanese martial arts such as, judo and kendo, and in various non-martial arts, such as Japanese calligraphy (), flower arranging () and tea ceremony ( or ).
Therefore, from a purely literal interpretation, aikido is the "Way of combining forces" or "Way of unifying energy", in which the term refers to the martial arts principle or tactic of blending with an attacker's movements for the purpose of controlling their actions with minimal effort. One applies by understanding the rhythm and intent of the attacker to find the optimal position and timing to apply a counter-technique.
History
Aikido was created by (1883–1969), referred to by some aikido practitioners as (Great Teacher). The term aikido was coined in the 20th century. Ueshiba envisioned aikido not only as the synthesis of his martial training, but as an expression of his personal philosophy of universal peace and reconciliation. During Ueshiba's lifetime and continuing today, aikido has evolved from the that Ueshiba studied into a variety of expressions by martial artists throughout the world.
Initial development
Ueshiba developed aikido primarily during the late 1920s through the 1930s through the synthesis of the older martial arts that he had studied. The core martial art from which aikido derives is Daitō-ryū Aiki-jūjutsu, which Ueshiba studied directly with Takeda Sōkaku, the reviver of that art. Additionally, Ueshiba is known to have studied Tenjin Shin'yō-ryū with Tozawa Tokusaburō in Tokyo in 1901, Gotōha Yagyū Shingan-ryū under Nakai Masakatsu in Sakai from 1903 to 1908, and judo with (1894–1972) in Tanabe in 1911.
The art of is the primary technical influence on aikido. Along with empty-handed throwing and joint-locking techniques, Ueshiba incorporated training movements with weapons, such as those for the spear (), short staff (), and possibly the . Aikido also derives much of its technical structure from the art of swordsmanship ().
Ueshiba moved to Hokkaidō in 1912, and began studying under Takeda Sokaku in 1915; His official association with Daitō-ryū continued until 1937. However, during the latter part of that period, Ueshiba had already begun to distance himself from Takeda and the . At that time Ueshiba referred to his martial art as "Aiki Budō". It is unclear exactly when Ueshiba began using the name "aikido", but it became the official name of the art in 1942 when the Greater Japan Martial Virtue Society () was engaged in a government sponsored reorganization and centralization of Japanese martial arts.
Religious influences
After Ueshiba left Hokkaidō in 1919, he met and was profoundly influenced by Onisaburo Deguchi, the spiritual leader of the Ōmoto-kyō religion (a neo-Shinto movement) in Ayabe. One of the primary features of Ōmoto-kyō is its emphasis on the attainment of utopia during one's life. This idea was a great influence on Ueshiba's martial arts philosophy of extending love and compassion especially to those who seek to harm others. Aikido demonstrates this philosophy in its emphasis on mastering martial arts so that one may receive an attack and harmlessly redirect it. In an ideal resolution, not only is the receiver unharmed, but so is the attacker.
In addition to the effect on his spiritual growth, the connection with Deguchi gave Ueshiba entry to elite political and military circles as a martial artist. As a result of this exposure, he was able to attract not only financial backing but also gifted students. Several of these students would found their own styles of aikido.
International dissemination
Aikido was first introduced to the rest of the world in 1951 by Minoru Mochizuki with a visit to France, where he demonstrated aikido techniques to judo students. He was followed by Tadashi Abe in 1952, who came as the official Aikikai Hombu representative, remaining in France for seven years. Kenji Tomiki toured with a delegation of various martial arts through 15 continental states of the United States in 1953. Later that year, Koichi Tohei was sent by Aikikai Hombu to Hawaii for a full year, where he set up several dōjō. This trip was followed by several subsequent visits and is considered the formal introduction of aikido to the United States. The United Kingdom followed in 1955; Italy in 1964 by Hiroshi Tada; and Germany in 1965 by Katsuaki Asai. Designated the "Official Delegate for Europe and Africa" by Morihei Ueshiba, Masamichi Noro arrived in France in September 1961. Seiichi Sugano was appointed to introduce aikido to Australia in 1965. Today there are aikido dōjō throughout the world.
Proliferation of independent organizations
The largest aikido organization is the Aikikai Foundation, which remains under the control of the Ueshiba family. However, aikido has developed into many styles, most of which were formed by Morihei Ueshiba's major students.
The earliest independent styles to emerge were Yoseikan Aikido, begun by Minoru Mochizuki in 1931, Yoshinkan Aikido, founded by Gozo Shioda in 1955, and Shodokan Aikido, founded by Kenji Tomiki in 1967. The emergence of these styles pre-dated Ueshiba's death and did not cause any major upheavals when they were formalized. Shodokan Aikido, however, was controversial, since it introduced a unique rule-based competition that some felt was contrary to the spirit of aikido.
After Ueshiba's death in 1969, two more major styles emerged. Significant controversy arose with the departure of the Aikikai Hombu Dojo's chief instructor Koichi Tohei, in 1974. Tohei left as a result of a disagreement with the son of the founder, Kisshomaru Ueshiba, who at that time headed the Aikikai Foundation. The disagreement was over the proper role of development in regular aikido training. After Tohei left, he formed his own style, called Shin Shin Toitsu Aikido, and the organization that governs it, the Ki Society ().
A final major style evolved from Ueshiba's retirement in Iwama, Ibaraki and the teaching methodology of long term student Morihiro Saito. It is unofficially referred to as the "Iwama style", and at one point a number of its followers formed a loose network of schools they called Iwama Ryu. Although Iwama style practitioners remained part of the Aikikai until Saito's death in 2002, followers of Saito subsequently split into two groups. One remained with the Aikikai and the other formed the independent Shinshin Aikishuren Kai in 2004 around Saito's son Hitohiro Saito.
Today, the major styles of aikido are each run by a separate governing organization, have their own in Japan, and are taught throughout the world.
The study of is an important component of aikido. The term does not specifically refer to either physical or mental training, as it encompasses both. The kanji for was written in its older form as up until the Japanese governmental writing reforms after World War II, and now is more prevalently seen in its modern form of . This form has the removal of the eight directions denoting the pre and post natal energies of (Chinese – ) also known in the Art of Aikido as "Source energy".
The character for is used in everyday Japanese terms, such as , or . has many meanings, including "ambience", "mind", "mood", or "intention and action", however, in traditional martial arts and medicine it is often referred to in its more general terminology as "life energy". Gozo Shioda's Yoshinkan Aikido, considered one of the "hard styles", largely follows Ueshiba's teachings from before World War II, and surmises that the secret to lies in timing and the application of the whole body's strength to a single point. In later years, Ueshiba's application of in aikido took on a softer, more gentle feel. This concept was known as Takemusu Aiki, and many of his later students teach about from this perspective. Koichi Tohei's Ki Society centers almost exclusively around the study of the empirical (albeit subjective) experience of , with students' proficiency in aikido techniques and development ranked separately.
Training
In aikido, as in virtually all Japanese martial arts, there are both physical and mental aspects of training. The physical training in aikido is diverse, covering both general physical fitness and conditioning, as well as specific techniques. Because a substantial portion of any aikido curriculum consists of throws, beginners learn how to safely fall or roll. The specific techniques for attack include both strikes and grabs; the techniques for defense consist of throws and pins. After basic techniques are learned, students study freestyle defense against multiple opponents, and techniques with weapons.
Fitness
Physical training goals pursued in conjunction with aikido include controlled relaxation, correct movement of joints such as hips and shoulders, flexibility, and endurance, with less emphasis on strength training. In aikido, pushing or extending movements are much more common than pulling or contracting movements. This distinction can be applied to general fitness goals for the aikido practitioner.
In aikido, specific muscles or muscle groups are not isolated and worked to improve tone, mass, or power. Aikido-related training emphasizes the use of coordinated whole-body movement and balance similar to yoga or pilates. For example, many dōjōs begin each class with , which may include stretching and (break falls).
Roles of and
Aikido training is based primarily on two partners practicing pre-arranged forms () rather than freestyle practice. The basic pattern is for the receiver of the technique () to initiate an attack against the person who applies the technique—the , or (depending on aikido style), also referred to as (when applying a throwing technique), who neutralises this attack with an aikido technique.
Both halves of the technique, that of and that of , are considered essential to aikido training. Both are studying aikido principles of blending and adaptation. learns to blend with and control attacking energy, while learns to become calm and flexible in the disadvantageous, off-balance positions in which places them. This "receiving" of the technique is called . continuously seeks to regain balance and cover vulnerabilities (e.g., an exposed side), while uses position and timing to keep off-balance and vulnerable. In more advanced training, will sometimes apply to regain balance and pin or throw .
refers to the act of receiving a technique. Good involves attention to the technique, the partner, and the immediate environment—it is considered an active part of the process of learning aikido. The method of falling itself is also important, and is a way for the practitioner to receive an aikido technique safely and minimize risk of injury.
Initial attacks
Aikido techniques are usually a defense against an attack, so students must learn to deliver various types of attacks to be able to practice aikido with a partner. Although attacks are not studied as thoroughly as in striking-based arts, attacks with intent (such as a strong strike or an immobilizing grab) are needed to study correct and effective application of technique.
Many of the of aikido resemble cuts from a sword or other grasped object, which indicate its origins in techniques intended for armed combat. Other techniques, which explicitly appear to be punches (), are practiced as thrusts with a knife or sword. Kicks are generally reserved for upper-level variations; reasons cited include that falls from kicks are especially dangerous, and that kicks (high kicks in particular) were uncommon during the types of combat prevalent in feudal Japan.
Some basic strikes include:
is a vertical knifehand strike to the head. In training, this is usually directed at the forehead or the crown for safety, but more dangerous versions of this attack target the bridge of the nose and the maxillary sinus.
is a diagonal knifehand strike to the side of the head or neck.
is a punch to the torso. Specific targets include the chest, abdomen, and solar plexus, sometimes referred to as , or .
is a punch to the face, sometimes referred to as .
Beginners in particular often practice techniques from grabs, both because they are safer and because it is easier to feel the energy and the direction of the movement of force of a hold than it is for a strike. Some grabs are historically derived from being held while trying to draw a weapon, whereupon a technique could then be used to free oneself and immobilize or strike the attacker while they are grabbing the defender. The following are examples of some basic grabs:
, when one hand grabs one wrist.
, when both hands grab one wrist; sometimes referred to as
, when both hands grab both wrists; sometimes referred to as .
when one shoulder is grabbed.
, when both shoulders are grabbed. It is sometimes combined with an overhead strike as .
, when the lapel is grabbed; sometimes referred to as .
Basic techniques
The following are a sample of the basic or widely practiced throws and pins. Many of these techniques derive from Daitō-ryū Aiki-jūjutsu, but some others were invented by Morihei Ueshiba. The precise terminology for some may vary between organisations and styles; the following are the terms used by the Aikikai Foundation. Note that despite the names of the first five techniques listed, they are not universally taught in numeric order.
, a control technique using one hand on the elbow and one hand near the wrist which leverages to the ground. This grip applies pressure into the ulnar nerve at the wrist.
is a pronating wristlock that torques the arm and applies painful nerve pressure. (There is an adductive wristlock or Z-lock in the version.)
is a rotational wristlock that directs upward-spiraling tension throughout the arm, elbow and shoulder.
is a shoulder control technique similar to , but with both hands gripping the forearm. The knuckles (from the palm side) are applied to the recipient's radial nerve against the periosteum of the forearm bone.
is a technique that is visually similar to , but with an inverted grip of the wrist, medial rotation of the arm and shoulder, and downward pressure on the elbow. Common in knife and other weapon take-aways.
is a throw during which 's hand is folded back past the shoulder, locking the shoulder joint.
is a supinating wristlock-throw that stretches the extensor digitorum.
is a loosely used umbrella term for various types of mechanically unrelated techniques; generally do not use joint locks like other techniques.
, throws in which moves through the space occupied by . The classic form superficially resembles a "clothesline" technique.
, a throw in which, beginning with , moving forward, sweeps one hand low ("earth") and the other high ("heaven"), which unbalances so that he or she easily topples over.
, aikido's version of the hip throw; drops their hips lower than those of , then flips over the resultant fulcrum.
or , a throw that locks the arms against each other (the kanji for "10" is a cross-shape: ).
is a throw in which sweeps 's arm back until it locks the shoulder joint, then uses forward pressure to throw them.
Implementations
Aikido makes use of body movement () to blend the movement of with the movement of . For example, an "entering" () technique consists of movements inward towards , while a technique uses a pivoting motion.
Additionally, an technique takes place in front of , whereas an technique takes place to their side; a technique is applied with motion to the front of , and a version is applied with motion towards the rear of , usually by incorporating a turning or pivoting motion. Finally, most techniques can be performed while in a seated posture (). Techniques where both and are standing are called , techniques where both start off in are called , and techniques performed with standing and sitting are called ().
From these few basic techniques, there are numerous of possible implementations. For example, can be applied to an opponent moving forward with a strike (perhaps with an type of movement to redirect the incoming force), or to an opponent who has already struck and is now moving back to reestablish distance (perhaps an version). Specific aikido are typically referred to with the formula "attack-technique(-modifier)"; , for example, refers to any technique executed when is holding one wrist. This could be further specified as (referring to any forward-moving technique from that grab).
are strikes (or feints) employed during an aikido technique. Some view as attacks against "vital points" meant to cause damage in and of themselves. For instance, Gozo Shioda described using in a brawl to quickly down a gang's leader. Others consider , especially to the face, to be methods of distraction meant to enable other techniques; a strike, even if it is blocked, can startle the target and break their concentration. Additionally, the target may also become unbalanced while attempting to avoid a strike (by jerking the head back, for example) which may allow for an easier throw. Many sayings about are attributed to Morihei Ueshiba, who considered them an essential element of technique.
Weapons
Weapons training in aikido traditionally includes the short staff () (these techniques closely resemble the use of the bayonet, or Jūkendō), the wooden sword (), and the knife (). Some schools incorporate firearm-disarming techniques, where either weapon-taking and/or weapon-retention may be taught. Some schools, such as the Iwama style of Morihiro Saito, usually spend substantial time practicing with both and , under the names of , and , respectively.
The founder developed many of the empty-handed techniques from traditional sword, spear and bayonet movements. Consequently, the practice of the weapons arts gives insight into the origin of techniques and movements, and reinforces the concepts of distance, timing, foot movement, presence and connectedness with one's training partner(s).
Multiple attackers and
One feature of aikido is training to defend against multiple attackers, often called , or . Freestyle practice with multiple attackers called is a key part of most curricula and is required for the higher-level ranks. exercises a person's ability to intuitively perform techniques in an unstructured environment. Strategic choice of techniques, based on how they reposition the student relative to other attackers, is important in training. For instance, an technique might be used to neutralise the current attacker while turning to face attackers approaching from behind.
In Shodokan Aikido, differs in that it is not performed with multiple persons with defined roles of defender and attacker, but between two people, where both participants attack, defend, and counter at will. In this respect it resembles judo .
Injuries
In applying a technique during training, it is the responsibility of to prevent injury to by employing a speed and force of application that is appropriate with their partner's proficiency in . When injuries (especially to the joints) occur, they are often the result of a misjudging the ability of to receive the throw or pin.
A study of injuries in the martial arts showed that the type of injuries varied considerably from one art to the other. Soft tissue injuries are one of the most common types of injuries found within aikido, as well as joint strain and stubbed fingers and toes. Several deaths from head-and-neck injuries, caused by aggressive in a hazing context, have been reported.
Mental training
Aikido training is mental as well as physical, emphasizing the ability to relax the mind and body even under the stress of dangerous situations. This is necessary to enable the practitioner to perform the 'enter-and-blend' movements that underlie aikido techniques, wherein an attack is met with confidence and directness. Morihei Ueshiba once remarked that one "must be willing to receive 99% of an opponent's attack and stare death in the face" in order to execute techniques without hesitation. As a martial art concerned not only with fighting proficiency but with the betterment of daily life, this mental aspect is of key importance to aikido practitioners.
Uniforms and ranking
Aikido practitioners (commonly called outside Japan) generally progress by promotion through a series of "grades" (), followed by a series of "degrees" (), pursuant to formal testing procedures. Some aikido organizations use belts to distinguish practitioners' grades, often simply white and black belts to distinguish and grades, although some use various belt colors. Testing requirements vary, so a particular rank in one organization is not comparable or interchangeable with the rank of another. Some dōjōs have an age requirement before students can take the rank exam.
The uniform worn for practicing aikido () is similar to the training uniform () used in most other modern martial arts; simple trousers and a wraparound jacket, usually white. Both thi
use log::{debug, error, info, trace, warn, Level, LevelFilter, Log, Metadata, Record};
use std::sync::{Arc, Mutex};
#[cfg(feature = "std")]
use log::set_boxed_logger;
#[cfg(not(feature = "std"))]
fn set_boxed_logger(logger: Box) -> Result<(), log::SetLoggerError> {
log::set_logger(Box::leak(logger))
}
struct State {
last_log: Mutex