diff --git a/Code/irc/formatter.py b/Code/irc/formatter.py new file mode 100644 index 0000000..d438aca --- /dev/null +++ b/Code/irc/formatter.py @@ -0,0 +1,16 @@ +import time +import re + +def format_message(message): + pattern = r'^:.*\!~(.*)@.* (.*) (.*) :(.*)' + now = int(time.time()) + matches = re.match(pattern, message) + if not matches: + return '' + + nick = matches.group(1).strip() + command = matches.group(2).strip() + channel = matches.group(3).strip() + message = matches.group(4).strip() + + return "%s\t%s\t%s\t%s\t%s" % (now, nick, command, channel, message) diff --git a/Code/irc/formatter.pyc b/Code/irc/formatter.pyc new file mode 100644 index 0000000..48a929c Binary files /dev/null and b/Code/irc/formatter.pyc differ diff --git a/Code/irc/get_users.py b/Code/irc/get_users.py new file mode 100644 index 0000000..2b78b11 --- /dev/null +++ b/Code/irc/get_users.py @@ -0,0 +1,12 @@ +# Return a list of users on this system + +def get_users(): + # thanks, ~dan! + users = [] + with open("/etc/passwd", "r") as f: + for line in f: + if "/bin/bash" in line: + u = line.split(":")[0] # Grab all text before first ':' + users.append(u) + + return users \ No newline at end of file diff --git a/Code/irc/get_users.pyc b/Code/irc/get_users.pyc new file mode 100644 index 0000000..a422c78 Binary files /dev/null and b/Code/irc/get_users.pyc differ diff --git a/Code/irc/inflect.py b/Code/irc/inflect.py new file mode 100644 index 0000000..64382a2 --- /dev/null +++ b/Code/irc/inflect.py @@ -0,0 +1,3130 @@ +''' + inflect.py: correctly generate plurals, ordinals, indefinite articles; + convert numbers to words + Copyright (C) 2010 Paul Dyson + + Based upon the Perl module Lingua::EN::Inflect by Damian Conway. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + The original Perl module Lingua::EN::Inflect by Damian Conway is + available from http://search.cpan.org/~dconway/ + + This module can be downloaded at http://pypi.python.org/pypi/inflect + +methods: + classical inflect + plural plural_noun plural_verb plural_adj singular_noun no num a an + compare compare_nouns compare_verbs compare_adjs + present_participle + ordinal + number_to_words + join + defnoun defverb defadj defa defan + + INFLECTIONS: classical inflect + plural plural_noun plural_verb plural_adj singular_noun compare + no num a an present_participle + + PLURALS: classical inflect + plural plural_noun plural_verb plural_adj singular_noun no num + compare compare_nouns compare_verbs compare_adjs + + COMPARISONS: classical + compare compare_nouns compare_verbs compare_adjs + + ARTICLES: classical inflect num a an + + NUMERICAL: ordinal number_to_words + + USER_DEFINED: defnoun defverb defadj defa defan + +Exceptions: + UnknownClassicalModeError + BadNumValueError + BadChunkingOptionError + NumOutOfRangeError + BadUserDefinedPatternError + BadRcFileError + BadGenderError + +''' + +from re import match, search, subn, IGNORECASE, VERBOSE +from re import split as splitre +from re import error as reerror +from re import sub as resub + + +class UnknownClassicalModeError(Exception): + pass + + +class BadNumValueError(Exception): + pass + + +class BadChunkingOptionError(Exception): + pass + + +class NumOutOfRangeError(Exception): + pass + + +class BadUserDefinedPatternError(Exception): + pass + + +class BadRcFileError(Exception): + pass + + +class BadGenderError(Exception): + pass + +__ver_major__ = 0 +__ver_minor__ = 2 +__ver_patch__ = 4 +__ver_sub__ = "" +__version__ = "%d.%d.%d%s" % (__ver_major__, __ver_minor__, + __ver_patch__, __ver_sub__) + + +STDOUT_ON = False + + +def print3(txt): + if STDOUT_ON: + print(txt) + + +def enclose(s): + return "(?:%s)" % s + + +def joinstem(cutpoint=0, words=''): + ''' + join stem of each word in words into a string for regex + each word is truncated at cutpoint + cutpoint is usually negative indicating the number of letters to remove + from the end of each word + + e.g. + joinstem(-2, ["ephemeris", "iris", ".*itis"]) returns + (?:ephemer|ir|.*it) + + ''' + return enclose('|'.join(w[:cutpoint] for w in words)) + + +def bysize(words): + ''' + take a list of words and return a dict of sets sorted by word length + e.g. + ret[3]=set(['ant', 'cat', 'dog', 'pig']) + ret[4]=set(['frog', 'goat']) + ret[5]=set(['horse']) + ret[8]=set(['elephant']) + ''' + ret = {} + for w in words: + if len(w) not in ret: + ret[len(w)] = set() + ret[len(w)].add(w) + return ret + + +def make_pl_si_lists(lst, plending, siendingsize, dojoinstem=True): + ''' + given a list of singular words: lst + an ending to append to make the plural: plending + the number of characters to remove from the singular before appending plending: siendingsize + a flag whether to create a joinstem: dojoinstem + + return: + a list of pluralised words: si_list (called si because this is what you need to + look for to make the singular) + the pluralised words as a dict of sets sorted by word length: si_bysize + the singular words as a dict of sets sorted by word length: pl_bysize + if dojoinstem is True: a regular expression that matches any of the stems: stem + ''' + if siendingsize is not None: + siendingsize = -siendingsize + si_list = [w[:siendingsize] + plending for w in lst] + pl_bysize = bysize(lst) + si_bysize = bysize(si_list) + if dojoinstem: + stem = joinstem(siendingsize, lst) + return si_list, si_bysize, pl_bysize, stem + else: + return si_list, si_bysize, pl_bysize + + +# 1. PLURALS + +pl_sb_irregular_s = { + "corpus": "corpuses|corpora", + "opus": "opuses|opera", + "genus": "genera", + "mythos": "mythoi", + "penis": "penises|penes", + "testis": "testes", + "atlas": "atlases|atlantes", + "yes": "yeses", +} + +pl_sb_irregular = { + "child": "children", + "brother": "brothers|brethren", + "loaf": "loaves", + "hoof": "hoofs|hooves", + "beef": "beefs|beeves", + "thief": "thiefs|thieves", + "money": "monies", + "mongoose": "mongooses", + "ox": "oxen", + "cow": "cows|kine", + "graffito": "graffiti", + "octopus": "octopuses|octopodes", + "genie": "genies|genii", + "ganglion": "ganglions|ganglia", + "trilby": "trilbys", + "turf": "turfs|turves", + "numen": "numina", + "atman": "atmas", + "occiput": "occiputs|occipita", + "sabretooth": "sabretooths", + "sabertooth": "sabertooths", + "lowlife": "lowlifes", + "flatfoot": "flatfoots", + "tenderfoot": "tenderfoots", + "romany": "romanies", + "jerry": "jerries", + "mary": "maries", + "talouse": "talouses", + "blouse": "blouses", + "rom": "roma", + "carmen": "carmina", +} + +pl_sb_irregular.update(pl_sb_irregular_s) +# pl_sb_irregular_keys = enclose('|'.join(pl_sb_irregular.keys())) + +pl_sb_irregular_caps = { + 'Romany': 'Romanies', + 'Jerry': 'Jerrys', + 'Mary': 'Marys', + 'Rom': 'Roma', +} + +pl_sb_irregular_compound = { + "prima donna": "prima donnas|prime donne", +} + +si_sb_irregular = dict([(v, k) for (k, v) in pl_sb_irregular.items()]) +keys = list(si_sb_irregular.keys()) +for k in keys: + if '|' in k: + k1, k2 = k.split('|') + si_sb_irregular[k1] = si_sb_irregular[k2] = si_sb_irregular[k] + del si_sb_irregular[k] +si_sb_irregular_caps = dict([(v, k) for (k, v) in pl_sb_irregular_caps.items()]) +si_sb_irregular_compound = dict([(v, k) for (k, v) in pl_sb_irregular_compound.items()]) +keys = list(si_sb_irregular_compound.keys()) +for k in keys: + if '|' in k: + k1, k2 = k.split('|') + si_sb_irregular_compound[k1] = si_sb_irregular_compound[k2] = si_sb_irregular_compound[k] + del si_sb_irregular_compound[k] + +# si_sb_irregular_keys = enclose('|'.join(si_sb_irregular.keys())) + +# Z's that don't double + +pl_sb_z_zes_list = ( + "quartz", "topaz", +) +pl_sb_z_zes_bysize = bysize(pl_sb_z_zes_list) + +pl_sb_ze_zes_list = ('snooze',) +pl_sb_ze_zes_bysize = bysize(pl_sb_ze_zes_list) + + +# CLASSICAL "..is" -> "..ides" + +pl_sb_C_is_ides_complete = [ + # GENERAL WORDS... + "ephemeris", "iris", "clitoris", + "chrysalis", "epididymis", +] + +pl_sb_C_is_ides_endings = [ + # INFLAMATIONS... + "itis", +] + +pl_sb_C_is_ides = joinstem(-2, pl_sb_C_is_ides_complete + ['.*%s' % w for w in pl_sb_C_is_ides_endings]) + +pl_sb_C_is_ides_list = pl_sb_C_is_ides_complete + pl_sb_C_is_ides_endings + +(si_sb_C_is_ides_list, si_sb_C_is_ides_bysize, + pl_sb_C_is_ides_bysize) = make_pl_si_lists(pl_sb_C_is_ides_list, 'ides', 2, dojoinstem=False) + + +# CLASSICAL "..a" -> "..ata" + +pl_sb_C_a_ata_list = ( + "anathema", "bema", "carcinoma", "charisma", "diploma", + "dogma", "drama", "edema", "enema", "enigma", "lemma", + "lymphoma", "magma", "melisma", "miasma", "oedema", + "sarcoma", "schema", "soma", "stigma", "stoma", "trauma", + "gumma", "pragma", +) + +(si_sb_C_a_ata_list, si_sb_C_a_ata_bysize, + pl_sb_C_a_ata_bysize, pl_sb_C_a_ata) = make_pl_si_lists(pl_sb_C_a_ata_list, 'ata', 1) + +# UNCONDITIONAL "..a" -> "..ae" + +pl_sb_U_a_ae_list = ( + "alumna", "alga", "vertebra", "persona" +) +(si_sb_U_a_ae_list, si_sb_U_a_ae_bysize, + pl_sb_U_a_ae_bysize, pl_sb_U_a_ae) = make_pl_si_lists(pl_sb_U_a_ae_list, 'e', None) + +# CLASSICAL "..a" -> "..ae" + +pl_sb_C_a_ae_list = ( + "amoeba", "antenna", "formula", "hyperbola", + "medusa", "nebula", "parabola", "abscissa", + "hydra", "nova", "lacuna", "aurora", "umbra", + "flora", "fauna", +) +(si_sb_C_a_ae_list, si_sb_C_a_ae_bysize, + pl_sb_C_a_ae_bysize, pl_sb_C_a_ae) = make_pl_si_lists(pl_sb_C_a_ae_list, 'e', None) + + +# CLASSICAL "..en" -> "..ina" + +pl_sb_C_en_ina_list = ( + "stamen", "foramen", "lumen", +) + +(si_sb_C_en_ina_list, si_sb_C_en_ina_bysize, + pl_sb_C_en_ina_bysize, pl_sb_C_en_ina) = make_pl_si_lists(pl_sb_C_en_ina_list, 'ina', 2) + + +# UNCONDITIONAL "..um" -> "..a" + +pl_sb_U_um_a_list = ( + "bacterium", "agendum", "desideratum", "erratum", + "stratum", "datum", "ovum", "extremum", + "candelabrum", +) +(si_sb_U_um_a_list, si_sb_U_um_a_bysize, + pl_sb_U_um_a_bysize, pl_sb_U_um_a) = make_pl_si_lists(pl_sb_U_um_a_list, 'a', 2) + +# CLASSICAL "..um" -> "..a" + +pl_sb_C_um_a_list = ( + "maximum", "minimum", "momentum", "optimum", + "quantum", "cranium", "curriculum", "dictum", + "phylum", "aquarium", "compendium", "emporium", + "enconium", "gymnasium", "honorarium", "interregnum", + "lustrum", "memorandum", "millennium", "rostrum", + "spectrum", "speculum", "stadium", "trapezium", + "ultimatum", "medium", "vacuum", "velum", + "consortium", "arboretum", +) + +(si_sb_C_um_a_list, si_sb_C_um_a_bysize, + pl_sb_C_um_a_bysize, pl_sb_C_um_a) = make_pl_si_lists(pl_sb_C_um_a_list, 'a', 2) + + +# UNCONDITIONAL "..us" -> "i" + +pl_sb_U_us_i_list = ( + "alumnus", "alveolus", "bacillus", "bronchus", + "locus", "nucleus", "stimulus", "meniscus", + "sarcophagus", +) +(si_sb_U_us_i_list, si_sb_U_us_i_bysize, + pl_sb_U_us_i_bysize, pl_sb_U_us_i) = make_pl_si_lists(pl_sb_U_us_i_list, 'i', 2) + +# CLASSICAL "..us" -> "..i" + +pl_sb_C_us_i_list = ( + "focus", "radius", "genius", + "incubus", "succubus", "nimbus", + "fungus", "nucleolus", "stylus", + "torus", "umbilicus", "uterus", + "hippopotamus", "cactus", +) + +(si_sb_C_us_i_list, si_sb_C_us_i_bysize, + pl_sb_C_us_i_bysize, pl_sb_C_us_i) = make_pl_si_lists(pl_sb_C_us_i_list, 'i', 2) + + +# CLASSICAL "..us" -> "..us" (ASSIMILATED 4TH DECLENSION LATIN NOUNS) + +pl_sb_C_us_us = ( + "status", "apparatus", "prospectus", "sinus", + "hiatus", "impetus", "plexus", +) +pl_sb_C_us_us_bysize = bysize(pl_sb_C_us_us) + +# UNCONDITIONAL "..on" -> "a" + +pl_sb_U_on_a_list = ( + "criterion", "perihelion", "aphelion", + "phenomenon", "prolegomenon", "noumenon", + "organon", "asyndeton", "hyperbaton", +) +(si_sb_U_on_a_list, si_sb_U_on_a_bysize, + pl_sb_U_on_a_bysize, pl_sb_U_on_a) = make_pl_si_lists(pl_sb_U_on_a_list, 'a', 2) + +# CLASSICAL "..on" -> "..a" + +pl_sb_C_on_a_list = ( + "oxymoron", +) + +(si_sb_C_on_a_list, si_sb_C_on_a_bysize, + pl_sb_C_on_a_bysize, pl_sb_C_on_a) = make_pl_si_lists(pl_sb_C_on_a_list, 'a', 2) + + +# CLASSICAL "..o" -> "..i" (BUT NORMALLY -> "..os") + +pl_sb_C_o_i = [ + "solo", "soprano", "basso", "alto", + "contralto", "tempo", "piano", "virtuoso", +] # list not tuple so can concat for pl_sb_U_o_os + +pl_sb_C_o_i_bysize = bysize(pl_sb_C_o_i) +si_sb_C_o_i_bysize = bysize(['%si' % w[:-1] for w in pl_sb_C_o_i]) + +pl_sb_C_o_i_stems = joinstem(-1, pl_sb_C_o_i) + +# ALWAYS "..o" -> "..os" + +pl_sb_U_o_os_complete = set(( + "ado", "ISO", "NATO", "NCO", "NGO", "oto", +)) +si_sb_U_o_os_complete = set('%ss' % w for w in pl_sb_U_o_os_complete) + + +pl_sb_U_o_os_endings = [ + "aficionado", "aggro", + "albino", "allegro", "ammo", + "Antananarivo", "archipelago", "armadillo", + "auto", "avocado", "Bamako", + "Barquisimeto", "bimbo", "bingo", + "Biro", "bolero", "Bolzano", + "bongo", "Boto", "burro", + "Cairo", "canto", "cappuccino", + "casino", "cello", "Chicago", + "Chimango", "cilantro", "cochito", + "coco", "Colombo", "Colorado", + "commando", "concertino", "contango", + "credo", "crescendo", "cyano", + "demo", "ditto", "Draco", + "dynamo", "embryo", "Esperanto", + "espresso", "euro", "falsetto", + "Faro", "fiasco", "Filipino", + "flamenco", "furioso", "generalissimo", + "Gestapo", "ghetto", "gigolo", + "gizmo", "Greensboro", "gringo", + "Guaiabero", "guano", "gumbo", + "gyro", "hairdo", "hippo", + "Idaho", "impetigo", "inferno", + "info", "intermezzo", "intertrigo", + "Iquico", "jumbo", + "junto", "Kakapo", "kilo", + "Kinkimavo", "Kokako", "Kosovo", + "Lesotho", "libero", "libido", + "libretto", "lido", "Lilo", + "limbo", "limo", "lineno", + "lingo", "lino", "livedo", + "loco", "logo", "lumbago", + "macho", "macro", "mafioso", + "magneto", "magnifico", "Majuro", + "Malabo", "manifesto", "Maputo", + "Maracaibo", "medico", "memo", + "metro", "Mexico", "micro", + "Milano", "Monaco", "mono", + "Montenegro", "Morocco", "Muqdisho", + "myo", + "neutrino", "Ningbo", + "octavo", "oregano", "Orinoco", + "Orlando", "Oslo", + "panto", "Paramaribo", "Pardusco", + "pedalo", "photo", "pimento", + "pinto", "pleco", "Pluto", + "pogo", "polo", "poncho", + "Porto-Novo", "Porto", "pro", + "psycho", "pueblo", "quarto", + "Quito", "rhino", "risotto", + "rococo", "rondo", "Sacramento", + "saddo", "sago", "salvo", + "Santiago", "Sapporo", "Sarajevo", + "scherzando", "scherzo", "silo", + "sirocco", "sombrero", "staccato", + "sterno", "stucco", "stylo", + "sumo", "Taiko", "techno", + "terrazzo", "testudo", "timpano", + "tiro", "tobacco", "Togo", + "Tokyo", "torero", "Torino", + "Toronto", "torso", "tremolo", + "typo", "tyro", "ufo", + "UNESCO", "vaquero", "vermicello", + "verso", "vibrato", "violoncello", + "Virgo", "weirdo", "WHO", + "WTO", "Yamoussoukro", "yo-yo", + "zero", "Zibo", +] + pl_sb_C_o_i + +pl_sb_U_o_os_bysize = bysize(pl_sb_U_o_os_endings) +si_sb_U_o_os_bysize = bysize(['%ss' % w for w in pl_sb_U_o_os_endings]) + + +# UNCONDITIONAL "..ch" -> "..chs" + +pl_sb_U_ch_chs_list = ( + "czech", "eunuch", "stomach" +) + +(si_sb_U_ch_chs_list, si_sb_U_ch_chs_bysize, + pl_sb_U_ch_chs_bysize, pl_sb_U_ch_chs) = make_pl_si_lists(pl_sb_U_ch_chs_list, 's', None) + + +# UNCONDITIONAL "..[ei]x" -> "..ices" + +pl_sb_U_ex_ices_list = ( + "codex", "murex", "silex", +) +(si_sb_U_ex_ices_list, si_sb_U_ex_ices_bysize, + pl_sb_U_ex_ices_bysize, pl_sb_U_ex_ices) = make_pl_si_lists(pl_sb_U_ex_ices_list, 'ices', 2) + +pl_sb_U_ix_ices_list = ( + "radix", "helix", +) +(si_sb_U_ix_ices_list, si_sb_U_ix_ices_bysize, + pl_sb_U_ix_ices_bysize, pl_sb_U_ix_ices) = make_pl_si_lists(pl_sb_U_ix_ices_list, 'ices', 2) + +# CLASSICAL "..[ei]x" -> "..ices" + +pl_sb_C_ex_ices_list = ( + "vortex", "vertex", "cortex", "latex", + "pontifex", "apex", "index", "simplex", +) + +(si_sb_C_ex_ices_list, si_sb_C_ex_ices_bysize, + pl_sb_C_ex_ices_bysize, pl_sb_C_ex_ices) = make_pl_si_lists(pl_sb_C_ex_ices_list, 'ices', 2) + + +pl_sb_C_ix_ices_list = ( + "appendix", +) + +(si_sb_C_ix_ices_list, si_sb_C_ix_ices_bysize, + pl_sb_C_ix_ices_bysize, pl_sb_C_ix_ices) = make_pl_si_lists(pl_sb_C_ix_ices_list, 'ices', 2) + + +# ARABIC: ".." -> "..i" + +pl_sb_C_i_list = ( + "afrit", "afreet", "efreet", +) + +(si_sb_C_i_list, si_sb_C_i_bysize, + pl_sb_C_i_bysize, pl_sb_C_i) = make_pl_si_lists(pl_sb_C_i_list, 'i', None) + + +# HEBREW: ".." -> "..im" + +pl_sb_C_im_list = ( + "goy", "seraph", "cherub", +) + +(si_sb_C_im_list, si_sb_C_im_bysize, + pl_sb_C_im_bysize, pl_sb_C_im) = make_pl_si_lists(pl_sb_C_im_list, 'im', None) + + +# UNCONDITIONAL "..man" -> "..mans" + +pl_sb_U_man_mans_list = """ + ataman caiman cayman ceriman + desman dolman farman harman hetman + human leman ottoman shaman talisman +""".split() +pl_sb_U_man_mans_caps_list = """ + Alabaman Bahaman Burman German + Hiroshiman Liman Nakayaman Norman Oklahoman + Panaman Roman Selman Sonaman Tacoman Yakiman + Yokohaman Yuman +""".split() + +(si_sb_U_man_mans_list, si_sb_U_man_mans_bysize, + pl_sb_U_man_mans_bysize) = make_pl_si_lists(pl_sb_U_man_mans_list, 's', None, dojoinstem=False) +(si_sb_U_man_mans_caps_list, si_sb_U_man_mans_caps_bysize, + pl_sb_U_man_mans_caps_bysize) = make_pl_si_lists(pl_sb_U_man_mans_caps_list, 's', None, dojoinstem=False) + + +pl_sb_uninflected_s_complete = [ + # PAIRS OR GROUPS SUBSUMED TO A SINGULAR... + "breeches", "britches", "pajamas", "pyjamas", "clippers", "gallows", + "hijinks", "headquarters", "pliers", "scissors", "testes", "herpes", + "pincers", "shears", "proceedings", "trousers", + + # UNASSIMILATED LATIN 4th DECLENSION + + "cantus", "coitus", "nexus", + + # RECENT IMPORTS... + "contretemps", "corps", "debris", + "siemens", + + # DISEASES + "mumps", + + # MISCELLANEOUS OTHERS... + "diabetes", "jackanapes", "series", "species", "subspecies", "rabies", + "chassis", "innings", "news", "mews", "haggis", +] + +pl_sb_uninflected_s_endings = [ + # RECENT IMPORTS... + "ois", + + # DISEASES + "measles", +] + +pl_sb_uninflected_s = pl_sb_uninflected_s_complete + ['.*%s' % w for w in pl_sb_uninflected_s_endings] + +pl_sb_uninflected_herd = ( + # DON'T INFLECT IN CLASSICAL MODE, OTHERWISE NORMAL INFLECTION + "wildebeest", "swine", "eland", "bison", "buffalo", + "elk", "rhinoceros", 'zucchini', + 'caribou', 'dace', 'grouse', 'guinea fowl', 'guinea-fowl', + 'haddock', 'hake', 'halibut', 'herring', 'mackerel', + 'pickerel', 'pike', 'roe', 'seed', 'shad', + 'snipe', 'teal', 'turbot', 'water fowl', 'water-fowl', +) + +pl_sb_uninflected_complete = [ + # SOME FISH AND HERD ANIMALS + "tuna", "salmon", "mackerel", "trout", + "bream", "sea-bass", "sea bass", "carp", "cod", "flounder", "whiting", + "moose", + + # OTHER ODDITIES + "graffiti", "djinn", 'samuri', + 'offspring', 'pence', 'quid', 'hertz', +] + pl_sb_uninflected_s_complete +# SOME WORDS ENDING IN ...s (OFTEN PAIRS TAKEN AS A WHOLE) + +pl_sb_uninflected_caps = [ + # ALL NATIONALS ENDING IN -ese + "Portuguese", "Amoyese", "Borghese", "Congoese", "Faroese", + "Foochowese", "Genevese", "Genoese", "Gilbertese", "Hottentotese", + "Kiplingese", "Kongoese", "Lucchese", "Maltese", "Nankingese", + "Niasese", "Pekingese", "Piedmontese", "Pistoiese", "Sarawakese", + "Shavese", "Vermontese", "Wenchowese", "Yengeese", +] + + +pl_sb_uninflected_endings = [ + # SOME FISH AND HERD ANIMALS + "fish", + + "deer", "sheep", + + # ALL NATIONALS ENDING IN -ese + "nese", "rese", "lese", "mese", + + # DISEASES + "pox", + + + # OTHER ODDITIES + 'craft', +] + pl_sb_uninflected_s_endings +# SOME WORDS ENDING IN ...s (OFTEN PAIRS TAKEN AS A WHOLE) + + +pl_sb_uninflected_bysize = bysize(pl_sb_uninflected_endings) + + +# SINGULAR WORDS ENDING IN ...s (ALL INFLECT WITH ...es) + +pl_sb_singular_s_complete = [ + "acropolis", "aegis", "alias", "asbestos", "bathos", "bias", + "bronchitis", "bursitis", "caddis", "cannabis", + "canvas", "chaos", "cosmos", "dais", "digitalis", + "epidermis", "ethos", "eyas", "gas", "glottis", + "hubris", "ibis", "lens", "mantis", "marquis", "metropolis", + "pathos", "pelvis", "polis", "rhinoceros", + "sassafras", "trellis", +] + pl_sb_C_is_ides_complete + + +pl_sb_singular_s_endings = [ + "ss", "us", +] + pl_sb_C_is_ides_endings + +pl_sb_singular_s_bysize = bysize(pl_sb_singular_s_endings) + +si_sb_singular_s_complete = ['%ses' % w for w in pl_sb_singular_s_complete] +si_sb_singular_s_endings = ['%ses' % w for w in pl_sb_singular_s_endings] +si_sb_singular_s_bysize = bysize(si_sb_singular_s_endings) + +pl_sb_singular_s_es = [ + "[A-Z].*es", +] + +pl_sb_singular_s = enclose('|'.join(pl_sb_singular_s_complete + + ['.*%s' % w for w in pl_sb_singular_s_endings] + + pl_sb_singular_s_es)) + + +# PLURALS ENDING IN uses -> use + + +si_sb_ois_oi_case = ( + 'Bolshois', 'Hanois' +) + +si_sb_uses_use_case = ( + 'Betelgeuses', 'Duses', 'Meuses', 'Syracuses', 'Toulouses', +) + +si_sb_uses_use = ( + 'abuses', 'applauses', 'blouses', + 'carouses', 'causes', 'chartreuses', 'clauses', + 'contuses', 'douses', 'excuses', 'fuses', + 'grouses', 'hypotenuses', 'masseuses', + 'menopauses', 'misuses', 'muses', 'overuses', 'pauses', + 'peruses', 'profuses', 'recluses', 'reuses', + 'ruses', 'souses', 'spouses', 'suffuses', 'transfuses', 'uses', +) + +si_sb_ies_ie_case = ( + 'Addies', 'Aggies', 'Allies', 'Amies', 'Angies', 'Annies', + 'Annmaries', 'Archies', 'Arties', 'Aussies', 'Barbies', + 'Barries', 'Basies', 'Bennies', 'Bernies', 'Berties', 'Bessies', + 'Betties', 'Billies', 'Blondies', 'Bobbies', 'Bonnies', + 'Bowies', 'Brandies', 'Bries', 'Brownies', 'Callies', + 'Carnegies', 'Carries', 'Cassies', 'Charlies', 'Cheries', + 'Christies', 'Connies', 'Curies', 'Dannies', 'Debbies', 'Dixies', + 'Dollies', 'Donnies', 'Drambuies', 'Eddies', 'Effies', 'Ellies', + 'Elsies', 'Eries', 'Ernies', 'Essies', 'Eugenies', 'Fannies', + 'Flossies', 'Frankies', 'Freddies', 'Gillespies', 'Goldies', + 'Gracies', 'Guthries', 'Hallies', 'Hatties', 'Hetties', + 'Hollies', 'Jackies', 'Jamies', 'Janies', 'Jannies', 'Jeanies', + 'Jeannies', 'Jennies', 'Jessies', 'Jimmies', 'Jodies', 'Johnies', + 'Johnnies', 'Josies', 'Julies', 'Kalgoorlies', 'Kathies', 'Katies', + 'Kellies', 'Kewpies', 'Kristies', 'Laramies', 'Lassies', 'Lauries', + 'Leslies', 'Lessies', 'Lillies', 'Lizzies', 'Lonnies', 'Lories', + 'Lorries', 'Lotties', 'Louies', 'Mackenzies', 'Maggies', 'Maisies', + 'Mamies', 'Marcies', 'Margies', 'Maries', 'Marjories', 'Matties', + 'McKenzies', 'Melanies', 'Mickies', 'Millies', 'Minnies', 'Mollies', + 'Mounties', 'Nannies', 'Natalies', 'Nellies', 'Netties', 'Ollies', + 'Ozzies', 'Pearlies', 'Pottawatomies', 'Reggies', 'Richies', 'Rickies', + 'Robbies', 'Ronnies', 'Rosalies', 'Rosemaries', 'Rosies', 'Roxies', + 'Rushdies', 'Ruthies', 'Sadies', 'Sallies', 'Sammies', 'Scotties', + 'Selassies', 'Sherries', 'Sophies', 'Stacies', 'Stefanies', 'Stephanies', + 'Stevies', 'Susies', 'Sylvies', 'Tammies', 'Terries', 'Tessies', + 'Tommies', 'Tracies', 'Trekkies', 'Valaries', 'Valeries', 'Valkyries', + 'Vickies', 'Virgies', 'Willies', 'Winnies', 'Wylies', 'Yorkies', +) + +si_sb_ies_ie = ( + 'aeries', 'baggies', 'belies', 'biggies', 'birdies', 'bogies', + 'bonnies', 'boogies', 'bookies', 'bourgeoisies', 'brownies', + 'budgies', 'caddies', 'calories', 'camaraderies', 'cockamamies', + 'collies', 'cookies', 'coolies', 'cooties', 'coteries', 'crappies', + 'curies', 'cutesies', 'dogies', 'eyrie', 'floozies', 'footsies', + 'freebies', 'genies', 'goalies', 'groupies', + 'hies', 'jalousies', 'junkies', + 'kiddies', 'laddies', 'lassies', 'lies', + 'lingeries', 'magpies', 'menageries', 'mommies', 'movies', 'neckties', + 'newbies', 'nighties', 'oldies', 'organdies', 'overlies', + 'pies', 'pinkies', 'pixies', 'potpies', 'prairies', + 'quickies', 'reveries', 'rookies', 'rotisseries', 'softies', 'sorties', + 'species', 'stymies', 'sweeties', 'ties', 'underlies', 'unties', + 'veggies', 'vies', 'yuppies', 'zombies', +) + + +si_sb_oes_oe_case = ( + 'Chloes', 'Crusoes', 'Defoes', 'Faeroes', 'Ivanhoes', 'Joes', + 'McEnroes', 'Moes', 'Monroes', 'Noes', 'Poes', 'Roscoes', + 'Tahoes', 'Tippecanoes', 'Zoes', +) + +si_sb_oes_oe = ( + 'aloes', 'backhoes', 'canoes', + 'does', 'floes', 'foes', 'hoes', 'mistletoes', + 'oboes', 'pekoes', 'roes', 'sloes', + 'throes', 'tiptoes', 'toes', 'woes', +) + +si_sb_z_zes = ( + "quartzes", "topazes", +) + +si_sb_zzes_zz = ( + 'buzzes', 'fizzes', 'frizzes', 'razzes' +) + +si_sb_ches_che_case = ( + 'Andromaches', 'Apaches', 'Blanches', 'Comanches', + 'Nietzsches', 'Porsches', 'Roches', +) + +si_sb_ches_che = ( + 'aches', 'avalanches', 'backaches', 'bellyaches', 'caches', + 'cloches', 'creches', 'douches', 'earaches', 'fiches', + 'headaches', 'heartaches', 'microfiches', + 'niches', 'pastiches', 'psyches', 'quiches', + 'stomachaches', 'toothaches', +) + +si_sb_xes_xe = ( + 'annexes', 'axes', 'deluxes', 'pickaxes', +) + +si_sb_sses_sse_case = ( + 'Hesses', 'Jesses', 'Larousses', 'Matisses', +) +si_sb_sses_sse = ( + 'bouillabaisses', 'crevasses', 'demitasses', 'impasses', + 'mousses', 'posses', +) + +si_sb_ves_ve_case = ( + # *[nwl]ives -> [nwl]live + 'Clives', 'Palmolives', +) +si_sb_ves_ve = ( + # *[^d]eaves -> eave + 'interweaves', 'weaves', + + # *[nwl]ives -> [nwl]live + 'olives', + + # *[eoa]lves -> [eoa]lve + 'bivalves', 'dissolves', 'resolves', 'salves', 'twelves', 'valves', +) + + +plverb_special_s = enclose('|'.join( + [pl_sb_singular_s] + + pl_sb_uninflected_s + + list(pl_sb_irregular_s.keys()) + [ + '(.*[csx])is', + '(.*)ceps', + '[A-Z].*s', + ] +)) + +pl_sb_postfix_adj = { + 'general': ['(?!major|lieutenant|brigadier|adjutant|.*star)\S+'], + 'martial': ['court'], +} + +for k in list(pl_sb_postfix_adj.keys()): + pl_sb_postfix_adj[k] = enclose( + enclose('|'.join(pl_sb_postfix_adj[k])) + + "(?=(?:-|\\s+)%s)" % k) + +pl_sb_postfix_adj_stems = '(' + '|'.join(list(pl_sb_postfix_adj.values())) + ')(.*)' + + +# PLURAL WORDS ENDING IS es GO TO SINGULAR is + +si_sb_es_is = ( + 'amanuenses', 'amniocenteses', 'analyses', 'antitheses', + 'apotheoses', 'arterioscleroses', 'atheroscleroses', 'axes', + # 'bases', # bases -> basis + 'catalyses', 'catharses', 'chasses', 'cirrhoses', + 'cocces', 'crises', 'diagnoses', 'dialyses', 'diereses', + 'electrolyses', 'emphases', 'exegeses', 'geneses', + 'halitoses', 'hydrolyses', 'hypnoses', 'hypotheses', 'hystereses', + 'metamorphoses', 'metastases', 'misdiagnoses', 'mitoses', + 'mononucleoses', 'narcoses', 'necroses', 'nemeses', 'neuroses', + 'oases', 'osmoses', 'osteoporoses', 'paralyses', 'parentheses', + 'parthenogeneses', 'periphrases', 'photosyntheses', 'probosces', + 'prognoses', 'prophylaxes', 'prostheses', 'preces', 'psoriases', + 'psychoanalyses', 'psychokineses', 'psychoses', 'scleroses', + 'scolioses', 'sepses', 'silicoses', 'symbioses', 'synopses', + 'syntheses', 'taxes', 'telekineses', 'theses', 'thromboses', + 'tuberculoses', 'urinalyses', +) + +pl_prep_list = """ + about above across after among around at athwart before behind + below beneath beside besides between betwixt beyond but by + during except for from in into near of off on onto out over + since till to under until unto upon with""".split() + +pl_prep_list_da = pl_prep_list + ['de', 'du', 'da'] + +pl_prep_bysize = bysize(pl_prep_list_da) + +pl_prep = enclose('|'.join(pl_prep_list_da)) + +pl_sb_prep_dual_compound = r'(.*?)((?:-|\s+)(?:' + pl_prep + r')(?:-|\s+))a(?:-|\s+)(.*)' + + +singular_pronoun_genders = set(['neuter', + 'feminine', + 'masculine', + 'gender-neutral', + 'feminine or masculine', + 'masculine or feminine']) + +pl_pron_nom = { + # NOMINATIVE REFLEXIVE + "i": "we", "myself": "ourselves", + "you": "you", "yourself": "yourselves", + "she": "they", "herself": "themselves", + "he": "they", "himself": "themselves", + "it": "they", "itself": "themselves", + "they": "they", "themself": "themselves", + + # POSSESSIVE + "mine": "ours", + "yours": "yours", + "hers": "theirs", + "his": "theirs", + "its": "theirs", + "theirs": "theirs", +} + +si_pron = {} +si_pron['nom'] = dict([(v, k) for (k, v) in pl_pron_nom.items()]) +si_pron['nom']['we'] = 'I' + + +pl_pron_acc = { + # ACCUSATIVE REFLEXIVE + "me": "us", "myself": "ourselves", + "you": "you", "yourself": "yourselves", + "her": "them", "herself": "themselves", + "him": "them", "himself": "themselves", + "it": "them", "itself": "themselves", + "them": "them", "themself": "themselves", +} + +pl_pron_acc_keys = enclose('|'.join(list(pl_pron_acc.keys()))) +pl_pron_acc_keys_bysize = bysize(list(pl_pron_acc.keys())) + +si_pron['acc'] = dict([(v, k) for (k, v) in pl_pron_acc.items()]) + +for thecase, plur, gend, sing in ( + ('nom', 'they', 'neuter', 'it'), + ('nom', 'they', 'feminine', 'she'), + ('nom', 'they', 'masculine', 'he'), + ('nom', 'they', 'gender-neutral', 'they'), + ('nom', 'they', 'feminine or masculine', 'she or he'), + ('nom', 'they', 'masculine or feminine', 'he or she'), + ('nom', 'themselves', 'neuter', 'itself'), + ('nom', 'themselves', 'feminine', 'herself'), + ('nom', 'themselves', 'masculine', 'himself'), + ('nom', 'themselves', 'gender-neutral', 'themself'), + ('nom', 'themselves', 'feminine or masculine', 'herself or himself'), + ('nom', 'themselves', 'masculine or feminine', 'himself or herself'), + ('nom', 'theirs', 'neuter', 'its'), + ('nom', 'theirs', 'feminine', 'hers'), + ('nom', 'theirs', 'masculine', 'his'), + ('nom', 'theirs', 'gender-neutral', 'theirs'), + ('nom', 'theirs', 'feminine or masculine', 'hers or his'), + ('nom', 'theirs', 'masculine or feminine', 'his or hers'), + ('acc', 'them', 'neuter', 'it'), + ('acc', 'them', 'feminine', 'her'), + ('acc', 'them', 'masculine', 'him'), + ('acc', 'them', 'gender-neutral', 'them'), + ('acc', 'them', 'feminine or masculine', 'her or him'), + ('acc', 'them', 'masculine or feminine', 'him or her'), + ('acc', 'themselves', 'neuter', 'itself'), + ('acc', 'themselves', 'feminine', 'herself'), + ('acc', 'themselves', 'masculine', 'himself'), + ('acc', 'themselves', 'gender-neutral', 'themself'), + ('acc', 'themselves', 'feminine or masculine', 'herself or himself'), + ('acc', 'themselves', 'masculine or feminine', 'himself or herself'), +): + try: + si_pron[thecase][plur][gend] = sing + except TypeError: + si_pron[thecase][plur] = {} + si_pron[thecase][plur][gend] = sing + + +si_pron_acc_keys = enclose('|'.join(list(si_pron['acc'].keys()))) +si_pron_acc_keys_bysize = bysize(list(si_pron['acc'].keys())) + + +def get_si_pron(thecase, word, gender): + try: + sing = si_pron[thecase][word] + except KeyError: + raise # not a pronoun + try: + return sing[gender] # has several types due to gender + except TypeError: + return sing # answer independent of gender + +plverb_irregular_pres = { + # 1st PERS. SING. 2ND PERS. SING. 3RD PERS. SINGULAR + # 3RD PERS. (INDET.) + "am": "are", "are": "are", "is": "are", + "was": "were", "were": "were", "was": "were", + "have": "have", "have": "have", "has": "have", + "do": "do", "do": "do", "does": "do", +} + +plverb_ambiguous_pres = { + # 1st PERS. SING. 2ND PERS. SING. 3RD PERS. SINGULAR + # 3RD PERS. (INDET.) + "act": "act", "act": "act", "acts": "act", + "blame": "blame", "blame": "blame", "blames": "blame", + "can": "can", "can": "can", "can": "can", + "must": "must", "must": "must", "must": "must", + "fly": "fly", "fly": "fly", "flies": "fly", + "copy": "copy", "copy": "copy", "copies": "copy", + "drink": "drink", "drink": "drink", "drinks": "drink", + "fight": "fight", "fight": "fight", "fights": "fight", + "fire": "fire", "fire": "fire", "fires": "fire", + "like": "like", "like": "like", "likes": "like", + "look": "look", "look": "look", "looks": "look", + "make": "make", "make": "make", "makes": "make", + "reach": "reach", "reach": "reach", "reaches": "reach", + "run": "run", "run": "run", "runs": "run", + "sink": "sink", "sink": "sink", "sinks": "sink", + "sleep": "sleep", "sleep": "sleep", "sleeps": "sleep", + "view": "view", "view": "view", "views": "view", +} + +plverb_ambiguous_pres_keys = enclose('|'.join(list(plverb_ambiguous_pres.keys()))) + + +plverb_irregular_non_pres = ( + "did", "had", "ate", "made", "put", + "spent", "fought", "sank", "gave", "sought", + "shall", "could", "ought", "should", +) + +plverb_ambiguous_non_pres = enclose('|'.join(( + "thought", "saw", "bent", "will", "might", "cut", +))) + +# "..oes" -> "..oe" (the rest are "..oes" -> "o") + +pl_v_oes_oe = ('canoes', 'floes', 'oboes', 'roes', 'throes', 'woes') +pl_v_oes_oe_endings_size4 = ('hoes', 'toes') +pl_v_oes_oe_endings_size5 = ('shoes') + + +pl_count_zero = ( + "0", "no", "zero", "nil" +) + + +pl_count_one = ( + "1", "a", "an", "one", "each", "every", "this", "that", +) + +pl_adj_special = { + "a": "some", "an": "some", + "this": "these", "that": "those", +} + +pl_adj_special_keys = enclose('|'.join(list(pl_adj_special.keys()))) + +pl_adj_poss = { + "my": "our", + "your": "your", + "its": "their", + "her": "their", + "his": "their", + "their": "their", +} + +pl_adj_poss_keys = enclose('|'.join(list(pl_adj_poss.keys()))) + + +# 2. INDEFINITE ARTICLES + +# THIS PATTERN MATCHES STRINGS OF CAPITALS STARTING WITH A "VOWEL-SOUND" +# CONSONANT FOLLOWED BY ANOTHER CONSONANT, AND WHICH ARE NOT LIKELY +# TO BE REAL WORDS (OH, ALL RIGHT THEN, IT'S JUST MAGIC!) + +A_abbrev = r""" +(?! FJO | [HLMNS]Y. | RY[EO] | SQU + | ( F[LR]? | [HL] | MN? | N | RH? | S[CHKLMNPTVW]? | X(YL)?) [AEIOU]) +[FHLMNRSX][A-Z] +""" + +# THIS PATTERN CODES THE BEGINNINGS OF ALL ENGLISH WORDS BEGINING WITH A +# 'y' FOLLOWED BY A CONSONANT. ANY OTHER Y-CONSONANT PREFIX THEREFORE +# IMPLIES AN ABBREVIATION. + +A_y_cons = 'y(b[lor]|cl[ea]|fere|gg|p[ios]|rou|tt)' + +# EXCEPTIONS TO EXCEPTIONS + +A_explicit_a = enclose('|'.join(( + "unabomber", "unanimous", "US", +))) + +A_explicit_an = enclose('|'.join(( + "euler", + "hour(?!i)", "heir", "honest", "hono[ur]", + "mpeg", +))) + +A_ordinal_an = enclose('|'.join(( + "[aefhilmnorsx]-?th", +))) + +A_ordinal_a = enclose('|'.join(( + "[bcdgjkpqtuvwyz]-?th", +))) + + +# NUMERICAL INFLECTIONS + +nth = { + 0: 'th', + 1: 'st', + 2: 'nd', + 3: 'rd', + 4: 'th', + 5: 'th', + 6: 'th', + 7: 'th', + 8: 'th', + 9: 'th', + 11: 'th', + 12: 'th', + 13: 'th', +} + +ordinal = dict(ty='tieth', + one='first', + two='second', + three='third', + five='fifth', + eight='eighth', + nine='ninth', + twelve='twelfth') + +ordinal_suff = '|'.join(list(ordinal.keys())) + + +# NUMBERS + +unit = ['', 'one', 'two', 'three', 'four', 'five', + 'six', 'seven', 'eight', 'nine'] +teen = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', + 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] +ten = ['', '', 'twenty', 'thirty', 'forty', + 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] +mill = [' ', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', + ' quintillion', ' sextillion', ' septillion', ' octillion', + ' nonillion', ' decillion'] + + +# SUPPORT CLASSICAL PLURALIZATIONS + +def_classical = dict( + all=False, + zero=False, + herd=False, + names=True, + persons=False, + ancient=False, +) + +all_classical = dict((k, True) for k in list(def_classical.keys())) +no_classical = dict((k, False) for k in list(def_classical.keys())) + + +# TODO: .inflectrc file does not work +# can't just execute methods from another file like this + +# for rcfile in (pathjoin(dirname(__file__), '.inflectrc'), +# expanduser(pathjoin(('~'), '.inflectrc'))): +# if isfile(rcfile): +# try: +# execfile(rcfile) +# except: +# print3("\nBad .inflectrc file (%s):\n" % rcfile) +# raise BadRcFileError + + +class engine: + + def __init__(self): + + self.classical_dict = def_classical.copy() + self.persistent_count = None + self.mill_count = 0 + self.pl_sb_user_defined = [] + self.pl_v_user_defined = [] + self.pl_adj_user_defined = [] + self.si_sb_user_defined = [] + self.A_a_user_defined = [] + self.thegender = 'neuter' + + deprecated_methods = dict(pl='plural', + plnoun='plural_noun', + plverb='plural_verb', + pladj='plural_adj', + sinoun='single_noun', + prespart='present_participle', + numwords='number_to_words', + plequal='compare', + plnounequal='compare_nouns', + plverbequal='compare_verbs', + pladjequal='compare_adjs', + wordlist='join', + ) + + def __getattr__(self, meth): + if meth in self.deprecated_methods: + print3('%s() deprecated, use %s()' % (meth, self.deprecated_methods[meth])) + raise DeprecationWarning + raise AttributeError + + def defnoun(self, singular, plural): + ''' + Set the noun plural of singular to plural. + + ''' + self.checkpat(singular) + self.checkpatplural(plural) + self.pl_sb_user_defined.extend((singular, plural)) + self.si_sb_user_defined.extend((plural, singular)) + return 1 + + def defverb(self, s1, p1, s2, p2, s3, p3): + ''' + Set the verb plurals for s1, s2 and s3 to p1, p2 and p3 respectively. + + Where 1, 2 and 3 represent the 1st, 2nd and 3rd person forms of the verb. + + ''' + self.checkpat(s1) + self.checkpat(s2) + self.checkpat(s3) + self.checkpatplural(p1) + self.checkpatplural(p2) + self.checkpatplural(p3) + self.pl_v_user_defined.extend((s1, p1, s2, p2, s3, p3)) + return 1 + + def defadj(self, singular, plural): + ''' + Set the adjective plural of singular to plural. + + ''' + self.checkpat(singular) + self.checkpatplural(plural) + self.pl_adj_user_defined.extend((singular, plural)) + return 1 + + def defa(self, pattern): + ''' + Define the indefinate article as 'a' for words matching pattern. + + ''' + self.checkpat(pattern) + self.A_a_user_defined.extend((pattern, 'a')) + return 1 + + def defan(self, pattern): + ''' + Define the indefinate article as 'an' for words matching pattern. + + ''' + self.checkpat(pattern) + self.A_a_user_defined.extend((pattern, 'an')) + return 1 + + def checkpat(self, pattern): + ''' + check for errors in a regex pattern + ''' + if pattern is None: + return + try: + match(pattern, '') + except reerror: + print3("\nBad user-defined singular pattern:\n\t%s\n" % pattern) + raise BadUserDefinedPatternError + + def checkpatplural(self, pattern): + ''' + check for errors in a regex replace pattern + ''' + return + # can't find a pattern that doesn't pass the following test: + # if pattern is None: + # return + # try: + # resub('', pattern, '') + # except reerror: + # print3("\nBad user-defined plural pattern:\n\t%s\n" % pattern) + # raise BadUserDefinedPatternError + + def ud_match(self, word, wordlist): + for i in range(len(wordlist) - 2, -2, -2): # backwards through even elements + mo = search(r'^%s$' % wordlist[i], word, IGNORECASE) + if mo: + if wordlist[i + 1] is None: + return None + pl = resub(r'\$(\d+)', r'\\1', wordlist[i + 1]) # change $n to \n for expand + return mo.expand(pl) + return None + + def classical(self, **kwargs): + """ + turn classical mode on and off for various categories + + turn on all classical modes: + classical() + classical(all=True) + + turn on or off specific claassical modes: + e.g. + classical(herd=True) + classical(names=False) + + By default all classical modes are off except names. + + unknown value in args or key in kwargs rasies exception: UnknownClasicalModeError + + """ + classical_mode = list(def_classical.keys()) + if not kwargs: + self.classical_dict = all_classical.copy() + return + if 'all' in kwargs: + if kwargs['all']: + self.classical_dict = all_classical.copy() + else: + self.classical_dict = no_classical.copy() + + for k, v in list(kwargs.items()): + if k in classical_mode: + self.classical_dict[k] = v + else: + raise UnknownClassicalModeError + + def num(self, count=None, show=None): # (;$count,$show) + ''' + Set the number to be used in other method calls. + + Returns count. + + Set show to False to return '' instead. + + ''' + if count is not None: + try: + self.persistent_count = int(count) + except ValueError: + raise BadNumValueError + if (show is None) or show: + return str(count) + else: + self.persistent_count = None + return '' + + def gender(self, gender): + ''' + set the gender for the singular of plural pronouns + + can be one of: + 'neuter' ('they' -> 'it') + 'feminine' ('they' -> 'she') + 'masculine' ('they' -> 'he') + 'gender-neutral' ('they' -> 'they') + 'feminine or masculine' ('they' -> 'she or he') + 'masculine or feminine' ('they' -> 'he or she') + ''' + if gender in singular_pronoun_genders: + self.thegender = gender + else: + raise BadGenderError + + def nummo(self, matchobject): + ''' + num but take a matchobject + use groups 1 and 2 in matchobject + ''' + return self.num(matchobject.group(1), matchobject.group(2)) + + def plmo(self, matchobject): + ''' + plural but take a matchobject + use groups 1 and 3 in matchobject + ''' + return self.plural(matchobject.group(1), matchobject.group(3)) + + def plnounmo(self, matchobject): + ''' + plural_noun but take a matchobject + use groups 1 and 3 in matchobject + ''' + return self.plural_noun(matchobject.group(1), matchobject.group(3)) + + def plverbmo(self, matchobject): + ''' + plural_verb but take a matchobject + use groups 1 and 3 in matchobject + ''' + return self.plural_verb(matchobject.group(1), matchobject.group(3)) + + def pladjmo(self, matchobject): + ''' + plural_adj but take a matchobject + use groups 1 and 3 in matchobject + ''' + return self.plural_adj(matchobject.group(1), matchobject.group(3)) + + def sinounmo(self, matchobject): + ''' + singular_noun but take a matchobject + use groups 1 and 3 in matchobject + ''' + return self.singular_noun(matchobject.group(1), matchobject.group(3)) + + def amo(self, matchobject): + ''' + A but take a matchobject + use groups 1 and 3 in matchobject + ''' + if matchobject.group(3) is None: + return self.a(matchobject.group(1)) + return self.a(matchobject.group(1), matchobject.group(3)) + + def nomo(self, matchobject): + ''' + NO but take a matchobject + use groups 1 and 3 in matchobject + ''' + return self.no(matchobject.group(1), matchobject.group(3)) + + def ordinalmo(self, matchobject): + ''' + ordinal but take a matchobject + use group 1 + ''' + return self.ordinal(matchobject.group(1)) + + def numwordsmo(self, matchobject): + ''' + number_to_words but take a matchobject + use group 1 + ''' + return self.number_to_words(matchobject.group(1)) + + def prespartmo(self, matchobject): + ''' + prespart but take a matchobject + use group 1 + ''' + return self.present_participle(matchobject.group(1)) + +# 0. PERFORM GENERAL INFLECTIONS IN A STRING + + def inflect(self, text): + ''' + Perform inflections in a string. + + e.g. inflect('The plural of cat is plural(cat)') returns + 'The plural of cat is cats' + + can use plural, plural_noun, plural_verb, plural_adj, singular_noun, a, an, no, ordinal, + number_to_words and prespart + + ''' + save_persistent_count = self.persistent_count + sections = splitre(r"(num\([^)]*\))", text) + inflection = [] + + for section in sections: + (section, count) = subn(r"num\(\s*?(?:([^),]*)(?:,([^)]*))?)?\)", self.nummo, section) + if not count: + total = -1 + while total: + (section, total) = subn( + r"(?x)\bplural \( ([^),]*) (, ([^)]*) )? \) ", + self.plmo, section) + (section, count) = subn( + r"(?x)\bplural_noun \( ([^),]*) (, ([^)]*) )? \) ", + self.plnounmo, section) + total += count + (section, count) = subn( + r"(?x)\bplural_verb \( ([^),]*) (, ([^)]*) )? \) ", + self.plverbmo, section) + total += count + (section, count) = subn( + r"(?x)\bplural_adj \( ([^),]*) (, ([^)]*) )? \) ", + self.pladjmo, section) + total += count + (section, count) = subn( + r"(?x)\bsingular_noun \( ([^),]*) (, ([^)]*) )? \) ", + self.sinounmo, section) + total += count + (section, count) = subn( + r"(?x)\ban? \( ([^),]*) (, ([^)]*) )? \) ", + self.amo, section) + total += count + (section, count) = subn( + r"(?x)\bno \( ([^),]*) (, ([^)]*) )? \) ", + self.nomo, section) + total += count + (section, count) = subn( + r"(?x)\bordinal \( ([^)]*) \) ", + self.ordinalmo, section) + total += count + (section, count) = subn( + r"(?x)\bnumber_to_words \( ([^)]*) \) ", + self.numwordsmo, section) + total += count + (section, count) = subn( + r"(?x)\bpresent_participle \( ([^)]*) \) ", + self.prespartmo, section) + total += count + + inflection.append(section) + + self.persistent_count = save_persistent_count + return "".join(inflection) + +# ## PLURAL SUBROUTINES + + def postprocess(self, orig, inflected): + """ + FIX PEDANTRY AND CAPITALIZATION :-) + """ + if '|' in inflected: + inflected = inflected.split('|')[self.classical_dict['all']] + if orig == "I": + return inflected + if orig == orig.upper(): + return inflected.upper() + if orig[0] == orig[0].upper(): + return '%s%s' % (inflected[0].upper(), + inflected[1:]) + return inflected + + def partition_word(self, text): + mo = search(r'\A(\s*)(.+?)(\s*)\Z', text) + try: + return mo.group(1), mo.group(2), mo.group(3) + except AttributeError: # empty string + return '', '', '' + +# def pl(self, *args, **kwds): +# print 'pl() deprecated, use plural()' +# raise DeprecationWarning +# return self.plural(*args, **kwds) +# +# def plnoun(self, *args, **kwds): +# print 'plnoun() deprecated, use plural_noun()' +# raise DeprecationWarning +# return self.plural_noun(*args, **kwds) +# +# def plverb(self, *args, **kwds): +# print 'plverb() deprecated, use plural_verb()' +# raise DeprecationWarning +# return self.plural_verb(*args, **kwds) +# +# def pladj(self, *args, **kwds): +# print 'pladj() deprecated, use plural_adj()' +# raise DeprecationWarning +# return self.plural_adj(*args, **kwds) +# +# def sinoun(self, *args, **kwds): +# print 'sinoun() deprecated, use singular_noun()' +# raise DeprecationWarning +# return self.singular_noun(*args, **kwds) +# +# def prespart(self, *args, **kwds): +# print 'prespart() deprecated, use present_participle()' +# raise DeprecationWarning +# return self.present_participle(*args, **kwds) +# +# def numwords(self, *args, **kwds): +# print 'numwords() deprecated, use number_to_words()' +# raise DeprecationWarning +# return self.number_to_words(*args, **kwds) + + def plural(self, text, count=None): + ''' + Return the plural of text. + + If count supplied, then return text if count is one of: + 1, a, an, one, each, every, this, that + otherwise return the plural. + + Whitespace at the start and end is preserved. + + ''' + pre, word, post = self.partition_word(text) + if not word: + return text + plural = self.postprocess( + word, + self._pl_special_adjective(word, count) or + self._pl_special_verb(word, count) or + self._plnoun(word, count)) + return "%s%s%s" % (pre, plural, post) + + def plural_noun(self, text, count=None): + ''' + Return the plural of text, where text is a noun. + + If count supplied, then return text if count is one of: + 1, a, an, one, each, every, this, that + otherwise return the plural. + + Whitespace at the start and end is preserved. + + ''' + pre, word, post = self.partition_word(text) + if not word: + return text + plural = self.postprocess(word, self._plnoun(word, count)) + return "%s%s%s" % (pre, plural, post) + + def plural_verb(self, text, count=None): + ''' + Return the plural of text, where text is a verb. + + If count supplied, then return text if count is one of: + 1, a, an, one, each, every, this, that + otherwise return the plural. + + Whitespace at the start and end is preserved. + + ''' + pre, word, post = self.partition_word(text) + if not word: + return text + plural = self.postprocess(word, self._pl_special_verb(word, count) or + self._pl_general_verb(word, count)) + return "%s%s%s" % (pre, plural, post) + + def plural_adj(self, text, count=None): + ''' + Return the plural of text, where text is an adjective. + + If count supplied, then return text if count is one of: + 1, a, an, one, each, every, this, that + otherwise return the plural. + + Whitespace at the start and end is preserved. + + ''' + pre, word, post = self.partition_word(text) + if not word: + return text + plural = self.postprocess(word, self._pl_special_adjective(word, count) or word) + return "%s%s%s" % (pre, plural, post) + + def compare(self, word1, word2): + ''' + compare word1 and word2 for equality regardless of plurality + + return values: + eq - the strings are equal + p:s - word1 is the plural of word2 + s:p - word2 is the plural of word1 + p:p - word1 and word2 are two different plural forms of the one word + False - otherwise + + ''' + return ( + self._plequal(word1, word2, self.plural_noun) or + self._plequal(word1, word2, self.plural_verb) or + self._plequal(word1, word2, self.plural_adj)) + + def compare_nouns(self, word1, word2): + ''' + compare word1 and word2 for equality regardless of plurality + word1 and word2 are to be treated as nouns + + return values: + eq - the strings are equal + p:s - word1 is the plural of word2 + s:p - word2 is the plural of word1 + p:p - word1 and word2 are two different plural forms of the one word + False - otherwise + + ''' + return self._plequal(word1, word2, self.plural_noun) + + def compare_verbs(self, word1, word2): + ''' + compare word1 and word2 for equality regardless of plurality + word1 and word2 are to be treated as verbs + + return values: + eq - the strings are equal + p:s - word1 is the plural of word2 + s:p - word2 is the plural of word1 + p:p - word1 and word2 are two different plural forms of the one word + False - otherwise + + ''' + return self._plequal(word1, word2, self.plural_verb) + + def compare_adjs(self, word1, word2): + ''' + compare word1 and word2 for equality regardless of plurality + word1 and word2 are to be treated as adjectives + + return values: + eq - the strings are equal + p:s - word1 is the plural of word2 + s:p - word2 is the plural of word1 + p:p - word1 and word2 are two different plural forms of the one word + False - otherwise + + ''' + return self._plequal(word1, word2, self.plural_adj) + + def singular_noun(self, text, count=None, gender=None): + ''' + Return the singular of text, where text is a plural noun. + + If count supplied, then return the singular if count is one of: + 1, a, an, one, each, every, this, that or if count is None + otherwise return text unchanged. + + Whitespace at the start and end is preserved. + + ''' + pre, word, post = self.partition_word(text) + if not word: + return text + sing = self._sinoun(word, count=count, gender=gender) + if sing is not False: + plural = self.postprocess(word, self._sinoun(word, count=count, gender=gender)) + return "%s%s%s" % (pre, plural, post) + return False + + def _plequal(self, word1, word2, pl): + classval = self.classical_dict.copy() + self.classical_dict = all_classical.copy() + if word1 == word2: + return "eq" + if word1 == pl(word2): + return "p:s" + if pl(word1) == word2: + return "s:p" + self.classical_dict = no_classical.copy() + if word1 == pl(word2): + return "p:s" + if pl(word1) == word2: + return "s:p" + self.classical_dict = classval.copy() + + if pl == self.plural or pl == self.plural_noun: + if self._pl_check_plurals_N(word1, word2): + return "p:p" + if self._pl_check_plurals_N(word2, word1): + return "p:p" + if pl == self.plural or pl == self.plural_adj: + if self._pl_check_plurals_adj(word1, word2): + return "p:p" + return False + + def _pl_reg_plurals(self, pair, stems, end1, end2): + if search(r"(%s)(%s\|\1%s|%s\|\1%s)" % (stems, end1, end2, end2, end1), pair): + return True + return False + + def _pl_check_plurals_N(self, word1, word2): + pair = "%s|%s" % (word1, word2) + if pair in list(pl_sb_irregular_s.values()): + return True + if pair in list(pl_sb_irregular.values()): + return True + if pair in list(pl_sb_irregular_caps.values()): + return True + + for (stems, end1, end2) in ( + (pl_sb_C_a_ata, "as", "ata"), + (pl_sb_C_is_ides, "is", "ides"), + (pl_sb_C_a_ae, "s", "e"), + (pl_sb_C_en_ina, "ens", "ina"), + (pl_sb_C_um_a, "ums", "a"), + (pl_sb_C_us_i, "uses", "i"), + (pl_sb_C_on_a, "ons", "a"), + (pl_sb_C_o_i_stems, "os", "i"), + (pl_sb_C_ex_ices, "exes", "ices"), + (pl_sb_C_ix_ices, "ixes", "ices"), + (pl_sb_C_i, "s", "i"), + (pl_sb_C_im, "s", "im"), + ('.*eau', "s", "x"), + ('.*ieu', "s", "x"), + ('.*tri', "xes", "ces"), + ('.{2,}[yia]n', "xes", "ges") + ): + if self._pl_reg_plurals(pair, stems, end1, end2): + return True + return False + + def _pl_check_plurals_adj(self, word1, word2): +# VERSION: tuple in endswith requires python 2.5 + word1a = word1[:word1.rfind("'")] if word1.endswith(("'s", "'")) else '' + word2a = word2[:word2.rfind("'")] if word2.endswith(("'s", "'")) else '' + # TODO: BUG? report upstream. I don't think you should chop off the s' + # word1b = word1[:-2] if word1.endswith("s'") else '' + # word2b = word2[:-2] if word2.endswith("s'") else '' + + # TODO: dresses', dresses's -> dresses, dresses when chop off letters + # then they return False because they are the same. Need to fix this. + + if word1a: + if word2a and (self._pl_check_plurals_N(word1a, word2a) + or self._pl_check_plurals_N(word2a, word1a)): + return True + # if word2b and ( self._pl_check_plurals_N(word1a, word2b) + # or self._pl_check_plurals_N(word2b, word1a) ): + # return True + + # if word1b: + # if word2a and ( self._pl_check_plurals_N(word1b, word2a) + # or self._pl_check_plurals_N(word2a, word1b) ): + # return True + # if word2b and ( self._pl_check_plurals_N(word1b, word2b) + # or self._pl_check_plurals_N(word2b, word1b) ): + # return True + + return False + + def get_count(self, count=None): + if count is None and self.persistent_count is not None: + count = self.persistent_count + + if count is not None: + count = 1 if ((str(count) in pl_count_one) or + (self.classical_dict['zero'] and str(count).lower() in pl_count_zero)) else 2 + else: + count = '' + return count + + # @profile + def _plnoun(self, word, count=None): + count = self.get_count(count) + +# DEFAULT TO PLURAL + + if count == 1: + return word + +# HANDLE USER-DEFINED NOUNS + + value = self.ud_match(word, self.pl_sb_user_defined) + if value is not None: + return value + +# HANDLE EMPTY WORD, SINGULAR COUNT AND UNINFLECTED PLURALS + + if word == '': + return word + + lowerword = word.lower() + + if lowerword in pl_sb_uninflected_complete: + return word + + if word in pl_sb_uninflected_caps: + return word + + for k, v in pl_sb_uninflected_bysize.items(): + if lowerword[-k:] in v: + return word + + if (self.classical_dict['herd'] and lowerword in pl_sb_uninflected_herd): + return word + +# HANDLE COMPOUNDS ("Governor General", "mother-in-law", "aide-de-camp", ETC.) + + mo = search(r"^(?:%s)$" % pl_sb_postfix_adj_stems, word, IGNORECASE) + if mo and mo.group(2) != '': + return "%s%s" % (self._plnoun(mo.group(1), 2), mo.group(2)) + + if ' a ' in lowerword or '-a-' in lowerword: + mo = search(r"^(?:%s)$" % pl_sb_prep_dual_compound, word, IGNORECASE) + if mo and mo.group(2) != '' and mo.group(3) != '': + return "%s%s%s" % (self._plnoun(mo.group(1), 2), + mo.group(2), + self._plnoun(mo.group(3))) + + lowersplit = lowerword.split(' ') + if len(lowersplit) >= 3: + for numword in range(1, len(lowersplit) - 1): + if lowersplit[numword] in pl_prep_list_da: + return ' '.join( + lowersplit[:numword - 1] + + [self._plnoun(lowersplit[numword - 1], 2)] + lowersplit[numword:]) + + lowersplit = lowerword.split('-') + if len(lowersplit) >= 3: + for numword in range(1, len(lowersplit) - 1): + if lowersplit[numword] in pl_prep_list_da: + return ' '.join( + lowersplit[:numword - 1] + + [self._plnoun(lowersplit[numword - 1], 2) + + '-' + lowersplit[numword] + '-']) + ' '.join(lowersplit[(numword + 1):]) + +# HANDLE PRONOUNS + + for k, v in pl_pron_acc_keys_bysize.items(): + if lowerword[-k:] in v: # ends with accusivate pronoun + for pk, pv in pl_prep_bysize.items(): + if lowerword[:pk] in pv: # starts with a prep + if lowerword.split() == [lowerword[:pk], lowerword[-k:]]: # only whitespace in between + return lowerword[:-k] + pl_pron_acc[lowerword[-k:]] + + try: + return pl_pron_nom[word.lower()] + except KeyError: + pass + + try: + return pl_pron_acc[word.lower()] + except KeyError: + pass + +# HANDLE ISOLATED IRREGULAR PLURALS + + wordsplit = word.split() + wordlast = wordsplit[-1] + lowerwordlast = wordlast.lower() + + if wordlast in list(pl_sb_irregular_caps.keys()): + llen = len(wordlast) + return '%s%s' % (word[:-llen], + pl_sb_irregular_caps[wordlast]) + + if lowerwordlast in list(pl_sb_irregular.keys()): + llen = len(lowerwordlast) + return '%s%s' % (word[:-llen], + pl_sb_irregular[lowerwordlast]) + + if (' '.join(wordsplit[-2:])).lower() in list(pl_sb_irregular_compound.keys()): + llen = len(' '.join(wordsplit[-2:])) # TODO: what if 2 spaces between these words? + return '%s%s' % (word[:-llen], + pl_sb_irregular_compound[(' '.join(wordsplit[-2:])).lower()]) + + if lowerword[-3:] == 'quy': + return word[:-1] + 'ies' + + if lowerword[-6:] == 'person': + if self.classical_dict['persons']: + return word + 's' + else: + return word[:-4] + 'ople' + +# HANDLE FAMILIES OF IRREGULAR PLURALS + + if lowerword[-3:] == 'man': + for k, v in pl_sb_U_man_mans_bysize.items(): + if lowerword[-k:] in v: + return word + 's' + for k, v in pl_sb_U_man_mans_caps_bysize.items(): + if word[-k:] in v: + return word + 's' + return word[:-3] + 'men' + if lowerword[-5:] == 'mouse': + return word[:-5] + 'mice' + if lowerword[-5:] == 'louse': + return word[:-5] + 'lice' + if lowerword[-5:] == 'goose': + return word[:-5] + 'geese' + if lowerword[-5:] == 'tooth': + return word[:-5] + 'teeth' + if lowerword[-4:] == 'foot': + return word[:-4] + 'feet' + + if lowerword == 'die': + return 'dice' + +# HANDLE UNASSIMILATED IMPORTS + + if lowerword[-4:] == 'ceps': + return word + if lowerword[-4:] == 'zoon': + return word[:-2] + 'a' + if lowerword[-3:] in ('cis', 'sis', 'xis'): + return word[:-2] + 'es' + + for lastlet, d, numend, post in ( + ('h', pl_sb_U_ch_chs_bysize, None, 's'), + ('x', pl_sb_U_ex_ices_bysize, -2, 'ices'), + ('x', pl_sb_U_ix_ices_bysize, -2, 'ices'), + ('m', pl_sb_U_um_a_bysize, -2, 'a'), + ('s', pl_sb_U_us_i_bysize, -2, 'i'), + ('n', pl_sb_U_on_a_bysize, -2, 'a'), + ('a', pl_sb_U_a_ae_bysize, None, 'e'), + ): + if lowerword[-1] == lastlet: # this test to add speed + for k, v in d.items(): + if lowerword[-k:] in v: + return word[:numend] + post + +# HANDLE INCOMPLETELY ASSIMILATED IMPORTS + + if (self.classical_dict['ancient']): + if lowerword[-4:] == 'trix': + return word[:-1] + 'ces' + if lowerword[-3:] in ('eau', 'ieu'): + return word + 'x' + if lowerword[-3:] in ('ynx', 'inx', 'anx') and len(word) > 4: + return word[:-1] + 'ges' + + for lastlet, d, numend, post in ( + ('n', pl_sb_C_en_ina_bysize, -2, 'ina'), + ('x', pl_sb_C_ex_ices_bysize, -2, 'ices'), + ('x', pl_sb_C_ix_ices_bysize, -2, 'ices'), + ('m', pl_sb_C_um_a_bysize, -2, 'a'), + ('s', pl_sb_C_us_i_bysize, -2, 'i'), + ('s', pl_sb_C_us_us_bysize, None, ''), + ('a', pl_sb_C_a_ae_bysize, None, 'e'), + ('a', pl_sb_C_a_ata_bysize, None, 'ta'), + ('s', pl_sb_C_is_ides_bysize, -1, 'des'), + ('o', pl_sb_C_o_i_bysize, -1, 'i'), + ('n', pl_sb_C_on_a_bysize, -2, 'a'), + ): + if lowerword[-1] == lastlet: # this test to add speed + for k, v in d.items(): + if lowerword[-k:] in v: + return word[:numend] + post + + for d, numend, post in ( + (pl_sb_C_i_bysize, None, 'i'), + (pl_sb_C_im_bysize, None, 'im'), + ): + for k, v in d.items(): + if lowerword[-k:] in v: + return word[:numend] + post + +# HANDLE SINGULAR NOUNS ENDING IN ...s OR OTHER SILIBANTS + + if lowerword in pl_sb_singular_s_complete: + return word + 'es' + + for k, v in pl_sb_singular_s_bysize.items(): + if lowerword[-k:] in v: + return word + 'es' + + if lowerword[-2:] == 'es' and word[0] == word[0].upper(): + return word + 'es' + +# Wouldn't special words +# ending with 's' always have been caught, regardless of them starting +# with a capital letter (i.e. being names) +# It makes sense below to do this for words ending in 'y' so that +# Sally -> Sallys. But not sure it makes sense here. Where is the case +# of a word ending in s that is caught here and would otherwise have been +# caught below? +# +# removing it as I can't find a case that executes it +# TODO: check this again +# +# if (self.classical_dict['names']): +# mo = search(r"([A-Z].*s)$", word) +# if mo: +# return "%ses" % mo.group(1) + + if lowerword[-1] == 'z': + for k, v in pl_sb_z_zes_bysize.items(): + if lowerword[-k:] in v: + return word + 'es' + + if lowerword[-2:-1] != 'z': + return word + 'zes' + + if lowerword[-2:] == 'ze': + for k, v in pl_sb_ze_zes_bysize.items(): + if lowerword[-k:] in v: + return word + 's' + + if lowerword[-2:] in ('ch', 'sh', 'zz', 'ss') or lowerword[-1] == 'x': + return word + 'es' + +# ## (r"(.*)(us)$", "%s%ses"), TODO: why is this commented? + +# HANDLE ...f -> ...ves + + if lowerword[-3:] in ('elf', 'alf', 'olf'): + return word[:-1] + 'ves' + if lowerword[-3:] == 'eaf' and lowerword[-4:-3] != 'd': + return word[:-1] + 'ves' + if lowerword[-4:] in ('nife', 'life', 'wife'): + return word[:-2] + 'ves' + if lowerword[-3:] == 'arf': + return word[:-1] + 'ves' + +# HANDLE ...y + + if lowerword[-1] == 'y': + if lowerword[-2:-1] in 'aeiou' or len(word) == 1: + return word + 's' + + if (self.classical_dict['names']): + if lowerword[-1] == 'y' and word[0] == word[0].upper(): + return word + 's' + + return word[:-1] + 'ies' + +# HANDLE ...o + + if lowerword in pl_sb_U_o_os_complete: + return word + 's' + + for k, v in pl_sb_U_o_os_bysize.items(): + if lowerword[-k:] in v: + return word + 's' + + if lowerword[-2:] in ('ao', 'eo', 'io', 'oo', 'uo'): + return word + 's' + + if lowerword[-1] == 'o': + return word + 'es' + +# OTHERWISE JUST ADD ...s + + return "%ss" % word + + def _pl_special_verb(self, word, count=None): + if (self.classical_dict['zero'] and + str(count).lower() in pl_count_zero): + return False + count = self.get_count(count) + + if count == 1: + return word + +# HANDLE USER-DEFINED VERBS + + value = self.ud_match(word, self.pl_v_user_defined) + if value is not None: + return value + +# HANDLE IRREGULAR PRESENT TENSE (SIMPLE AND COMPOUND) + + lowerword = word.lower() + try: + firstword = lowerword.split()[0] + except IndexError: + return False # word is '' + + if firstword in list(plverb_irregular_pres.keys()): + return "%s%s" % (plverb_irregular_pres[firstword], word[len(firstword):]) + +# HANDLE IRREGULAR FUTURE, PRETERITE AND PERFECT TENSES + + if firstword in plverb_irregular_non_pres: + return word + +# HANDLE PRESENT NEGATIONS (SIMPLE AND COMPOUND) + + if firstword.endswith("n't") and firstword[:-3] in list(plverb_irregular_pres.keys()): + return "%sn't%s" % (plverb_irregular_pres[firstword[:-3]], word[len(firstword):]) + + if firstword.endswith("n't"): + return word + +# HANDLE SPECIAL CASES + + mo = search(r"^(%s)$" % plverb_special_s, word) + if mo: + return False + if search(r"\s", word): + return False + if lowerword == 'quizzes': + return 'quiz' + +# HANDLE STANDARD 3RD PERSON (CHOP THE ...(e)s OFF SINGLE WORDS) + + if lowerword[-4:] in ('ches', 'shes', 'zzes', 'sses') or \ + lowerword[-3:] == 'xes': + return word[:-2] + +# # mo = search(r"^(.*)([cs]h|[x]|zz|ss)es$", +# # word, IGNORECASE) +# # if mo: +# # return "%s%s" % (mo.group(1), mo.group(2)) + + if lowerword[-3:] == 'ies' and len(word) > 3: + return lowerword[:-3] + 'y' + + if (lowerword in pl_v_oes_oe or + lowerword[-4:] in pl_v_oes_oe_endings_size4 or + lowerword[-5:] in pl_v_oes_oe_endings_size5): + return word[:-1] + + if lowerword.endswith('oes') and len(word) > 3: + return lowerword[:-2] + + mo = search(r"^(.*[^s])s$", word, IGNORECASE) + if mo: + return mo.group(1) + +# OTHERWISE, A REGULAR VERB (HANDLE ELSEWHERE) + + return False + + def _pl_general_verb(self, word, count=None): + count = self.get_count(count) + + if count == 1: + return word + +# HANDLE AMBIGUOUS PRESENT TENSES (SIMPLE AND COMPOUND) + + mo = search(r"^(%s)((\s.*)?)$" % plverb_ambiguous_pres_keys, word, IGNORECASE) + if mo: + return "%s%s" % (plverb_ambiguous_pres[mo.group(1).lower()], mo.group(2)) + +# HANDLE AMBIGUOUS PRETERITE AND PERFECT TENSES + + mo = search(r"^(%s)((\s.*)?)$" % plverb_ambiguous_non_pres, word, IGNORECASE) + if mo: + return word + +# OTHERWISE, 1st OR 2ND PERSON IS UNINFLECTED + + return word + + def _pl_special_adjective(self, word, count=None): + count = self.get_count(count) + + if count == 1: + return word + +# HANDLE USER-DEFINED ADJECTIVES + + value = self.ud_match(word, self.pl_adj_user_defined) + if value is not None: + return value + +# HANDLE KNOWN CASES + + mo = search(r"^(%s)$" % pl_adj_special_keys, + word, IGNORECASE) + if mo: + return "%s" % (pl_adj_special[mo.group(1).lower()]) + +# HANDLE POSSESSIVES + + mo = search(r"^(%s)$" % pl_adj_poss_keys, + word, IGNORECASE) + if mo: + return "%s" % (pl_adj_poss[mo.group(1).lower()]) + + mo = search(r"^(.*)'s?$", + word) + if mo: + pl = self.plural_noun(mo.group(1)) + trailing_s = "" if pl[-1] == 's' else "s" + return "%s'%s" % (pl, trailing_s) + +# OTHERWISE, NO IDEA + + return False + + # @profile + def _sinoun(self, word, count=None, gender=None): + count = self.get_count(count) + +# DEFAULT TO PLURAL + + if count == 2: + return word + +# SET THE GENDER + + try: + if gender is None: + gender = self.thegender + elif gender not in singular_pronoun_genders: + raise BadGenderError + except (TypeError, IndexError): + raise BadGenderError + +# HANDLE USER-DEFINED NOUNS + + value = self.ud_match(word, self.si_sb_user_defined) + if value is not None: + return value + +# HANDLE EMPTY WORD, SINGULAR COUNT AND UNINFLECTED PLURALS + + if word == '': + return word + + lowerword = word.lower() + + if word in si_sb_ois_oi_case: + return word[:-1] + + if lowerword in pl_sb_uninflected_complete: + return word + + if word in pl_sb_uninflected_caps: + return word + + for k, v in pl_sb_uninflected_bysize.items(): + if lowerword[-k:] in v: + return word + + if (self.classical_dict['herd'] and lowerword in pl_sb_uninflected_herd): + return word + +# HANDLE COMPOUNDS ("Governor General", "mother-in-law", "aide-de-camp", ETC.) + + mo = search(r"^(?:%s)$" % pl_sb_postfix_adj_stems, word, IGNORECASE) + if mo and mo.group(2) != '': + return "%s%s" % (self._sinoun(mo.group(1), 1, gender=gender), mo.group(2)) + + # how to reverse this one? + # mo = search(r"^(?:%s)$" % pl_sb_prep_dual_compound, word, IGNORECASE) + # if mo and mo.group(2) != '' and mo.group(3) != '': + # return "%s%s%s" % (self._sinoun(mo.group(1), 1), + # mo.group(2), + # self._sinoun(mo.group(3), 1)) + + lowersplit = lowerword.split(' ') + if len(lowersplit) >= 3: + for numword in range(1, len(lowersplit) - 1): + if lowersplit[numword] in pl_prep_list_da: + return ' '.join(lowersplit[:numword - 1] + + [self._sinoun(lowersplit[numword - 1], 1, gender=gender)] + + lowersplit[numword:]) + + lowersplit = lowerword.split('-') + if len(lowersplit) >= 3: + for numword in range(1, len(lowersplit) - 1): + if lowersplit[numword] in pl_prep_list_da: + return ' '.join( + lowersplit[:numword - 1] + + [self._sinoun(lowersplit[numword - 1], 1, gender=gender) + + '-' + lowersplit[numword] + '-']) + ' '.join(lowersplit[(numword + 1):]) + +# HANDLE PRONOUNS + + for k, v in si_pron_acc_keys_bysize.items(): + if lowerword[-k:] in v: # ends with accusivate pronoun + for pk, pv in pl_prep_bysize.items(): + if lowerword[:pk] in pv: # starts with a prep + if lowerword.split() == [lowerword[:pk], lowerword[-k:]]: # only whitespace in between + return lowerword[:-k] + get_si_pron('acc', lowerword[-k:], gender) + + try: + return get_si_pron('nom', word.lower(), gender) + except KeyError: + pass + + try: + return get_si_pron('acc', word.lower(), gender) + except KeyError: + pass + +# HANDLE ISOLATED IRREGULAR PLURALS + + wordsplit = word.split() + wordlast = wordsplit[-1] + lowerwordlast = wordlast.lower() + + if wordlast in list(si_sb_irregular_caps.keys()): + llen = len(wordlast) + return '%s%s' % (word[:-llen], + si_sb_irregular_caps[wordlast]) + + if lowerwordlast in list(si_sb_irregular.keys()): + llen = len(lowerwordlast) + return '%s%s' % (word[:-llen], + si_sb_irregular[lowerwordlast]) + + if (' '.join(wordsplit[-2:])).lower() in list(si_sb_irregular_compound.keys()): + llen = len(' '.join(wordsplit[-2:])) # TODO: what if 2 spaces between these words? + return '%s%s' % (word[:-llen], + si_sb_irregular_compound[(' '.join(wordsplit[-2:])).lower()]) + + if lowerword[-5:] == 'quies': + return word[:-3] + 'y' + + if lowerword[-7:] == 'persons': + return word[:-1] + if lowerword[-6:] == 'people': + return word[:-4] + 'rson' + +# HANDLE FAMILIES OF IRREGULAR PLURALS + + if lowerword[-4:] == 'mans': + for k, v in si_sb_U_man_mans_bysize.items(): + if lowerword[-k:] in v: + return word[:-1] + for k, v in si_sb_U_man_mans_caps_bysize.items(): + if word[-k:] in v: + return word[:-1] + if lowerword[-3:] == 'men': + return word[:-3] + 'man' + if lowerword[-4:] == 'mice': + return word[:-4] + 'mouse' + if lowerword[-4:] == 'lice': + return word[:-4] + 'louse' + if lowerword[-5:] == 'geese': + return word[:-5] + 'goose' + if lowerword[-5:] == 'teeth': + return word[:-5] + 'tooth' + if lowerword[-4:] == 'feet': + return word[:-4] + 'foot' + + if lowerword == 'dice': + return 'die' + +# HANDLE UNASSIMILATED IMPORTS + + if lowerword[-4:] == 'ceps': + return word + if lowerword[-3:] == 'zoa': + return word[:-1] + 'on' + + for lastlet, d, numend, post in ( + ('s', si_sb_U_ch_chs_bysize, -1, ''), + ('s', si_sb_U_ex_ices_bysize, -4, 'ex'), + ('s', si_sb_U_ix_ices_bysize, -4, 'ix'), + ('a', si_sb_U_um_a_bysize, -1, 'um'), + ('i', si_sb_U_us_i_bysize, -1, 'us'), + ('a', si_sb_U_on_a_bysize, -1, 'on'), + ('e', si_sb_U_a_ae_bysize, -1, ''), + ): + if lowerword[-1] == lastlet: # this test to add speed + for k, v in d.items(): + if lowerword[-k:] in v: + return word[:numend] + post + +# HANDLE INCOMPLETELY ASSIMILATED IMPORTS + + if (self.classical_dict['ancient']): + + if lowerword[-6:] == 'trices': + return word[:-3] + 'x' + if lowerword[-4:] in ('eaux', 'ieux'): + return word[:-1] + if lowerword[-5:] in ('ynges', 'inges', 'anges') and len(word) > 6: + return word[:-3] + 'x' + + for lastlet, d, numend, post in ( + ('a', si_sb_C_en_ina_bysize, -3, 'en'), + ('s', si_sb_C_ex_ices_bysize, -4, 'ex'), + ('s', si_sb_C_ix_ices_bysize, -4, 'ix'), + ('a', si_sb_C_um_a_bysize, -1, 'um'), + ('i', si_sb_C_us_i_bysize, -1, 'us'), + ('s', pl_sb_C_us_us_bysize, None, ''), + ('e', si_sb_C_a_ae_bysize, -1, ''), + ('a', si_sb_C_a_ata_bysize, -2, ''), + ('s', si_sb_C_is_ides_bysize, -3, 's'), + ('i', si_sb_C_o_i_bysize, -1, 'o'), + ('a', si_sb_C_on_a_bysize, -1, 'on'), + ('m', si_sb_C_im_bysize, -2, ''), + ('i', si_sb_C_i_bysize, -1, ''), + ): + if lowerword[-1] == lastlet: # this test to add speed + for k, v in d.items(): + if lowerword[-k:] in v: + return word[:numend] + post + +# HANDLE PLURLS ENDING IN uses -> use + + if (lowerword[-6:] == 'houses' or + word in si_sb_uses_use_case or + lowerword in si_sb_uses_use): + return word[:-1] + +# HANDLE PLURLS ENDING IN ies -> ie + + if word in si_sb_ies_ie_case or lowerword in si_sb_ies_ie: + return word[:-1] + +# HANDLE PLURLS ENDING IN oes -> oe + + if (lowerword[-5:] == 'shoes' or + word in si_sb_oes_oe_case or + lowerword in si_sb_oes_oe): + return word[:-1] + +# HANDLE SINGULAR NOUNS ENDING IN ...s OR OTHER SILIBANTS + + if (word in si_sb_sses_sse_case or + lowerword in si_sb_sses_sse): + return word[:-1] + + if lowerword in si_sb_singular_s_complete: + return word[:-2] + + for k, v in si_sb_singular_s_bysize.items(): + if lowerword[-k:] in v: + return word[:-2] + + if lowerword[-4:] == 'eses' and word[0] == word[0].upper(): + return word[:-2] + +# Wouldn't special words +# ending with 's' always have been caught, regardless of them starting +# with a capital letter (i.e. being names) +# It makes sense below to do this for words ending in 'y' so that +# Sally -> Sallys. But not sure it makes sense here. Where is the case +# of a word ending in s that is caught here and would otherwise have been +# caught below? +# +# removing it as I can't find a case that executes it +# TODO: check this again +# +# if (self.classical_dict['names']): +# mo = search(r"([A-Z].*ses)$", word) +# if mo: +# return "%s" % mo.group(1) + + if lowerword in si_sb_z_zes: + return word[:-2] + + if lowerword in si_sb_zzes_zz: + return word[:-2] + + if lowerword[-4:] == 'zzes': + return word[:-3] + + if (word in si_sb_ches_che_case or + lowerword in si_sb_ches_che): + return word[:-1] + + if lowerword[-4:] in ('ches', 'shes'): + return word[:-2] + + if lowerword in si_sb_xes_xe: + return word[:-1] + + if lowerword[-3:] == 'xes': + return word[:-2] +# (r"(.*)(us)es$", "%s%s"), TODO: why is this commented? + +# HANDLE ...f -> ...ves + + if (word in si_sb_ves_ve_case or + lowerword in si_sb_ves_ve): + return word[:-1] + + if lowerword[-3:] == 'ves': + if lowerword[-5:-3] in ('el', 'al', 'ol'): + return word[:-3] + 'f' + if lowerword[-5:-3] == 'ea' and word[-6:-5] != 'd': + return word[:-3] + 'f' + if lowerword[-5:-3] in ('ni', 'li', 'wi'): + return word[:-3] + 'fe' + if lowerword[-5:-3] == 'ar': + return word[:-3] + 'f' + +# HANDLE ...y + + if lowerword[-2:] == 'ys': + if len(lowerword) > 2 and lowerword[-3] in 'aeiou': + return word[:-1] + + if (self.classical_dict['names']): + if lowerword[-2:] == 'ys' and word[0] == word[0].upper(): + return word[:-1] + + if lowerword[-3:] == 'ies': + return word[:-3] + 'y' + +# HANDLE ...o + + if lowerword[-2:] == 'os': + + if lowerword in si_sb_U_o_os_complete: + return word[:-1] + + for k, v in si_sb_U_o_os_bysize.items(): + if lowerword[-k:] in v: + return word[:-1] + + if lowerword[-3:] in ('aos', 'eos', 'ios', 'oos', 'uos'): + return word[:-1] + + if lowerword[-3:] == 'oes': + return word[:-2] + +# UNASSIMILATED IMPORTS FINAL RULE + + if word in si_sb_es_is: + return word[:-2] + 'is' + +# OTHERWISE JUST REMOVE ...s + + if lowerword[-1] == 's': + return word[:-1] + +# COULD NOT FIND SINGULAR + + return False + +# ADJECTIVES + + def a(self, text, count=1): + ''' + Return the appropriate indefinite article followed by text. + + The indefinite article is either 'a' or 'an'. + + If count is not one, then return count followed by text + instead of 'a' or 'an'. + + Whitespace at the start and end is preserved. + + ''' + mo = search(r"\A(\s*)(?:an?\s+)?(.+?)(\s*)\Z", + text, IGNORECASE) + if mo: + word = mo.group(2) + if not word: + return text + pre = mo.group(1) + post = mo.group(3) + result = self._indef_article(word, count) + return "%s%s%s" % (pre, result, post) + return '' + + an = a + + def _indef_article(self, word, count): + mycount = self.get_count(count) + + if mycount != 1: + return "%s %s" % (count, word) + +# HANDLE USER-DEFINED VARIANTS + + value = self.ud_match(word, self.A_a_user_defined) + if value is not None: + return "%s %s" % (value, word) + +# HANDLE ORDINAL FORMS + + for a in ( + (r"^(%s)" % A_ordinal_a, "a"), + (r"^(%s)" % A_ordinal_an, "an"), + ): + mo = search(a[0], word, IGNORECASE) + if mo: + return "%s %s" % (a[1], word) + +# HANDLE SPECIAL CASES + + for a in ( + (r"^(%s)" % A_explicit_an, "an"), + (r"^[aefhilmnorsx]$", "an"), + (r"^[bcdgjkpqtuvwyz]$", "a"), + ): + mo = search(a[0], word, IGNORECASE) + if mo: + return "%s %s" % (a[1], word) + +# HANDLE ABBREVIATIONS + + for a in ( + (r"(%s)" % A_abbrev, "an", VERBOSE), + (r"^[aefhilmnorsx][.-]", "an", IGNORECASE), + (r"^[a-z][.-]", "a", IGNORECASE), + ): + mo = search(a[0], word, a[2]) + if mo: + return "%s %s" % (a[1], word) + +# HANDLE CONSONANTS + + mo = search(r"^[^aeiouy]", word, IGNORECASE) + if mo: + return "a %s" % word + +# HANDLE SPECIAL VOWEL-FORMS + + for a in ( + (r"^e[uw]", "a"), + (r"^onc?e\b", "a"), + (r"^onetime\b", "a"), + (r"^uni([^nmd]|mo)", "a"), + (r"^u[bcfghjkqrst][aeiou]", "a"), + (r"^ukr", "a"), + (r"^(%s)" % A_explicit_a, "a"), + ): + mo = search(a[0], word, IGNORECASE) + if mo: + return "%s %s" % (a[1], word) + +# HANDLE SPECIAL CAPITALS + + mo = search(r"^U[NK][AIEO]?", word) + if mo: + return "a %s" % word + +# HANDLE VOWELS + + mo = search(r"^[aeiou]", word, IGNORECASE) + if mo: + return "an %s" % word + +# HANDLE y... (BEFORE CERTAIN CONSONANTS IMPLIES (UNNATURALIZED) "i.." SOUND) + + mo = search(r"^(%s)" % A_y_cons, word, IGNORECASE) + if mo: + return "an %s" % word + +# OTHERWISE, GUESS "a" + return "a %s" % word + +# 2. TRANSLATE ZERO-QUANTIFIED $word TO "no plural($word)" + + def no(self, text, count=None): + ''' + If count is 0, no, zero or nil, return 'no' followed by the plural + of text. + + If count is one of: + 1, a, an, one, each, every, this, that + return count followed by text. + + Otherwise return count follow by the plural of text. + + In the return value count is always followed by a space. + + Whitespace at the start and end is preserved. + + ''' + if count is None and self.persistent_count is not None: + count = self.persistent_count + + if count is None: + count = 0 + mo = search(r"\A(\s*)(.+?)(\s*)\Z", text) + pre = mo.group(1) + word = mo.group(2) + post = mo.group(3) + + if str(count).lower() in pl_count_zero: + return "%sno %s%s" % (pre, self.plural(word, 0), post) + else: + return "%s%s %s%s" % (pre, count, self.plural(word, count), post) + +# PARTICIPLES + + def present_participle(self, word): + ''' + Return the present participle for word. + + word is the 3rd person singular verb. + + ''' + plv = self.plural_verb(word, 2) + + for pat, repl in ( + (r"ie$", r"y"), + (r"ue$", r"u"), # TODO: isn't ue$ -> u encompassed in the following rule? + (r"([auy])e$", r"\g<1>"), + (r"ski$", r"ski"), + (r"[^b]i$", r""), + (r"^(are|were)$", r"be"), + (r"^(had)$", r"hav"), + (r"^(hoe)$", r"\g<1>"), + (r"([^e])e$", r"\g<1>"), + (r"er$", r"er"), + (r"([^aeiou][aeiouy]([bdgmnprst]))$", "\g<1>\g<2>"), + ): + (ans, num) = subn(pat, repl, plv) + if num: + return "%sing" % ans + return "%sing" % ans + +# NUMERICAL INFLECTIONS + + def ordinal(self, num): + ''' + Return the ordinal of num. + + num can be an integer or text + + e.g. ordinal(1) returns '1st' + ordinal('one') returns 'first' + + ''' + if match(r"\d", str(num)): + try: + num % 2 + n = num + except TypeError: + if '.' in str(num): + try: + n = int(num[-1]) # numbers after decimal, so only need last one for ordinal + except ValueError: # ends with '.', so need to use whole string + n = int(num[:-1]) + else: + n = int(num) + try: + post = nth[n % 100] + except KeyError: + post = nth[n % 10] + return "%s%s" % (num, post) + else: + mo = search(r"(%s)\Z" % ordinal_suff, num) + try: + post = ordinal[mo.group(1)] + return resub(r"(%s)\Z" % ordinal_suff, post, num) + except AttributeError: + return "%sth" % num + + def millfn(self, ind=0): + if ind > len(mill) - 1: + print3("number out of range") + raise NumOutOfRangeError + return mill[ind] + + def unitfn(self, units, mindex=0): + return "%s%s" % (unit[units], self.millfn(mindex)) + + def tenfn(self, tens, units, mindex=0): + if tens != 1: + return "%s%s%s%s" % (ten[tens], + '-' if tens and units else '', + unit[units], + self.millfn(mindex)) + return "%s%s" % (teen[units], mill[mindex]) + + def hundfn(self, hundreds, tens, units, mindex): + if hundreds: + return "%s hundred%s%s%s, " % (unit[hundreds], # use unit not unitfn as simpler + " %s " % self.number_args['andword'] if tens or units else '', + self.tenfn(tens, units), + self.millfn(mindex)) + if tens or units: + return "%s%s, " % (self.tenfn(tens, units), self.millfn(mindex)) + return '' + + def group1sub(self, mo): + units = int(mo.group(1)) + if units == 1: + return " %s, " % self.number_args['one'] + elif units: + # TODO: bug one and zero are padded with a space but other numbers aren't. check this in perl + return "%s, " % unit[units] + else: + return " %s, " % self.number_args['zero'] + + def group1bsub(self, mo): + units = int(mo.group(1)) + if units: + # TODO: bug one and zero are padded with a space but other numbers aren't. check this in perl + return "%s, " % unit[units] + else: + return " %s, " % self.number_args['zero'] + + def group2sub(self, mo): + tens = int(mo.group(1)) + units = int(mo.group(2)) + if tens: + return "%s, " % self.tenfn(tens, units) + if units: + return " %s %s, " % (self.number_args['zero'], unit[units]) + return " %s %s, " % (self.number_args['zero'], self.number_args['zero']) + + def group3sub(self, mo): + hundreds = int(mo.group(1)) + tens = int(mo.group(2)) + units = int(mo.group(3)) + if hundreds == 1: + hunword = " %s" % self.number_args['one'] + elif hundreds: + hunword = "%s" % unit[hundreds] + # TODO: bug one and zero are padded with a space but other numbers aren't. check this in perl + else: + hunword = " %s" % self.number_args['zero'] + if tens: + tenword = self.tenfn(tens, units) + elif units: + tenword = " %s %s" % (self.number_args['zero'], unit[units]) + else: + tenword = " %s %s" % (self.number_args['zero'], self.number_args['zero']) + return "%s %s, " % (hunword, tenword) + + def hundsub(self, mo): + ret = self.hundfn(int(mo.group(1)), int(mo.group(2)), int(mo.group(3)), self.mill_count) + self.mill_count += 1 + return ret + + def tensub(self, mo): + return "%s, " % self.tenfn(int(mo.group(1)), int(mo.group(2)), self.mill_count) + + def unitsub(self, mo): + return "%s, " % self.unitfn(int(mo.group(1)), self.mill_count) + + def enword(self, num, group): + # import pdb + # pdb.set_trace() + + if group == 1: + num = resub(r"(\d)", self.group1sub, num) + elif group == 2: + num = resub(r"(\d)(\d)", self.group2sub, num) + num = resub(r"(\d)", self.group1bsub, num, 1) + # group1bsub same as + # group1sub except it doesn't use the default word for one. + # Is this required? i.e. is the default word not to beused when + # grouping in pairs? + # + # No. This is a bug. Fixed. TODO: report upstream. + elif group == 3: + num = resub(r"(\d)(\d)(\d)", self.group3sub, num) + num = resub(r"(\d)(\d)", self.group2sub, num, 1) + num = resub(r"(\d)", self.group1sub, num, 1) + elif int(num) == 0: + num = self.number_args['zero'] + elif int(num) == 1: + num = self.number_args['one'] + else: + num = num.lstrip().lstrip('0') + self.mill_count = 0 + # surely there's a better way to do the next bit + mo = search(r"(\d)(\d)(\d)(?=\D*\Z)", num) + while mo: + num = resub(r"(\d)(\d)(\d)(?=\D*\Z)", self.hundsub, num, 1) + mo = search(r"(\d)(\d)(\d)(?=\D*\Z)", num) + num = resub(r"(\d)(\d)(?=\D*\Z)", self.tensub, num, 1) + num = resub(r"(\d)(?=\D*\Z)", self.unitsub, num, 1) + return num + + def blankfn(self, mo): + ''' do a global blank replace + TODO: surely this can be done with an option to resub + rather than this fn + ''' + return '' + + def commafn(self, mo): + ''' do a global ',' replace + TODO: surely this can be done with an option to resub + rather than this fn + ''' + return ',' + + def spacefn(self, mo): + ''' do a global ' ' replace + TODO: surely this can be done with an option to resub + rather than this fn + ''' + return ' ' + + def number_to_words(self, num, wantlist=False, + group=0, comma=',', andword='and', + zero='zero', one='one', decimal='point', + threshold=None): + ''' + Return a number in words. + + group = 1, 2 or 3 to group numbers before turning into words + comma: define comma + andword: word for 'and'. Can be set to ''. + e.g. "one hundred and one" vs "one hundred one" + zero: word for '0' + one: word for '1' + decimal: word for decimal point + threshold: numbers above threshold not turned into words + + parameters not remembered from last call. Departure from Perl version. + ''' + self.number_args = dict(andword=andword, zero=zero, one=one) + num = '%s' % num + + # Handle "stylistic" conversions (up to a given threshold)... + if (threshold is not None and float(num) > threshold): + spnum = num.split('.', 1) + while (comma): + (spnum[0], n) = subn(r"(\d)(\d{3}(?:,|\Z))", r"\1,\2", spnum[0]) + if n == 0: + break + try: + return "%s.%s" % (spnum[0], spnum[1]) + except IndexError: + return "%s" % spnum[0] + + if group < 0 or group > 3: + raise BadChunkingOptionError + nowhite = num.lstrip() + if nowhite[0] == '+': + sign = "plus" + elif nowhite[0] == '-': + sign = "minus" + else: + sign = "" + + myord = (num[-2:] in ('st', 'nd', 'rd', 'th')) + if myord: + num = num[:-2] + finalpoint = False + if decimal: + if group != 0: + chunks = num.split('.') + else: + chunks = num.split('.', 1) + if chunks[-1] == '': # remove blank string if nothing after decimal + chunks = chunks[:-1] + finalpoint = True # add 'point' to end of output + else: + chunks = [num] + + first = 1 + loopstart = 0 + + if chunks[0] == '': + first = 0 + if len(chunks) > 1: + loopstart = 1 + + for i in range(loopstart, len(chunks)): + chunk = chunks[i] + # remove all non numeric \D + chunk = resub(r"\D", self.blankfn, chunk) + if chunk == "": + chunk = "0" + + if group == 0 and (first == 0 or first == ''): + chunk = self.enword(chunk, 1) + else: + chunk = self.enword(chunk, group) + + if chunk[-2:] == ', ': + chunk = chunk[:-2] + chunk = resub(r"\s+,", self.commafn, chunk) + + if group == 0 and first: + chunk = resub(r", (\S+)\s+\Z", " %s \\1" % andword, chunk) + chunk = resub(r"\s+", self.spacefn, chunk) + # chunk = resub(r"(\A\s|\s\Z)", self.blankfn, chunk) + chunk = chunk.strip() + if first: + first = '' + chunks[i] = chunk + + numchunks = [] + if first != 0: + numchunks = chunks[0].split("%s " % comma) + + if myord and numchunks: + # TODO: can this be just one re as it is in perl? + mo = search(r"(%s)\Z" % ordinal_suff, numchunks[-1]) + if mo: + numchunks[-1] = resub(r"(%s)\Z" % ordinal_suff, ordinal[mo.group(1)], + numchunks[-1]) + else: + numchunks[-1] += 'th' + + for chunk in chunks[1:]: + numchunks.append(decimal) + numchunks.extend(chunk.split("%s " % comma)) + + if finalpoint: + numchunks.append(decimal) + + # wantlist: Perl list context. can explictly specify in Python + if wantlist: + if sign: + numchunks = [sign] + numchunks + return numchunks + elif group: + signout = "%s " % sign if sign else '' + return "%s%s" % (signout, ", ".join(numchunks)) + else: + signout = "%s " % sign if sign else '' + num = "%s%s" % (signout, numchunks.pop(0)) + if decimal is None: + first = True + else: + first = not num.endswith(decimal) + for nc in numchunks: + if nc == decimal: + num += " %s" % nc + first = 0 + elif first: + num += "%s %s" % (comma, nc) + else: + num += " %s" % nc + return num + +# Join words with commas and a trailing 'and' (when appropriate)... + + def join(self, words, sep=None, sep_spaced=True, + final_sep=None, conj='and', conj_spaced=True): + ''' + Join words into a list. + + e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly' + + options: + conj: replacement for 'and' + sep: separator. default ',', unless ',' is in the list then ';' + final_sep: final separator. default ',', unless ',' is in the list then ';' + conj_spaced: boolean. Should conj have spaces around it + + ''' + if not words: + return "" + if len(words) == 1: + return words[0] + + if conj_spaced: + if conj == '': + conj = ' ' + else: + conj = ' %s ' % conj + + if len(words) == 2: + return "%s%s%s" % (words[0], conj, words[1]) + + if sep is None: + if ',' in ''.join(words): + sep = ';' + else: + sep = ',' + if final_sep is None: + final_sep = sep + + final_sep = "%s%s" % (final_sep, conj) + + if sep_spaced: + sep += ' ' + + return "%s%s%s" % (sep.join(words[0:-1]), final_sep, words[-1]) diff --git a/Code/irc/inflect.pyc b/Code/irc/inflect.pyc new file mode 100644 index 0000000..9feea7f Binary files /dev/null and b/Code/irc/inflect.pyc differ diff --git a/Code/irc/int2word.py b/Code/irc/int2word.py new file mode 100644 index 0000000..eaf5dba --- /dev/null +++ b/Code/irc/int2word.py @@ -0,0 +1,65 @@ +# integer number to english word conversion +# can be used for numbers as large as 999 vigintillion +# (vigintillion --> 10 to the power 60) +# tested with Python24 vegaseat 07dec2006 +def int2word(n): + """ + convert an integer number n into a string of english words + """ + # break the number into groups of 3 digits using slicing + # each group representing hundred, thousand, million, billion, ... + n3 = [] + r1 = "" + # create numeric string + ns = str(n) + for k in range(3, 33, 3): + r = ns[-k:] + q = len(ns) - k + # break if end of ns has been reached + if q < -2: + break + else: + if q >= 0: + n3.append(int(r[:3])) + elif q >= -1: + n3.append(int(r[:2])) + elif q >= -2: + n3.append(int(r[:1])) + r1 = r + + #print n3 # test + + # break each group of 3 digits into + # ones, tens/twenties, hundreds + # and form a string + nw = "" + for i, x in enumerate(n3): + b1 = x % 10 + b2 = (x % 100)//10 + b3 = (x % 1000)//100 + #print b1, b2, b3 # test + if x == 0: + continue # skip + else: + t = thousands[i] + if b2 == 0: + nw = ones[b1] + t + nw + elif b2 == 1: + nw = tens[b1] + t + nw + elif b2 > 1: + nw = twenties[b2] + ones[b1] + t + nw + if b3 > 0: + nw = ones[b3] + "hundred " + nw + return nw +############# globals ################ +ones = ["", "one ","two ","three ","four ", "five ", + "six ","seven ","eight ","nine "] +tens = ["ten ","eleven ","twelve ","thirteen ", "fourteen ", + "fifteen ","sixteen ","seventeen ","eighteen ","nineteen "] +twenties = ["","","twenty ","thirty ","forty ", + "fifty ","sixty ","seventy ","eighty ","ninety "] +thousands = ["","thousand ","million ", "billion ", "trillion ", + "quadrillion ", "quintillion ", "sextillion ", "septillion ","octillion ", + "nonillion ", "decillion ", "undecillion ", "duodecillion ", "tredecillion ", + "quattuordecillion ", "sexdecillion ", "septendecillion ", "octodecillion ", + "novemdecillion ", "vigintillion "] diff --git a/Code/irc/int2word.pyc b/Code/irc/int2word.pyc new file mode 100644 index 0000000..2b29b73 Binary files /dev/null and b/Code/irc/int2word.pyc differ diff --git a/Code/irc/log b/Code/irc/log new file mode 100644 index 0000000..e69de29 diff --git a/Code/irc/mentions.pyc b/Code/irc/mentions.pyc new file mode 100644 index 0000000..e452a1d Binary files /dev/null and b/Code/irc/mentions.pyc differ diff --git a/Code/irc/pretty_date.py b/Code/irc/pretty_date.py new file mode 100644 index 0000000..d8f670e --- /dev/null +++ b/Code/irc/pretty_date.py @@ -0,0 +1,42 @@ +def pretty_date(time=False): + """ + Get a datetime object or a int() Epoch timestamp and return a + pretty string like 'an hour ago', 'Yesterday', '3 months ago', + 'just now', etc + """ + from datetime import datetime + now = datetime.now() + if type(time) is int: + diff = now - datetime.fromtimestamp(time) + elif isinstance(time,datetime): + diff = now - time + elif not time: + diff = now - now + second_diff = diff.seconds + day_diff = diff.days + + if day_diff < 0: + return '' + + if day_diff == 0: + if second_diff < 10: + return "just now" + if second_diff < 60: + return str(second_diff) + " seconds ago" + if second_diff < 120: + return "a minute ago" + if second_diff < 3600: + return str(second_diff / 60) + " minutes ago" + if second_diff < 7200: + return "an hour ago" + if second_diff < 86400: + return str(second_diff / 3600) + " hours ago" + if day_diff == 1: + return "Yesterday" + if day_diff < 7: + return str(day_diff) + " days ago" + if day_diff < 31: + return str(day_diff / 7) + " weeks ago" + if day_diff < 365: + return str(day_diff / 30) + " months ago" + return str(day_diff / 365) + " years ago" diff --git a/Code/irc/pretty_date.pyc b/Code/irc/pretty_date.pyc new file mode 100644 index 0000000..e362852 Binary files /dev/null and b/Code/irc/pretty_date.pyc differ diff --git a/Code/irc/quote_bot.py b/Code/irc/quote_bot.py new file mode 100755 index 0000000..21a4898 --- /dev/null +++ b/Code/irc/quote_bot.py @@ -0,0 +1,118 @@ +#!/usr/bin/python +# http://wiki.shellium.org/w/Writing_an_IRC_bot_in_Python + +# Import some necessary libraries. +import socket +import os +import sys +from optparse import OptionParser + +import get_users +import mentions +import formatter + +parser = OptionParser() + +parser.add_option("-s", "--server", dest="server", default='127.0.0.1', + help="the server to connect to", metavar="SERVER") +parser.add_option("-c", "--channel", dest="channel", default='#tildetown', + help="the channel to join", metavar="CHANNEL") +parser.add_option("-n", "--nick", dest="nick", default='quote_bot', + help="the nick to use", metavar="NICK") + +(options, args) = parser.parse_args() + +def ping(): + ircsock.send("PONG :pingis\n") + +def sendmsg(chan , msg): + ircsock.send("PRIVMSG "+ chan +" :"+ msg +"\n") + +def joinchan(chan): + ircsock.send("JOIN "+ chan +"\n") + +def hello(): + ircsock.send("PRIVMSG "+ channel +" :Hello!\n") + +def random_quote(channel): + quote = os.popen("/home/frs/quotes/randquote.py").read() + if len(quote) >= 256: + quote = quote[:253] + '...' + ircsock.send("PRIVMSG "+ channel +" :" + quote + "\n") + +def haiku(channel): + h = os.popen("haiku").read().replace("\n", " // ") + ircsock.send("PRIVMSG "+ channel +" :" + h + "\n") + +def connect(server, channel, botnick): + ircsock.connect((server, 6667)) + ircsock.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This bot is a result of a tutoral covered on http://shellium.org/wiki.\n") # user authentication + ircsock.send("NICK "+ botnick +"\n") + + joinchan(channel) + +def get_user_from_message(msg): + try: + i1 = msg.index(':') + 1 + i2 = msg.index('!') + return msg[i1:i2] + except ValueError: + return "" + +def say_mentions(user, message): + nick = get_user_from_message(message) + menschns = os.popen("/home/karlen/bin/mensch -u %s -t 24 -z +0" % (user)).read().replace("\t", ": ").split("\n") + for mention in menschns: + if not "" == mention: + toSend = "PRIVMSG "+ nick + " :" + mention + "\n" + if len(toSend) >= 256: + toSend = toSend[:253] + '...' + ircsock.send(toSend) + +def say_chatty(channel): + chattyOut = os.popen("/home/karlen/bin/chatty").read().split("\n") + for line in chattyOut: + if line: + ircsock.send("PRIVMSG "+ channel + " :" + line + "\n") + +def listen(): + while 1: + + ircmsg = ircsock.recv(2048) + ircmsg = ircmsg.strip('\n\r') + + if ircmsg.find("PING :") != -1: + ping() + + formatted = formatter.format_message(ircmsg) + + if "" == formatted: + continue + + print formatted + + split = formatted.split("\t") + time = split[0] + user = split[1] + messageText = split[2] + + if ircmsg.find(":!quote") != -1: + random_quote(options.channel) + + if ircmsg.find(":!mentions") != -1: + say_mentions(user, ircmsg) + + if ircmsg.find(":!chatty") != -1: + say_chatty(options.channel) + + if ircmsg.find(":!haiku") != -1: + haiku(options.channel) + + if ircmsg.find("PING :") != -1: + ping() + + sys.stdout.flush() + +ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +connect(options.server, options.channel, options.nick) +listen() diff --git a/Code/irc/randomtopics.txt b/Code/irc/randomtopics.txt new file mode 100644 index 0000000..cf1944a --- /dev/null +++ b/Code/irc/randomtopics.txt @@ -0,0 +1,217 @@ +What was the last picture you took with your phone? +Do you know any big gossipers? +Have you been pulled over by a cop? +Do you know your heritage? +What have you always wanted? Did you ever get it? +What kind of sickness have you lied about so you wouldn't go to work? +What was the last lie you told? +Have you ever danced in the rain? +What is your blood type? +Have you ever been in a car accident? +What was the weirdest prank call that you have made? +Best compliment you have received? +Do you trust anyone with your life? +What is your greatest strength or weakness? +What is your perfect pizza? +What was your first thought when you woke up this morning +Do you get along with your family? Why or why not? +Ugly and live forever, or attractive and die in a year? +You discover that your wonderful one year old child is because of a mix up at the hospital and not yours. Would you want to exchange the child to correct the mistake? +Would you be willing to lie to a court for a close friend if it meant saving your friend from going to jail for life? +Would you be willing to eat a bowl of crickets for 0,000? +If you could have anyone locked in a room so that you could torment them for a day, whom would you choose ad how would you torment them? +Do you feel that children should be sheltered from unhappiness? +If you could have personally witnessed anything, what would you want to have seen? +If you could wake up tomorrow in the body of someone else, who would you pick and what would you do? +If you could be any age for a week, what age would that be? + What question do you hate to answer? +If you could only have one meal for the rest of your life, what would it be? +Where do you go to get on a computer? + How do you start a conversation? +What keys on a keyboard do you not use? +If you had a brainwashing machine, who would you use it on? +You are walking home in the dark, you see something move. What/Who is it(guess)? What do you do? +What is the strangest name someone has introduced themselves as to you? What is their real name? +Where were you 3 hours ago? Do you think someone was stalking you? +Have you ever eating a crayon, or glue? Or what strange thing have you eaten? +What type of music do you listen to? (Genre, artists, songs?) +What cheers you up? +What do you constantly think about that, either makes you sad or just anything? +Is there something you constantly lose at your hours or anywhere? +Do you have a favorite book or read much? Why or why not? + What is the longest you have gone without sleep? +Do you have anyone you go to for advice? In person or online? +What is the habit you are proudest of breaking or want to break? +Is there anything I should know? +What do you order or not order at a restaurant you have been to or never been to? +What is your favorite word? Least favorite? +Describe something that's happened to you for which had no explanation. +What did you do for your latest birthday? +What holidays do you celebrate? Are you a religious person or not? +If you had to be named after a city, state, or country (etc), which would you want it to be? +Who is your hero? +Which do you use more often, the dictionary or the thesaurus? +Have you ever been stung by a bee? +Have you ever tipped a cow? +What's the sickest you have ever been? +Are you still learning who you are? +Are you afraid of heights? Or what are you afraid of? +Have you ever taken dance lessons? Who would you want to dance with? +What is the most memorable class you have ever taken? +Why? +What's your favorite knock-knock joke? +What is your favorite commercial? +If you could spend the day with any celebrity, who would it be? +What is your favorite breakfast food? +Do you like guacamole? Have you ever been in a food fight? +What is your favorite thing to spend money on? +What is the weirdest thing about you? Are you proud of it? +Ever been in love with 2 people at the same time? Do you think that's wrong? +Ever had any relatives in jail? +Glass half full or half empty? Or is the glass just malformed? +Mountains or the beach? View, or the tv? +Plain, train, or car? Boat, subway, or teleportation device? +If you could retire tomorrow, what would you do? +Ever sold/donated your blood? If you haven't do you want to? +Crowds, small groups, or “Go away, I'm a loner”? +Name the most terrifying moment of your life so far. Have you recovered from it? +What famous person do people tell you that you most resemble? +What is the strangest thing you have ever eaten? +If you could bring any person back to life, who would it be? +Do you believe honesty is the best policy? +What dead person would you least want to be haunted by? +Who would you most like to be stuck in an elevator with? +Who would you least like to be .? +What do you think Victoria's secret is? +Which cartoon character do you resemble the most? +Would you rather go a week without bathing, but be able to change your clothes? Or a week without changing your clothes but be able to bathe. +Which of the four seasons do you most love? Or Hate? +If you could choose your method of dying or where, what would they be? +If you had to be trapped in a tv show for a month, which would you choose? +List someone you know, and describe them in 5 words. +You can select one person from history and have them truthfully answer one question, who would you select and what is the question? +If you join the circus, what would you perform? +Is there anything purple within 10 feet of you? What is it? + When was the last time you bought something? What was it? +Are you wearing socks right now? +Have you been to the movies in the last 5 days? +When was the last time you ran/went for a jog? +Your dream vacation? Worst vacation? Best vacation? +Worst injury you have had? +Grab the book nearest to you, turn to page 18, and find line 4. +Stretch your left arm out as far as you can, What can you touch? +Before you started this survey, what were you doing? +What is the last thing you watched on TV? +Without looking, guess what time it is +Now look at the clock. What is the actual time? +With the exception of the computer, what can you hear? +When did you last step outside? What were you doing? +Did you dream last night? +Do you remember your dreams? +When did you last laugh? +Do you remember why / at what? +What is on the walls of the room you are in? +Seen anything weird lately? +What is the last film you saw? +If you could live anywhere in the world, where would you live? +If you became a multi-millionaire overnight, what would you buy? +Tell me something about you that most people don't know. +If you could change one thing about the world, regardless of guilt or politics, what would you do? +Do you like to dance? +Would you ever consider living abroad? +Does your name make any interesting anagrams? +Who made the last incoming call on your phone? +What is the last thing you downloaded onto your computer? +Last time you swam in a pool? +Type of music you like most? +Type of music you dislike most? +Are you listening to music right now? +What color is your bedroom carpet? +If you could change something about your home, without worry about expense or mess, what would you do? +What was the last thing you bought? +Have you ever ridden on a motorbike? +Would you go bungee jumping or sky diving? +Do you have a garden? +Do you really know all the words to your national anthem? +What is the first thing you think of when you wake up in the morning? +If you could eat lunch with one famous person, who would it be? +Who sent the last text message you received? +Which store would you choose to max out your credit card? +What time is bed time? +Have you ever been in a beauty pageant? +How many tattoos do you have? +If you don't have any, have you ever thought of getting one? +What did you do for your last birthday? +Do you carry a donor card? +Who was the last person you ate dinner with? +Is the glass half empty or half full? +What's the farthest-away place you've been? +When's the last time you ate a homegrown tomato? +Have you ever won a trophy? +Are you a good cook? +Do you know how to pump your own gas? +If you could meet any one person (from history or currently alive), who would it be? +Have you ever had to wear a uniform to school? +Do you touch-type? +What's under your bed? +Do you believe in love at first sight? +Think fast, what do you like right now? +Where were you on Valentine's day? +What time do you get up? +What was the name of your first pet? +Who is the second to last person to call you? +Is there anything going on this weekend? +How are you feeling right now? +What do you think about the most? +What time do you get up in the morning? +If you had A Big Win in the Lottery, how long would you wait to tell people? +Who would you tell first? +What is the last movie that you saw at the cinema? +Do you sing in the shower? +Which store would you choose to max out your credit card? +What do you do most when you are bored? +What do you do for a living? +Do you love your job? +What did you want to be when you grew up? +If you could have any job, what would you want to do/be? +Which came first the chicken or the egg? +How many keys on your key ring? +Where would you retire to? +What kind of car do you drive? +What are your best physical features? +What are your best characteristics? +If you could go anywhere in the world on vacation where would you go? +What kind of books do you like to read? +Where would you want to retire to? +What is your favorite time of the day? +Where did you grow up? +How far away from your birthplace do you live now? +What are you reading now? +Are you a morning person or a night owl? +Can you touch your nose with your tongue? +Can you close your eyes and raise your eyebrows? +Do you have pets? +How many rings before you answer the phone? +What is your best childhood memory? +What are some of the different jobs that you have had in your life? +Any new and exciting things that you would like to share? +What is most important in life? +What Inspires You? +How lucky are you and why? +If you were a pizza deliveryman how would you benefit from scissors? +If you could sing one song on American Idol, what would it be? +Are you more of a hunter or a gatherer? +If you were on an island and could only bring 3 things, what would you bring? +If you were a box of cereal, what would you be and why? +Do you believe in Big Foot? +Why is a tennis ball fuzzy? +What is your least favorite thing about humanity? +How honest are you? +If you were 80 years old, what would you tell your children? +You're a new addition to the crayon box, what color would you be and why? +How does the internet work? +If there was a movie produced about your life, who would play you, and why? +What's the color of money? +What was the last gift you gave someone? +What is the funniest thing that has happened to you recently? +Have you ever been on a boat? diff --git a/Code/irc/run.sh b/Code/irc/run.sh new file mode 100755 index 0000000..dc98a46 --- /dev/null +++ b/Code/irc/run.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +nohup ./tilde_bot.py -s 127.0.0.1 -n tilde_bot -c \#bot_test >> log 2>> log & diff --git a/Code/irc/run_topic.sh b/Code/irc/run_topic.sh new file mode 100755 index 0000000..999ac75 --- /dev/null +++ b/Code/irc/run_topic.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +nohup ./topicbot.py -s 127.0.0.1 -n topicbot -c \#tildetown >> log 2>> log & +#nohup ./topicbot.py -s 127.0.0.1 -n topicbot -c \#bot_test >> log 2>> log & +#./topic_bot.py -s 127.0.0.1 -n topic_bot -c \#bot_test diff --git a/Code/irc/tilde_bot.py b/Code/irc/tilde_bot.py new file mode 100755 index 0000000..e449e2b --- /dev/null +++ b/Code/irc/tilde_bot.py @@ -0,0 +1,89 @@ +#!/usr/bin/python +# http://wiki.shellium.org/w/Writing_an_IRC_bot_in_Python + +# Import some necessary libraries. +import socket +import os +import sys +from optparse import OptionParser + +import get_users +import mentions +import formatter + +parser = OptionParser() + +parser.add_option("-s", "--server", dest="server", default='127.0.0.1', + help="the server to connect to", metavar="SERVER") +parser.add_option("-c", "--channel", dest="channel", default='#bot_test', + help="the channel to join", metavar="CHANNEL") +parser.add_option("-n", "--nick", dest="nick", default='tilde_bot', + help="the nick to use", metavar="NICK") + +(options, args) = parser.parse_args() + +def ping(): + ircsock.send("PONG :pingis\n") + +def sendmsg(chan , msg): + ircsock.send("PRIVMSG "+ chan +" :"+ msg +"\n") + +def joinchan(chan): + ircsock.send("JOIN "+ chan +"\n") + +def hello(): + ircsock.send("PRIVMSG "+ channel +" :Hello!\n") + +def tilde(channel, user, time): + #h = os.popen("haiku").read().replace("\n", " // ") + msg = time + ":" + user + print msg + ircsock.send("PRIVMSG "+ channel +" :" + msg + "\n") + +def connect(server, channel, botnick): + ircsock.connect((server, 6667)) + ircsock.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This bot is a result of a tutoral covered on http://shellium.org/wiki.\n") # user authentication + ircsock.send("NICK "+ botnick +"\n") + + joinchan(channel) + +def get_user_from_message(msg): + try: + i1 = msg.index(':') + 1 + i2 = msg.index('!') + return msg[i1:i2] + except ValueError: + return "" + +def listen(): + while 1: + + ircmsg = ircsock.recv(2048) + ircmsg = ircmsg.strip('\n\r') + + if ircmsg.find("PING :") != -1: + ping() + + formatted = formatter.format_message(ircmsg) + + if "" == formatted: + continue + + print formatted + + split = formatted.split("\t") + time = split[0] + user = split[1] + messageText = split[2] + + if ircmsg.find(":!tilde") != -1: + tilde(options.channel, user, time) + + if ircmsg.find("PING :") != -1: + ping() + + sys.stdout.flush() + +ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +connect(options.server, options.channel, options.nick) +listen() diff --git a/Code/irc/topicbot.py b/Code/irc/topicbot.py new file mode 100755 index 0000000..cac5055 --- /dev/null +++ b/Code/irc/topicbot.py @@ -0,0 +1,187 @@ +#!/usr/bin/python +# http://wiki.shellium.org/w/Writing_an_IRC_bot_in_Python + +# Import some necessary libraries. +import socket +import os +import sys +from optparse import OptionParser +import fileinput +import random + +import formatter +import get_users +import mentions +import pretty_date +import inflect + +parser = OptionParser() + +parser.add_option("-s", "--server", dest="server", default='127.0.0.1', + help="the server to connect to", metavar="SERVER") +parser.add_option("-c", "--channel", dest="channel", default='#bot_test', + help="the channel to join", metavar="CHANNEL") +parser.add_option("-n", "--nick", dest="nick", default='topicbot', + help="the nick to use", metavar="NICK") + +(options, args) = parser.parse_args() + +p = inflect.engine() + +def ping(): + ircsock.send("PONG :pingis\n") + +def sendmsg(chan , msg): + ircsock.send("PRIVMSG "+ chan +" :"+ msg +"\n") + +def joinchan(chan): + ircsock.send("JOIN "+ chan +"\n") + +def hello(): + ircsock.send("PRIVMSG "+ channel +" :Hello!\n") + +def get_topic(channel, user, time): + #topic scores are saved as &^%&^% + with open("topicscores.txt", "r") as scorefile: + scores = scorefile.readlines() + userscore = 1 + found = False + with open("topicscores.txt", "w") as scorefile: + for idx,score in enumerate(scores): + data = score.strip("\n").split("&^%") + if(data[0] == user): + found = True + userscore = int(data[1])+1 + scores[idx] = data[0] + "&^%" + str(userscore) + "&^%" + data[2] + "\n" + scorefile.writelines(scores) + if(not found): + scorefile.write(user + "&^%1&^%0") + + + with open("topics_" + channel + ".txt", "r") as topics: + topic = topics.readlines()[-1].strip("\n").split("&^%", 3) + ircsock.send("PRIVMSG "+ channel +" :I've told you " + p.number_to_words(userscore) + " times! It's \"" + topic[2] + "\" (Set by " + topic[1] + " " + pretty_date.pretty_date(int(topic[0])) + ")\n") + +def count_topic(channel, user, time, msg): + with open("topics_" + channel + ".txt", "a") as topics: + topics.write(time + "&^%" + user + "&^%" + msg + "\n") + with open("topicscores.txt", "r") as scorefile: + scores = scorefile.readlines() + userscore = 1 + found = False + with open("topicscores.txt", "w") as scorefile: + for idx,score in enumerate(scores): + data = score.strip("\n").split("&^%") + if(data[0] == user): + found = True + userscore = int(data[2])+1 + scores[idx] = data[0] + "&^%" + data[1] + "&^%" + str(userscore) + "\n" + scorefile.writelines(scores) + if(not found): + scorefile.write(user + "&^%0&^%1") + ircsock.send("PRIVMSG "+ channel +" :" + user + " has changed the topic " + p.number_to_words(userscore) + " times!\n") + +def set_topic(channel, user, time, msg): + ircsock.send("TOPIC "+ channel +" :" + msg + "\n") + count_topic(channel, user, time, msg) + +def random_topic(channel, user, time): + with open("randomtopics.txt") as rtopics: + msg = random.choice(rtopics.readlines()).strip("\n") + set_topic(channel, user, time, msg) + +def rollcall(channel): + ircsock.send("PRIVMSG "+ channel +" :topicbot reporting! I respond to !topic !settopic !randomtopic !thistory\n") + +def topic_score(): + ircsock.send("PRIVMSG "+ channel +" :Not implemented yet") + +def topic_scores(): + ircsock.send("PRIVMSG "+ channel +" :Not implemented yet") + +def topic_history(channel, user, count): + try: + iCount = int(count.split()[1]) + except ValueError: + iCount = 3 + if(iCount > 10): + iCount = 10 + if(iCount < 1): + iCount = 3 + with open("topics_" + channel + ".txt", "r") as topicsfile: + #topics = topicsfile.readlines()[-iCount:].reverse() + ircsock.send("PRIVMSG "+ channel +" :Ok, here were the last " + p.number_to_words(iCount) + " topics\n") + for idx,topic in enumerate(reversed(topicsfile.readlines()[-iCount:])): + topic = topic.strip("\n").split("&^%", 3) + ircsock.send("PRIVMSG "+ channel +" :" + str(idx+1) + ": \"" + topic[2] + "\" (Set by " + topic[1] + " " + pretty_date.pretty_date(int(topic[0])) + ")\n") + + +def connect(server, channel, botnick): + ircsock.connect((server, 6667)) + ircsock.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This bot is a result of a tutoral covered on http://shellium.org/wiki.\n") # user authentication + ircsock.send("NICK "+ botnick +"\n") + + joinchan(channel) + +def get_user_from_message(msg): + try: + i1 = msg.index(':') + 1 + i2 = msg.index('!') + return msg[i1:i2] + except ValueError: + return "" + +def listen(): + while 1: + + ircmsg = ircsock.recv(2048) + ircmsg = ircmsg.strip('\n\r') + + if ircmsg.find("PING :") != -1: + ping() + + formatted = formatter.format_message(ircmsg) + + if "" == formatted: + continue + + # print formatted + + split = formatted.split("\t") + time = split[0] + user = split[1] + command = split[2] + channel = split[3] + messageText = split[4] + + if(command == "TOPIC" and user != options.nick): + count_topic(channel,user, time, messageText) + + if ircmsg.find(":!topic") != -1: + get_topic(channel, user, time) + + if ircmsg.find(":!settopic") != -1: + set_topic(channel, user, time, messageText[10:]) + + if ircmsg.find(":!tscores") != -1: + topic_scores() + elif ircmsg.find(":!tscores") != -1: + topic_score() + + if ircmsg.find(":!randomtopic") != -1: + random_topic(channel, user, time) + + if ircmsg.find(":!thistory") != -1: + topic_history(channel, user, messageText) + + if ircmsg.find(":!rollcall") != -1: + rollcall(channel) + + if ircmsg.find("PING :") != -1: + ping() + + sys.stdout.flush() + +ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +connect(options.server, options.channel, options.nick) +listen() diff --git a/Code/irc/topics.txt b/Code/irc/topics.txt new file mode 100644 index 0000000..e69de29 diff --git a/Code/irc/topicscores.txt b/Code/irc/topicscores.txt new file mode 100644 index 0000000..177538d --- /dev/null +++ b/Code/irc/topicscores.txt @@ -0,0 +1,5 @@ +krowbar&^%20&^%13 +um&^%11&^%8 +kc&^%0&^%10 +marcus&^%3&^%0 +khoi&^%1&^%0 \ No newline at end of file diff --git a/Code/ruby/.gem b/Code/ruby/.gem new file mode 100644 index 0000000..d82f6b7 --- /dev/null +++ b/Code/ruby/.gem @@ -0,0 +1 @@ +gem 'opal' diff --git a/Code/ruby/Grimoire b/Code/ruby/Grimoire new file mode 160000 index 0000000..bd995fa --- /dev/null +++ b/Code/ruby/Grimoire @@ -0,0 +1 @@ +Subproject commit bd995fa5d7a64c179e7c562bb05f75cac67d8036 diff --git a/ideas.txt b/ideas.txt new file mode 100644 index 0000000..3809d17 --- /dev/null +++ b/ideas.txt @@ -0,0 +1,7 @@ +TopicBot + - !settopic - sets the current topic + - !topic - prints the current topic + - Saves all topics set from !settopic to a text file along with a timestamp + and who set the topic + - On load, sets the last topic in the topics file as the current topic + - Current topic will time out after X hours (or just display the time) diff --git a/public_html/df/index.html b/public_html/df/index.html new file mode 100644 index 0000000..09a9a49 --- /dev/null +++ b/public_html/df/index.html @@ -0,0 +1,15 @@ + +tilde.town ~dorf fortress!! + + + +
+ +
+ +

it's the tilde.town dwarf fortress succession game!

+

sign up!!!!

+

drop ~jumblesale an email

+

strike the earth!

+ + diff --git a/public_html/index.html b/public_html/index.html new file mode 100644 index 0000000..a35d74f --- /dev/null +++ b/public_html/index.html @@ -0,0 +1,12 @@ + + +WIP + + +

I just clobbered my index.html file

+

New site some time soon

+ + diff --git a/public_html/json/data.json b/public_html/json/data.json new file mode 100644 index 0000000..fe7bc6a --- /dev/null +++ b/public_html/json/data.json @@ -0,0 +1,5 @@ +{ + "data1": "foo", + "data2": "bar", + "data3": ["foo","bar","baz"] +}; diff --git a/public_html/mission/index.html b/public_html/mission/index.html new file mode 100644 index 0000000..61ccc10 --- /dev/null +++ b/public_html/mission/index.html @@ -0,0 +1,15 @@ + + +Secret Mission Name Generator + + + + + +
+ + +

{{name}}

+
+ + diff --git a/public_html/mission/js/lodash.js b/public_html/mission/js/lodash.js new file mode 100644 index 0000000..d653e5a --- /dev/null +++ b/public_html/mission/js/lodash.js @@ -0,0 +1,6785 @@ +/** + * @license + * Lo-Dash 2.4.1 (Custom Build) + * Build: `lodash modern -o ./dist/lodash.js` + * Copyright 2012-2013 The Dojo Foundation + * Based on Underscore.js 1.5.2 + * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre ES5 environments */ + var undefined; + + /** Used to pool arrays and objects used internally */ + var arrayPool = [], + objectPool = []; + + /** Used to generate unique IDs */ + var idCounter = 0; + + /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ + var keyPrefix = +new Date + ''; + + /** Used as the size when optimizations are enabled for large arrays */ + var largeArraySize = 75; + + /** Used as the max size of the `arrayPool` and `objectPool` */ + var maxPoolSize = 40; + + /** Used to detect and test whitespace */ + var whitespace = ( + // whitespace + ' \t\x0B\f\xA0\ufeff' + + + // line terminators + '\n\r\u2028\u2029' + + + // unicode category "Zs" space separators + '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000' + ); + + /** Used to match empty string literals in compiled template source */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** + * Used to match ES6 template delimiters + * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match regexp flags from their coerced string values */ + var reFlags = /\w*$/; + + /** Used to detected named functions */ + var reFuncName = /^\s*function[ \n\r\t]+\w/; + + /** Used to match "interpolate" template delimiters */ + var reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match leading whitespace and zeros to be removed */ + var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)'); + + /** Used to ensure capturing order of template delimiters */ + var reNoMatch = /($^)/; + + /** Used to detect functions containing a `this` reference */ + var reThis = /\bthis\b/; + + /** Used to match unescaped characters in compiled string literals */ + var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; + + /** Used to assign default `context` object properties */ + var contextProps = [ + 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object', + 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', + 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify */ + var templateCounter = 0; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + /** Used to identify object classifications that `_.clone` supports */ + var cloneableClasses = {}; + cloneableClasses[funcClass] = false; + cloneableClasses[argsClass] = cloneableClasses[arrayClass] = + cloneableClasses[boolClass] = cloneableClasses[dateClass] = + cloneableClasses[numberClass] = cloneableClasses[objectClass] = + cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; + + /** Used as an internal `_.debounce` options object */ + var debounceOptions = { + 'leading': false, + 'maxWait': 0, + 'trailing': false + }; + + /** Used as the property descriptor for `__bindData__` */ + var descriptor = { + 'configurable': false, + 'enumerable': false, + 'value': null, + 'writable': false + }; + + /** Used to determine if values are of the language type Object */ + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + /** Used to escape characters for inclusion in compiled string literals */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\t': 't', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Used as a reference to the global object */ + var root = (objectTypes[typeof window] && window) || this; + + /** Detect free variable `exports` */ + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + + /** Detect free variable `module` */ + var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports` */ + var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; + + /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ + var freeGlobal = objectTypes[typeof global] && global; + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { + root = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + /** + * The base implementation of `_.indexOf` without support for binary searches + * or `fromIndex` constraints. + * + * @private + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value or `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + var index = (fromIndex || 0) - 1, + length = array ? array.length : 0; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * An implementation of `_.contains` for cache objects that mimics the return + * signature of `_.indexOf` by returning `0` if the value is found, else `-1`. + * + * @private + * @param {Object} cache The cache object to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns `0` if `value` is found, else `-1`. + */ + function cacheIndexOf(cache, value) { + var type = typeof value; + cache = cache.cache; + + if (type == 'boolean' || value == null) { + return cache[value] ? 0 : -1; + } + if (type != 'number' && type != 'string') { + type = 'object'; + } + var key = type == 'number' ? value : keyPrefix + value; + cache = (cache = cache[type]) && cache[key]; + + return type == 'object' + ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1) + : (cache ? 0 : -1); + } + + /** + * Adds a given value to the corresponding cache object. + * + * @private + * @param {*} value The value to add to the cache. + */ + function cachePush(value) { + var cache = this.cache, + type = typeof value; + + if (type == 'boolean' || value == null) { + cache[value] = true; + } else { + if (type != 'number' && type != 'string') { + type = 'object'; + } + var key = type == 'number' ? value : keyPrefix + value, + typeCache = cache[type] || (cache[type] = {}); + + if (type == 'object') { + (typeCache[key] || (typeCache[key] = [])).push(value); + } else { + typeCache[key] = true; + } + } + } + + /** + * Used by `_.max` and `_.min` as the default callback when a given + * collection is a string value. + * + * @private + * @param {string} value The character to inspect. + * @returns {number} Returns the code unit of given character. + */ + function charAtCallback(value) { + return value.charCodeAt(0); + } + + /** + * Used by `sortBy` to compare transformed `collection` elements, stable sorting + * them in ascending order. + * + * @private + * @param {Object} a The object to compare to `b`. + * @param {Object} b The object to compare to `a`. + * @returns {number} Returns the sort order indicator of `1` or `-1`. + */ + function compareAscending(a, b) { + var ac = a.criteria, + bc = b.criteria, + index = -1, + length = ac.length; + + while (++index < length) { + var value = ac[index], + other = bc[index]; + + if (value !== other) { + if (value > other || typeof value == 'undefined') { + return 1; + } + if (value < other || typeof other == 'undefined') { + return -1; + } + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to return the same value for + // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247 + // + // This also ensures a stable sort in V8 and other engines. + // See http://code.google.com/p/v8/issues/detail?id=90 + return a.index - b.index; + } + + /** + * Creates a cache object to optimize linear searches of large arrays. + * + * @private + * @param {Array} [array=[]] The array to search. + * @returns {null|Object} Returns the cache object or `null` if caching should not be used. + */ + function createCache(array) { + var index = -1, + length = array.length, + first = array[0], + mid = array[(length / 2) | 0], + last = array[length - 1]; + + if (first && typeof first == 'object' && + mid && typeof mid == 'object' && last && typeof last == 'object') { + return false; + } + var cache = getObject(); + cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false; + + var result = getObject(); + result.array = array; + result.cache = cache; + result.push = cachePush; + + while (++index < length) { + result.push(array[index]); + } + return result; + } + + /** + * Used by `template` to escape characters for inclusion in compiled + * string literals. + * + * @private + * @param {string} match The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(match) { + return '\\' + stringEscapes[match]; + } + + /** + * Gets an array from the array pool or creates a new one if the pool is empty. + * + * @private + * @returns {Array} The array from the pool. + */ + function getArray() { + return arrayPool.pop() || []; + } + + /** + * Gets an object from the object pool or creates a new one if the pool is empty. + * + * @private + * @returns {Object} The object from the pool. + */ + function getObject() { + return objectPool.pop() || { + 'array': null, + 'cache': null, + 'criteria': null, + 'false': false, + 'index': 0, + 'null': false, + 'number': null, + 'object': null, + 'push': null, + 'string': null, + 'true': false, + 'undefined': false, + 'value': null + }; + } + + /** + * Releases the given array back to the array pool. + * + * @private + * @param {Array} [array] The array to release. + */ + function releaseArray(array) { + array.length = 0; + if (arrayPool.length < maxPoolSize) { + arrayPool.push(array); + } + } + + /** + * Releases the given object back to the object pool. + * + * @private + * @param {Object} [object] The object to release. + */ + function releaseObject(object) { + var cache = object.cache; + if (cache) { + releaseObject(cache); + } + object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null; + if (objectPool.length < maxPoolSize) { + objectPool.push(object); + } + } + + /** + * Slices the `collection` from the `start` index up to, but not including, + * the `end` index. + * + * Note: This function is used instead of `Array#slice` to support node lists + * in IE < 9 and to ensure dense arrays are returned. + * + * @private + * @param {Array|Object|string} collection The collection to slice. + * @param {number} start The start index. + * @param {number} end The end index. + * @returns {Array} Returns the new array. + */ + function slice(array, start, end) { + start || (start = 0); + if (typeof end == 'undefined') { + end = array ? array.length : 0; + } + var index = -1, + length = end - start || 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = array[start + index]; + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new `lodash` function using the given context object. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Object} [context=root] The context object. + * @returns {Function} Returns the `lodash` function. + */ + function runInContext(context) { + // Avoid issues with some ES3 environments that attempt to use values, named + // after built-in constructors like `Object`, for the creation of literals. + // ES5 clears this up by stating that literals must use built-in constructors. + // See http://es5.github.io/#x11.1.5. + context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; + + /** Native constructor references */ + var Array = context.Array, + Boolean = context.Boolean, + Date = context.Date, + Function = context.Function, + Math = context.Math, + Number = context.Number, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** + * Used for `Array` method references. + * + * Normally `Array.prototype` would suffice, however, using an array literal + * avoids issues in Narwhal. + */ + var arrayRef = []; + + /** Used for native method references */ + var objectProto = Object.prototype; + + /** Used to restore the original `_` reference in `noConflict` */ + var oldDash = context._; + + /** Used to resolve the internal [[Class]] of values */ + var toString = objectProto.toString; + + /** Used to detect if a method is native */ + var reNative = RegExp('^' + + String(toString) + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/toString| for [^\]]+/g, '.*?') + '$' + ); + + /** Native method shortcuts */ + var ceil = Math.ceil, + clearTimeout = context.clearTimeout, + floor = Math.floor, + fnToString = Function.prototype.toString, + getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, + hasOwnProperty = objectProto.hasOwnProperty, + push = arrayRef.push, + setTimeout = context.setTimeout, + splice = arrayRef.splice, + unshift = arrayRef.unshift; + + /** Used to set meta data on functions */ + var defineProperty = (function() { + // IE 8 only accepts DOM elements + try { + var o = {}, + func = isNative(func = Object.defineProperty) && func, + result = func(o, o, o) && func; + } catch(e) { } + return result; + }()); + + /* Native method shortcuts for methods with the same name as other `lodash` methods */ + var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, + nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, + nativeIsFinite = context.isFinite, + nativeIsNaN = context.isNaN, + nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, + nativeMax = Math.max, + nativeMin = Math.min, + nativeParseInt = context.parseInt, + nativeRandom = Math.random; + + /** Used to lookup a built-in constructor by [[Class]] */ + var ctorByClass = {}; + ctorByClass[arrayClass] = Array; + ctorByClass[boolClass] = Boolean; + ctorByClass[dateClass] = Date; + ctorByClass[funcClass] = Function; + ctorByClass[objectClass] = Object; + ctorByClass[numberClass] = Number; + ctorByClass[regexpClass] = RegExp; + ctorByClass[stringClass] = String; + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps the given value to enable intuitive + * method chaining. + * + * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: + * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, + * and `unshift` + * + * Chaining is supported in custom builds as long as the `value` method is + * implicitly or explicitly included in the build. + * + * The chainable wrapper functions are: + * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, + * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`, + * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, + * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, + * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, + * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, + * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, + * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, + * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`, + * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`, + * and `zip` + * + * The non-chainable wrapper functions are: + * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`, + * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`, + * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, + * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, + * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, + * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`, + * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`, + * `template`, `unescape`, `uniqueId`, and `value` + * + * The wrapper functions `first` and `last` return wrapped values when `n` is + * provided, otherwise they return unwrapped values. + * + * Explicit chaining can be enabled by using the `_.chain` method. + * + * @name _ + * @constructor + * @category Chaining + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns a `lodash` instance. + * @example + * + * var wrapped = _([1, 2, 3]); + * + * // returns an unwrapped value + * wrapped.reduce(function(sum, num) { + * return sum + num; + * }); + * // => 6 + * + * // returns a wrapped value + * var squares = wrapped.map(function(num) { + * return num * num; + * }); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor + return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__')) + ? value + : new lodashWrapper(value); + } + + /** + * A fast path for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap in a `lodash` instance. + * @param {boolean} chainAll A flag to enable chaining for all methods + * @returns {Object} Returns a `lodash` instance. + */ + function lodashWrapper(value, chainAll) { + this.__chain__ = !!chainAll; + this.__wrapped__ = value; + } + // ensure `new lodashWrapper` is an instance of `lodash` + lodashWrapper.prototype = lodash.prototype; + + /** + * An object used to flag environments features. + * + * @static + * @memberOf _ + * @type Object + */ + var support = lodash.support = {}; + + /** + * Detect if functions can be decompiled by `Function#toString` + * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps). + * + * @memberOf _.support + * @type boolean + */ + support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext); + + /** + * Detect if `Function#name` is supported (all but IE). + * + * @memberOf _.support + * @type boolean + */ + support.funcNames = typeof Function.name == 'string'; + + /** + * By default, the template delimiters used by Lo-Dash are similar to those in + * embedded Ruby (ERB). Change the following template settings to use alternative + * delimiters. + * + * @static + * @memberOf _ + * @type Object + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'escape': /<%-([\s\S]+?)%>/g, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'evaluate': /<%([\s\S]+?)%>/g, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type string + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type Object + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type Function + */ + '_': lodash + } + }; + + /*--------------------------------------------------------------------------*/ + + /** + * The base implementation of `_.bind` that creates the bound function and + * sets its meta data. + * + * @private + * @param {Array} bindData The bind data array. + * @returns {Function} Returns the new bound function. + */ + function baseBind(bindData) { + var func = bindData[0], + partialArgs = bindData[2], + thisArg = bindData[4]; + + function bound() { + // `Function#bind` spec + // http://es5.github.io/#x15.3.4.5 + if (partialArgs) { + // avoid `arguments` object deoptimizations by using `slice` instead + // of `Array.prototype.slice.call` and not assigning `arguments` to a + // variable as a ternary expression + var args = slice(partialArgs); + push.apply(args, arguments); + } + // mimic the constructor's `return` behavior + // http://es5.github.io/#x13.2.2 + if (this instanceof bound) { + // ensure `new bound` is an instance of `func` + var thisBinding = baseCreate(func.prototype), + result = func.apply(thisBinding, args || arguments); + return isObject(result) ? result : thisBinding; + } + return func.apply(thisArg, args || arguments); + } + setBindData(bound, bindData); + return bound; + } + + /** + * The base implementation of `_.clone` without argument juggling or support + * for `thisArg` binding. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} [isDeep=false] Specify a deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates clones with source counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, isDeep, callback, stackA, stackB) { + if (callback) { + var result = callback(value); + if (typeof result != 'undefined') { + return result; + } + } + // inspect [[Class]] + var isObj = isObject(value); + if (isObj) { + var className = toString.call(value); + if (!cloneableClasses[className]) { + return value; + } + var ctor = ctorByClass[className]; + switch (className) { + case boolClass: + case dateClass: + return new ctor(+value); + + case numberClass: + case stringClass: + return new ctor(value); + + case regexpClass: + result = ctor(value.source, reFlags.exec(value)); + result.lastIndex = value.lastIndex; + return result; + } + } else { + return value; + } + var isArr = isArray(value); + if (isDeep) { + // check for circular references and return corresponding clone + var initedStack = !stackA; + stackA || (stackA = getArray()); + stackB || (stackB = getArray()); + + var length = stackA.length; + while (length--) { + if (stackA[length] == value) { + return stackB[length]; + } + } + result = isArr ? ctor(value.length) : {}; + } + else { + result = isArr ? slice(value) : assign({}, value); + } + // add array properties assigned by `RegExp#exec` + if (isArr) { + if (hasOwnProperty.call(value, 'index')) { + result.index = value.index; + } + if (hasOwnProperty.call(value, 'input')) { + result.input = value.input; + } + } + // exit for shallow clone + if (!isDeep) { + return result; + } + // add the source value to the stack of traversed objects + // and associate it with its clone + stackA.push(value); + stackB.push(result); + + // recursively populate clone (susceptible to call stack limits) + (isArr ? forEach : forOwn)(value, function(objValue, key) { + result[key] = baseClone(objValue, isDeep, callback, stackA, stackB); + }); + + if (initedStack) { + releaseArray(stackA); + releaseArray(stackB); + } + return result; + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ + function baseCreate(prototype, properties) { + return isObject(prototype) ? nativeCreate(prototype) : {}; + } + // fallback for browsers without `Object.create` + if (!nativeCreate) { + baseCreate = (function() { + function Object() {} + return function(prototype) { + if (isObject(prototype)) { + Object.prototype = prototype; + var result = new Object; + Object.prototype = null; + } + return result || context.Object(); + }; + }()); + } + + /** + * The base implementation of `_.createCallback` without support for creating + * "_.pluck" or "_.where" style callbacks. + * + * @private + * @param {*} [func=identity] The value to convert to a callback. + * @param {*} [thisArg] The `this` binding of the created callback. + * @param {number} [argCount] The number of arguments the callback accepts. + * @returns {Function} Returns a callback function. + */ + function baseCreateCallback(func, thisArg, argCount) { + if (typeof func != 'function') { + return identity; + } + // exit early for no `thisArg` or already bound by `Function#bind` + if (typeof thisArg == 'undefined' || !('prototype' in func)) { + return func; + } + var bindData = func.__bindData__; + if (typeof bindData == 'undefined') { + if (support.funcNames) { + bindData = !func.name; + } + bindData = bindData || !support.funcDecomp; + if (!bindData) { + var source = fnToString.call(func); + if (!support.funcNames) { + bindData = !reFuncName.test(source); + } + if (!bindData) { + // checks if `func` references the `this` keyword and stores the result + bindData = reThis.test(source); + setBindData(func, bindData); + } + } + } + // exit early if there are no `this` references or `func` is bound + if (bindData === false || (bindData !== true && bindData[1] & 1)) { + return func; + } + switch (argCount) { + case 1: return function(value) { + return func.call(thisArg, value); + }; + case 2: return function(a, b) { + return func.call(thisArg, a, b); + }; + case 3: return function(value, index, collection) { + return func.call(thisArg, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(thisArg, accumulator, value, index, collection); + }; + } + return bind(func, thisArg); + } + + /** + * The base implementation of `createWrapper` that creates the wrapper and + * sets its meta data. + * + * @private + * @param {Array} bindData The bind data array. + * @returns {Function} Returns the new function. + */ + function baseCreateWrapper(bindData) { + var func = bindData[0], + bitmask = bindData[1], + partialArgs = bindData[2], + partialRightArgs = bindData[3], + thisArg = bindData[4], + arity = bindData[5]; + + var isBind = bitmask & 1, + isBindKey = bitmask & 2, + isCurry = bitmask & 4, + isCurryBound = bitmask & 8, + key = func; + + function bound() { + var thisBinding = isBind ? thisArg : this; + if (partialArgs) { + var args = slice(partialArgs); + push.apply(args, arguments); + } + if (partialRightArgs || isCurry) { + args || (args = slice(arguments)); + if (partialRightArgs) { + push.apply(args, partialRightArgs); + } + if (isCurry && args.length < arity) { + bitmask |= 16 & ~32; + return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]); + } + } + args || (args = arguments); + if (isBindKey) { + func = thisBinding[key]; + } + if (this instanceof bound) { + thisBinding = baseCreate(func.prototype); + var result = func.apply(thisBinding, args); + return isObject(result) ? result : thisBinding; + } + return func.apply(thisBinding, args); + } + setBindData(bound, bindData); + return bound; + } + + /** + * The base implementation of `_.difference` that accepts a single array + * of values to exclude. + * + * @private + * @param {Array} array The array to process. + * @param {Array} [values] The array of values to exclude. + * @returns {Array} Returns a new array of filtered values. + */ + function baseDifference(array, values) { + var index = -1, + indexOf = getIndexOf(), + length = array ? array.length : 0, + isLarge = length >= largeArraySize && indexOf === baseIndexOf, + result = []; + + if (isLarge) { + var cache = createCache(values); + if (cache) { + indexOf = cacheIndexOf; + values = cache; + } else { + isLarge = false; + } + } + while (++index < length) { + var value = array[index]; + if (indexOf(values, value) < 0) { + result.push(value); + } + } + if (isLarge) { + releaseObject(values); + } + return result; + } + + /** + * The base implementation of `_.flatten` without support for callback + * shorthands or `thisArg` binding. + * + * @private + * @param {Array} array The array to flatten. + * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. + * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects. + * @param {number} [fromIndex=0] The index to start from. + * @returns {Array} Returns a new flattened array. + */ + function baseFlatten(array, isShallow, isStrict, fromIndex) { + var index = (fromIndex || 0) - 1, + length = array ? array.length : 0, + result = []; + + while (++index < length) { + var value = array[index]; + + if (value && typeof value == 'object' && typeof value.length == 'number' + && (isArray(value) || isArguments(value))) { + // recursively flatten arrays (susceptible to call stack limits) + if (!isShallow) { + value = baseFlatten(value, isShallow, isStrict); + } + var valIndex = -1, + valLength = value.length, + resIndex = result.length; + + result.length += valLength; + while (++valIndex < valLength) { + result[resIndex++] = value[valIndex]; + } + } else if (!isStrict) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.isEqual`, without support for `thisArg` binding, + * that allows partial "_.where" style comparisons. + * + * @private + * @param {*} a The value to compare. + * @param {*} b The other value to compare. + * @param {Function} [callback] The function to customize comparing values. + * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons. + * @param {Array} [stackA=[]] Tracks traversed `a` objects. + * @param {Array} [stackB=[]] Tracks traversed `b` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(a, b, callback, isWhere, stackA, stackB) { + // used to indicate that when comparing objects, `a` has at least the properties of `b` + if (callback) { + var result = callback(a, b); + if (typeof result != 'undefined') { + return !!result; + } + } + // exit early for identical values + if (a === b) { + // treat `+0` vs. `-0` as not equal + return a !== 0 || (1 / a == 1 / b); + } + var type = typeof a, + otherType = typeof b; + + // exit early for unlike primitive values + if (a === a && + !(a && objectTypes[type]) && + !(b && objectTypes[otherType])) { + return false; + } + // exit early for `null` and `undefined` avoiding ES3's Function#call behavior + // http://es5.github.io/#x15.3.4.4 + if (a == null || b == null) { + return a === b; + } + // compare [[Class]] names + var className = toString.call(a), + otherClass = toString.call(b); + + if (className == argsClass) { + className = objectClass; + } + if (otherClass == argsClass) { + otherClass = objectClass; + } + if (className != otherClass) { + return false; + } + switch (className) { + case boolClass: + case dateClass: + // coerce dates and booleans to numbers, dates to milliseconds and booleans + // to `1` or `0` treating invalid dates coerced to `NaN` as not equal + return +a == +b; + + case numberClass: + // treat `NaN` vs. `NaN` as equal + return (a != +a) + ? b != +b + // but treat `+0` vs. `-0` as not equal + : (a == 0 ? (1 / a == 1 / b) : a == +b); + + case regexpClass: + case stringClass: + // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) + // treat string primitives and their corresponding object instances as equal + return a == String(b); + } + var isArr = className == arrayClass; + if (!isArr) { + // unwrap any `lodash` wrapped values + var aWrapped = hasOwnProperty.call(a, '__wrapped__'), + bWrapped = hasOwnProperty.call(b, '__wrapped__'); + + if (aWrapped || bWrapped) { + return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB); + } + // exit for functions and DOM nodes + if (className != objectClass) { + return false; + } + // in older versions of Opera, `arguments` objects have `Array` constructors + var ctorA = a.constructor, + ctorB = b.constructor; + + // non `Object` object instances with different constructors are not equal + if (ctorA != ctorB && + !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && + ('constructor' in a && 'constructor' in b) + ) { + return false; + } + } + // assume cyclic structures are equal + // the algorithm for detecting cyclic structures is adapted from ES 5.1 + // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) + var initedStack = !stackA; + stackA || (stackA = getArray()); + stackB || (stackB = getArray()); + + var length = stackA.length; + while (length--) { + if (stackA[length] == a) { + return stackB[length] == b; + } + } + var size = 0; + result = true; + + // add `a` and `b` to the stack of traversed objects + stackA.push(a); + stackB.push(b); + + // recursively compare objects and arrays (susceptible to call stack limits) + if (isArr) { + // compare lengths to determine if a deep comparison is necessary + length = a.length; + size = b.length; + result = size == length; + + if (result || isWhere) { + // deep compare the contents, ignoring non-numeric properties + while (size--) { + var index = length, + value = b[size]; + + if (isWhere) { + while (index--) { + if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) { + break; + } + } + } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) { + break; + } + } + } + } + else { + // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` + // which, in this case, is more costly + forIn(b, function(value, key, b) { + if (hasOwnProperty.call(b, key)) { + // count the number of properties. + size++; + // deep compare each property value. + return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB)); + } + }); + + if (result && !isWhere) { + // ensure both objects have the same number of properties + forIn(a, function(value, key, a) { + if (hasOwnProperty.call(a, key)) { + // `size` will be `-1` if `a` has more properties than `b` + return (result = --size > -1); + } + }); + } + } + stackA.pop(); + stackB.pop(); + + if (initedStack) { + releaseArray(stackA); + releaseArray(stackB); + } + return result; + } + + /** + * The base implementation of `_.merge` without argument juggling or support + * for `thisArg` binding. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {Function} [callback] The function to customize merging properties. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates values with source counterparts. + */ + function baseMerge(object, source, callback, stackA, stackB) { + (isArray(source) ? forEach : forOwn)(source, function(source, key) { + var found, + isArr, + result = source, + value = object[key]; + + if (source && ((isArr = isArray(source)) || isPlainObject(source))) { + // avoid merging previously merged cyclic sources + var stackLength = stackA.length; + while (stackLength--) { + if ((found = stackA[stackLength] == source)) { + value = stackB[stackLength]; + break; + } + } + if (!found) { + var isShallow; + if (callback) { + result = callback(value, source); + if ((isShallow = typeof result != 'undefined')) { + value = result; + } + } + if (!isShallow) { + value = isArr + ? (isArray(value) ? value : []) + : (isPlainObject(value) ? value : {}); + } + // add `source` and associated `value` to the stack of traversed objects + stackA.push(source); + stackB.push(value); + + // recursively merge objects and arrays (susceptible to call stack limits) + if (!isShallow) { + baseMerge(value, source, callback, stackA, stackB); + } + } + } + else { + if (callback) { + result = callback(value, source); + if (typeof result == 'undefined') { + result = source; + } + } + if (typeof result != 'undefined') { + value = result; + } + } + object[key] = value; + }); + } + + /** + * The base implementation of `_.random` without argument juggling or support + * for returning floating-point numbers. + * + * @private + * @param {number} min The minimum possible value. + * @param {number} max The maximum possible value. + * @returns {number} Returns a random number. + */ + function baseRandom(min, max) { + return min + floor(nativeRandom() * (max - min + 1)); + } + + /** + * The base implementation of `_.uniq` without support for callback shorthands + * or `thisArg` binding. + * + * @private + * @param {Array} array The array to process. + * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. + * @param {Function} [callback] The function called per iteration. + * @returns {Array} Returns a duplicate-value-free array. + */ + function baseUniq(array, isSorted, callback) { + var index = -1, + indexOf = getIndexOf(), + length = array ? array.length : 0, + result = []; + + var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf, + seen = (callback || isLarge) ? getArray() : result; + + if (isLarge) { + var cache = createCache(seen); + indexOf = cacheIndexOf; + seen = cache; + } + while (++index < length) { + var value = array[index], + computed = callback ? callback(value, index, array) : value; + + if (isSorted + ? !index || seen[seen.length - 1] !== computed + : indexOf(seen, computed) < 0 + ) { + if (callback || isLarge) { + seen.push(computed); + } + result.push(value); + } + } + if (isLarge) { + releaseArray(seen.array); + releaseObject(seen); + } else if (callback) { + releaseArray(seen); + } + return result; + } + + /** + * Creates a function that aggregates a collection, creating an object composed + * of keys generated from the results of running each element of the collection + * through a callback. The given `setter` function sets the keys and values + * of the composed object. + * + * @private + * @param {Function} setter The setter function. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter) { + return function(collection, callback, thisArg) { + var result = {}; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + var value = collection[index]; + setter(result, value, callback(value, index, collection), collection); + } + } else { + forOwn(collection, function(value, key, collection) { + setter(result, value, callback(value, key, collection), collection); + }); + } + return result; + }; + } + + /** + * Creates a function that, when called, either curries or invokes `func` + * with an optional `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to reference. + * @param {number} bitmask The bitmask of method flags to compose. + * The bitmask may be composed of the following flags: + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` + * 8 - `_.curry` (bound) + * 16 - `_.partial` + * 32 - `_.partialRight` + * @param {Array} [partialArgs] An array of arguments to prepend to those + * provided to the new function. + * @param {Array} [partialRightArgs] An array of arguments to append to those + * provided to the new function. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new function. + */ + function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) { + var isBind = bitmask & 1, + isBindKey = bitmask & 2, + isCurry = bitmask & 4, + isCurryBound = bitmask & 8, + isPartial = bitmask & 16, + isPartialRight = bitmask & 32; + + if (!isBindKey && !isFunction(func)) { + throw new TypeError; + } + if (isPartial && !partialArgs.length) { + bitmask &= ~16; + isPartial = partialArgs = false; + } + if (isPartialRight && !partialRightArgs.length) { + bitmask &= ~32; + isPartialRight = partialRightArgs = false; + } + var bindData = func && func.__bindData__; + if (bindData && bindData !== true) { + // clone `bindData` + bindData = slice(bindData); + if (bindData[2]) { + bindData[2] = slice(bindData[2]); + } + if (bindData[3]) { + bindData[3] = slice(bindData[3]); + } + // set `thisBinding` is not previously bound + if (isBind && !(bindData[1] & 1)) { + bindData[4] = thisArg; + } + // set if previously bound but not currently (subsequent curried functions) + if (!isBind && bindData[1] & 1) { + bitmask |= 8; + } + // set curried arity if not yet set + if (isCurry && !(bindData[1] & 4)) { + bindData[5] = arity; + } + // append partial left arguments + if (isPartial) { + push.apply(bindData[2] || (bindData[2] = []), partialArgs); + } + // append partial right arguments + if (isPartialRight) { + unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs); + } + // merge flags + bindData[1] |= bitmask; + return createWrapper.apply(null, bindData); + } + // fast path for `_.bind` + var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper; + return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]); + } + + /** + * Used by `escape` to convert characters to HTML entities. + * + * @private + * @param {string} match The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeHtmlChar(match) { + return htmlEscapes[match]; + } + + /** + * Gets the appropriate "indexOf" function. If the `_.indexOf` method is + * customized, this method returns the custom method, otherwise it returns + * the `baseIndexOf` function. + * + * @private + * @returns {Function} Returns the "indexOf" function. + */ + function getIndexOf() { + var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result; + return result; + } + + /** + * Checks if `value` is a native function. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a native function, else `false`. + */ + function isNative(value) { + return typeof value == 'function' && reNative.test(value); + } + + /** + * Sets `this` binding data on a given function. + * + * @private + * @param {Function} func The function to set data on. + * @param {Array} value The data array to set. + */ + var setBindData = !defineProperty ? noop : function(func, value) { + descriptor.value = value; + defineProperty(func, '__bindData__', descriptor); + }; + + /** + * A fallback implementation of `isPlainObject` which checks if a given value + * is an object created by the `Object` constructor, assuming objects created + * by the `Object` constructor have no inherited enumerable properties and that + * there are no `Object.prototype` extensions. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + */ + function shimIsPlainObject(value) { + var ctor, + result; + + // avoid non Object objects, `arguments` objects, and DOM elements + if (!(value && toString.call(value) == objectClass) || + (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) { + return false; + } + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + forIn(value, function(value, key) { + result = key; + }); + return typeof result == 'undefined' || hasOwnProperty.call(value, result); + } + + /** + * Used by `unescape` to convert HTML entities to characters. + * + * @private + * @param {string} match The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + function unescapeHtmlChar(match) { + return htmlUnescapes[match]; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Checks if `value` is an `arguments` object. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`. + * @example + * + * (function() { return _.isArguments(arguments); })(1, 2, 3); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + return value && typeof value == 'object' && typeof value.length == 'number' && + toString.call(value) == argsClass || false; + } + + /** + * Checks if `value` is an array. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an array, else `false`. + * @example + * + * (function() { return _.isArray(arguments); })(); + * // => false + * + * _.isArray([1, 2, 3]); + * // => true + */ + var isArray = nativeIsArray || function(value) { + return value && typeof value == 'object' && typeof value.length == 'number' && + toString.call(value) == arrayClass || false; + }; + + /** + * A fallback implementation of `Object.keys` which produces an array of the + * given object's own enumerable property names. + * + * @private + * @type Function + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names. + */ + var shimKeys = function(object) { + var index, iterable = object, result = []; + if (!iterable) return result; + if (!(objectTypes[typeof object])) return result; + for (index in iterable) { + if (hasOwnProperty.call(iterable, index)) { + result.push(index); + } + } + return result + }; + + /** + * Creates an array composed of the own enumerable property names of an object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names. + * @example + * + * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); + * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) + */ + var keys = !nativeKeys ? shimKeys : function(object) { + if (!isObject(object)) { + return []; + } + return nativeKeys(object); + }; + + /** + * Used to convert characters to HTML entities: + * + * Though the `>` character is escaped for symmetry, characters like `>` and `/` + * don't require escaping in HTML and have no special meaning unless they're part + * of a tag or an unquoted attribute value. + * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") + */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to convert HTML entities to characters */ + var htmlUnescapes = invert(htmlEscapes); + + /** Used to match HTML entities and HTML characters */ + var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'), + reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g'); + + /*--------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object. Subsequent sources will overwrite property assignments of previous + * sources. If a callback is provided it will be executed to produce the + * assigned values. The callback is bound to `thisArg` and invoked with two + * arguments; (objectValue, sourceValue). + * + * @static + * @memberOf _ + * @type Function + * @alias extend + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param {Function} [callback] The function to customize assigning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the destination object. + * @example + * + * _.assign({ 'name': 'fred' }, { 'employer': 'slate' }); + * // => { 'name': 'fred', 'employer': 'slate' } + * + * var defaults = _.partialRight(_.assign, function(a, b) { + * return typeof a == 'undefined' ? b : a; + * }); + * + * var object = { 'name': 'barney' }; + * defaults(object, { 'name': 'fred', 'employer': 'slate' }); + * // => { 'name': 'barney', 'employer': 'slate' } + */ + var assign = function(object, source, guard) { + var index, iterable = object, result = iterable; + if (!iterable) return result; + var args = arguments, + argsIndex = 0, + argsLength = typeof guard == 'number' ? 2 : args.length; + if (argsLength > 3 && typeof args[argsLength - 2] == 'function') { + var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2); + } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') { + callback = args[--argsLength]; + } + while (++argsIndex < argsLength) { + iterable = args[argsIndex]; + if (iterable && objectTypes[typeof iterable]) { + var ownIndex = -1, + ownProps = objectTypes[typeof iterable] && keys(iterable), + length = ownProps ? ownProps.length : 0; + + while (++ownIndex < length) { + index = ownProps[ownIndex]; + result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]; + } + } + } + return result + }; + + /** + * Creates a clone of `value`. If `isDeep` is `true` nested objects will also + * be cloned, otherwise they will be assigned by reference. If a callback + * is provided it will be executed to produce the cloned values. If the + * callback returns `undefined` cloning will be handled by the method instead. + * The callback is bound to `thisArg` and invoked with one argument; (value). + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to clone. + * @param {boolean} [isDeep=false] Specify a deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the cloned value. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * var shallow = _.clone(characters); + * shallow[0] === characters[0]; + * // => true + * + * var deep = _.clone(characters, true); + * deep[0] === characters[0]; + * // => false + * + * _.mixin({ + * 'clone': _.partialRight(_.clone, function(value) { + * return _.isElement(value) ? value.cloneNode(false) : undefined; + * }) + * }); + * + * var clone = _.clone(document.body); + * clone.childNodes.length; + * // => 0 + */ + function clone(value, isDeep, callback, thisArg) { + // allows working with "Collections" methods without using their `index` + // and `collection` arguments for `isDeep` and `callback` + if (typeof isDeep != 'boolean' && isDeep != null) { + thisArg = callback; + callback = isDeep; + isDeep = false; + } + return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); + } + + /** + * Creates a deep clone of `value`. If a callback is provided it will be + * executed to produce the cloned values. If the callback returns `undefined` + * cloning will be handled by the method instead. The callback is bound to + * `thisArg` and invoked with one argument; (value). + * + * Note: This method is loosely based on the structured clone algorithm. Functions + * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and + * objects created by constructors other than `Object` are cloned to plain `Object` objects. + * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the deep cloned value. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * var deep = _.cloneDeep(characters); + * deep[0] === characters[0]; + * // => false + * + * var view = { + * 'label': 'docs', + * 'node': element + * }; + * + * var clone = _.cloneDeep(view, function(value) { + * return _.isElement(value) ? value.cloneNode(true) : undefined; + * }); + * + * clone.node == view.node; + * // => false + */ + function cloneDeep(value, callback, thisArg) { + return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); + } + + /** + * Creates an object that inherits from the given `prototype` object. If a + * `properties` object is provided its own enumerable properties are assigned + * to the created object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties ? assign(result, properties) : result; + } + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object for all destination properties that resolve to `undefined`. Once a + * property is set, additional defaults of the same property will be ignored. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param- {Object} [guard] Allows working with `_.reduce` without using its + * `key` and `object` arguments as sources. + * @returns {Object} Returns the destination object. + * @example + * + * var object = { 'name': 'barney' }; + * _.defaults(object, { 'name': 'fred', 'employer': 'slate' }); + * // => { 'name': 'barney', 'employer': 'slate' } + */ + var defaults = function(object, source, guard) { + var index, iterable = object, result = iterable; + if (!iterable) return result; + var args = arguments, + argsIndex = 0, + argsLength = typeof guard == 'number' ? 2 : args.length; + while (++argsIndex < argsLength) { + iterable = args[argsIndex]; + if (iterable && objectTypes[typeof iterable]) { + var ownIndex = -1, + ownProps = objectTypes[typeof iterable] && keys(iterable), + length = ownProps ? ownProps.length : 0; + + while (++ownIndex < length) { + index = ownProps[ownIndex]; + if (typeof result[index] == 'undefined') result[index] = iterable[index]; + } + } + } + return result + }; + + /** + * This method is like `_.findIndex` except that it returns the key of the + * first element that passes the callback check, instead of the element itself. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to search. + * @param {Function|Object|string} [callback=identity] The function called per + * iteration. If a property name or object is provided it will be used to + * create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {string|undefined} Returns the key of the found element, else `undefined`. + * @example + * + * var characters = { + * 'barney': { 'age': 36, 'blocked': false }, + * 'fred': { 'age': 40, 'blocked': true }, + * 'pebbles': { 'age': 1, 'blocked': false } + * }; + * + * _.findKey(characters, function(chr) { + * return chr.age < 40; + * }); + * // => 'barney' (property order is not guaranteed across environments) + * + * // using "_.where" callback shorthand + * _.findKey(characters, { 'age': 1 }); + * // => 'pebbles' + * + * // using "_.pluck" callback shorthand + * _.findKey(characters, 'blocked'); + * // => 'fred' + */ + function findKey(object, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + forOwn(object, function(value, key, object) { + if (callback(value, key, object)) { + result = key; + return false; + } + }); + return result; + } + + /** + * This method is like `_.findKey` except that it iterates over elements + * of a `collection` in the opposite order. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to search. + * @param {Function|Object|string} [callback=identity] The function called per + * iteration. If a property name or object is provided it will be used to + * create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {string|undefined} Returns the key of the found element, else `undefined`. + * @example + * + * var characters = { + * 'barney': { 'age': 36, 'blocked': true }, + * 'fred': { 'age': 40, 'blocked': false }, + * 'pebbles': { 'age': 1, 'blocked': true } + * }; + * + * _.findLastKey(characters, function(chr) { + * return chr.age < 40; + * }); + * // => returns `pebbles`, assuming `_.findKey` returns `barney` + * + * // using "_.where" callback shorthand + * _.findLastKey(characters, { 'age': 40 }); + * // => 'fred' + * + * // using "_.pluck" callback shorthand + * _.findLastKey(characters, 'blocked'); + * // => 'pebbles' + */ + function findLastKey(object, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + forOwnRight(object, function(value, key, object) { + if (callback(value, key, object)) { + result = key; + return false; + } + }); + return result; + } + + /** + * Iterates over own and inherited enumerable properties of an object, + * executing the callback for each property. The callback is bound to `thisArg` + * and invoked with three arguments; (value, key, object). Callbacks may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * Shape.prototype.move = function(x, y) { + * this.x += x; + * this.y += y; + * }; + * + * _.forIn(new Shape, function(value, key) { + * console.log(key); + * }); + * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments) + */ + var forIn = function(collection, callback, thisArg) { + var index, iterable = collection, result = iterable; + if (!iterable) return result; + if (!objectTypes[typeof iterable]) return result; + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + for (index in iterable) { + if (callback(iterable[index], index, collection) === false) return result; + } + return result + }; + + /** + * This method is like `_.forIn` except that it iterates over elements + * of a `collection` in the opposite order. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * Shape.prototype.move = function(x, y) { + * this.x += x; + * this.y += y; + * }; + * + * _.forInRight(new Shape, function(value, key) { + * console.log(key); + * }); + * // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move' + */ + function forInRight(object, callback, thisArg) { + var pairs = []; + + forIn(object, function(value, key) { + pairs.push(key, value); + }); + + var length = pairs.length; + callback = baseCreateCallback(callback, thisArg, 3); + while (length--) { + if (callback(pairs[length--], pairs[length], object) === false) { + break; + } + } + return object; + } + + /** + * Iterates over own enumerable properties of an object, executing the callback + * for each property. The callback is bound to `thisArg` and invoked with three + * arguments; (value, key, object). Callbacks may exit iteration early by + * explicitly returning `false`. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + * console.log(key); + * }); + * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) + */ + var forOwn = function(collection, callback, thisArg) { + var index, iterable = collection, result = iterable; + if (!iterable) return result; + if (!objectTypes[typeof iterable]) return result; + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + var ownIndex = -1, + ownProps = objectTypes[typeof iterable] && keys(iterable), + length = ownProps ? ownProps.length : 0; + + while (++ownIndex < length) { + index = ownProps[ownIndex]; + if (callback(iterable[index], index, collection) === false) return result; + } + return result + }; + + /** + * This method is like `_.forOwn` except that it iterates over elements + * of a `collection` in the opposite order. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + * console.log(key); + * }); + * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length' + */ + function forOwnRight(object, callback, thisArg) { + var props = keys(object), + length = props.length; + + callback = baseCreateCallback(callback, thisArg, 3); + while (length--) { + var key = props[length]; + if (callback(object[key], key, object) === false) { + break; + } + } + return object; + } + + /** + * Creates a sorted array of property names of all enumerable properties, + * own and inherited, of `object` that have function values. + * + * @static + * @memberOf _ + * @alias methods + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property names that have function values. + * @example + * + * _.functions(_); + * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] + */ + function functions(object) { + var result = []; + forIn(object, function(value, key) { + if (isFunction(value)) { + result.push(key); + } + }); + return result.sort(); + } + + /** + * Checks if the specified property name exists as a direct property of `object`, + * instead of an inherited property. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @param {string} key The name of the property to check. + * @returns {boolean} Returns `true` if key is a direct property, else `false`. + * @example + * + * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); + * // => true + */ + function has(object, key) { + return object ? hasOwnProperty.call(object, key) : false; + } + + /** + * Creates an object composed of the inverted keys and values of the given object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to invert. + * @returns {Object} Returns the created inverted object. + * @example + * + * _.invert({ 'first': 'fred', 'second': 'barney' }); + * // => { 'fred': 'first', 'barney': 'second' } + */ + function invert(object) { + var index = -1, + props = keys(object), + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index]; + result[object[key]] = key; + } + return result; + } + + /** + * Checks if `value` is a boolean value. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`. + * @example + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + value && typeof value == 'object' && toString.call(value) == boolClass || false; + } + + /** + * Checks if `value` is a date. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a date, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + */ + function isDate(value) { + return value && typeof value == 'object' && toString.call(value) == dateClass || false; + } + + /** + * Checks if `value` is a DOM element. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + */ + function isElement(value) { + return value && value.nodeType === 1 || false; + } + + /** + * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a + * length of `0` and objects with no own enumerable properties are considered + * "empty". + * + * @static + * @memberOf _ + * @category Objects + * @param {Array|Object|string} value The value to inspect. + * @returns {boolean} Returns `true` if the `value` is empty, else `false`. + * @example + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({}); + * // => true + * + * _.isEmpty(''); + * // => true + */ + function isEmpty(value) { + var result = true; + if (!value) { + return result; + } + var className = toString.call(value), + length = value.length; + + if ((className == arrayClass || className == stringClass || className == argsClass ) || + (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { + return !length; + } + forOwn(value, function() { + return (result = false); + }); + return result; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent to each other. If a callback is provided it will be executed + * to compare values. If the callback returns `undefined` comparisons will + * be handled by the method instead. The callback is bound to `thisArg` and + * invoked with two arguments; (a, b). + * + * @static + * @memberOf _ + * @category Objects + * @param {*} a The value to compare. + * @param {*} b The other value to compare. + * @param {Function} [callback] The function to customize comparing values. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'name': 'fred' }; + * var copy = { 'name': 'fred' }; + * + * object == copy; + * // => false + * + * _.isEqual(object, copy); + * // => true + * + * var words = ['hello', 'goodbye']; + * var otherWords = ['hi', 'goodbye']; + * + * _.isEqual(words, otherWords, function(a, b) { + * var reGreet = /^(?:hello|hi)$/i, + * aGreet = _.isString(a) && reGreet.test(a), + * bGreet = _.isString(b) && reGreet.test(b); + * + * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; + * }); + * // => true + */ + function isEqual(a, b, callback, thisArg) { + return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2)); + } + + /** + * Checks if `value` is, or can be coerced to, a finite number. + * + * Note: This is not the same as native `isFinite` which will return true for + * booleans and empty strings. See http://es5.github.io/#x15.1.2.5. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is finite, else `false`. + * @example + * + * _.isFinite(-101); + * // => true + * + * _.isFinite('10'); + * // => true + * + * _.isFinite(true); + * // => false + * + * _.isFinite(''); + * // => false + * + * _.isFinite(Infinity); + * // => false + */ + function isFinite(value) { + return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); + } + + /** + * Checks if `value` is a function. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + */ + function isFunction(value) { + return typeof value == 'function'; + } + + /** + * Checks if `value` is the language type of Object. + * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(1); + * // => false + */ + function isObject(value) { + // check if the value is the ECMAScript language type of Object + // http://es5.github.io/#x8 + // and avoid a V8 bug + // http://code.google.com/p/v8/issues/detail?id=2291 + return !!(value && objectTypes[typeof value]); + } + + /** + * Checks if `value` is `NaN`. + * + * Note: This is not the same as native `isNaN` which will return `true` for + * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // `NaN` as a primitive is the only value that is not equal to itself + // (perform the [[Class]] check first to avoid errors with some host objects in IE) + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(undefined); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is a number. + * + * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a number, else `false`. + * @example + * + * _.isNumber(8.4 * 5); + * // => true + */ + function isNumber(value) { + return typeof value == 'number' || + value && typeof value == 'object' && toString.call(value) == numberClass || false; + } + + /** + * Checks if `value` is an object created by the `Object` constructor. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * _.isPlainObject(new Shape); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + */ + var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { + if (!(value && toString.call(value) == objectClass)) { + return false; + } + var valueOf = value.valueOf, + objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); + + return objProto + ? (value == objProto || getPrototypeOf(value) == objProto) + : shimIsPlainObject(value); + }; + + /** + * Checks if `value` is a regular expression. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`. + * @example + * + * _.isRegExp(/fred/); + * // => true + */ + function isRegExp(value) { + return value && typeof value == 'object' && toString.call(value) == regexpClass || false; + } + + /** + * Checks if `value` is a string. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is a string, else `false`. + * @example + * + * _.isString('fred'); + * // => true + */ + function isString(value) { + return typeof value == 'string' || + value && typeof value == 'object' && toString.call(value) == stringClass || false; + } + + /** + * Checks if `value` is `undefined`. + * + * @static + * @memberOf _ + * @category Objects + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + */ + function isUndefined(value) { + return typeof value == 'undefined'; + } + + /** + * Creates an object with the same keys as `object` and values generated by + * running each own enumerable property of `object` through the callback. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new object with values of the results of each `callback` execution. + * @example + * + * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; }); + * // => { 'a': 3, 'b': 6, 'c': 9 } + * + * var characters = { + * 'fred': { 'name': 'fred', 'age': 40 }, + * 'pebbles': { 'name': 'pebbles', 'age': 1 } + * }; + * + * // using "_.pluck" callback shorthand + * _.mapValues(characters, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } + */ + function mapValues(object, callback, thisArg) { + var result = {}; + callback = lodash.createCallback(callback, thisArg, 3); + + forOwn(object, function(value, key, object) { + result[key] = callback(value, key, object); + }); + return result; + } + + /** + * Recursively merges own enumerable properties of the source object(s), that + * don't resolve to `undefined` into the destination object. Subsequent sources + * will overwrite property assignments of previous sources. If a callback is + * provided it will be executed to produce the merged values of the destination + * and source properties. If the callback returns `undefined` merging will + * be handled by the method instead. The callback is bound to `thisArg` and + * invoked with two arguments; (objectValue, sourceValue). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The destination object. + * @param {...Object} [source] The source objects. + * @param {Function} [callback] The function to customize merging properties. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the destination object. + * @example + * + * var names = { + * 'characters': [ + * { 'name': 'barney' }, + * { 'name': 'fred' } + * ] + * }; + * + * var ages = { + * 'characters': [ + * { 'age': 36 }, + * { 'age': 40 } + * ] + * }; + * + * _.merge(names, ages); + * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] } + * + * var food = { + * 'fruits': ['apple'], + * 'vegetables': ['beet'] + * }; + * + * var otherFood = { + * 'fruits': ['banana'], + * 'vegetables': ['carrot'] + * }; + * + * _.merge(food, otherFood, function(a, b) { + * return _.isArray(a) ? a.concat(b) : undefined; + * }); + * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } + */ + function merge(object) { + var args = arguments, + length = 2; + + if (!isObject(object)) { + return object; + } + // allows working with `_.reduce` and `_.reduceRight` without using + // their `index` and `collection` arguments + if (typeof args[2] != 'number') { + length = args.length; + } + if (length > 3 && typeof args[length - 2] == 'function') { + var callback = baseCreateCallback(args[--length - 1], args[length--], 2); + } else if (length > 2 && typeof args[length - 1] == 'function') { + callback = args[--length]; + } + var sources = slice(arguments, 1, length), + index = -1, + stackA = getArray(), + stackB = getArray(); + + while (++index < length) { + baseMerge(object, sources[index], callback, stackA, stackB); + } + releaseArray(stackA); + releaseArray(stackB); + return object; + } + + /** + * Creates a shallow clone of `object` excluding the specified properties. + * Property names may be specified as individual arguments or as arrays of + * property names. If a callback is provided it will be executed for each + * property of `object` omitting the properties the callback returns truey + * for. The callback is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The source object. + * @param {Function|...string|string[]} [callback] The properties to omit or the + * function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns an object without the omitted properties. + * @example + * + * _.omit({ 'name': 'fred', 'age': 40 }, 'age'); + * // => { 'name': 'fred' } + * + * _.omit({ 'name': 'fred', 'age': 40 }, function(value) { + * return typeof value == 'number'; + * }); + * // => { 'name': 'fred' } + */ + function omit(object, callback, thisArg) { + var result = {}; + if (typeof callback != 'function') { + var props = []; + forIn(object, function(value, key) { + props.push(key); + }); + props = baseDifference(props, baseFlatten(arguments, true, false, 1)); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + result[key] = object[key]; + } + } else { + callback = lodash.createCallback(callback, thisArg, 3); + forIn(object, function(value, key, object) { + if (!callback(value, key, object)) { + result[key] = value; + } + }); + } + return result; + } + + /** + * Creates a two dimensional array of an object's key-value pairs, + * i.e. `[[key1, value1], [key2, value2]]`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns new array of key-value pairs. + * @example + * + * _.pairs({ 'barney': 36, 'fred': 40 }); + * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments) + */ + function pairs(object) { + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + var key = props[index]; + result[index] = [key, object[key]]; + } + return result; + } + + /** + * Creates a shallow clone of `object` composed of the specified properties. + * Property names may be specified as individual arguments or as arrays of + * property names. If a callback is provided it will be executed for each + * property of `object` picking the properties the callback returns truey + * for. The callback is bound to `thisArg` and invoked with three arguments; + * (value, key, object). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The source object. + * @param {Function|...string|string[]} [callback] The function called per + * iteration or property names to pick, specified as individual property + * names or arrays of property names. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns an object composed of the picked properties. + * @example + * + * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name'); + * // => { 'name': 'fred' } + * + * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) { + * return key.charAt(0) != '_'; + * }); + * // => { 'name': 'fred' } + */ + function pick(object, callback, thisArg) { + var result = {}; + if (typeof callback != 'function') { + var index = -1, + props = baseFlatten(arguments, true, false, 1), + length = isObject(object) ? props.length : 0; + + while (++index < length) { + var key = props[index]; + if (key in object) { + result[key] = object[key]; + } + } + } else { + callback = lodash.createCallback(callback, thisArg, 3); + forIn(object, function(value, key, object) { + if (callback(value, key, object)) { + result[key] = value; + } + }); + } + return result; + } + + /** + * An alternative to `_.reduce` this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable properties through a callback, with each callback execution + * potentially mutating the `accumulator` object. The callback is bound to + * `thisArg` and invoked with four arguments; (accumulator, value, key, object). + * Callbacks may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Array|Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the accumulated value. + * @example + * + * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) { + * num *= num; + * if (num % 2) { + * return result.push(num) < 3; + * } + * }); + * // => [1, 9, 25] + * + * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { + * result[key] = num * 3; + * }); + * // => { 'a': 3, 'b': 6, 'c': 9 } + */ + function transform(object, callback, accumulator, thisArg) { + var isArr = isArray(object); + if (accumulator == null) { + if (isArr) { + accumulator = []; + } else { + var ctor = object && object.constructor, + proto = ctor && ctor.prototype; + + accumulator = baseCreate(proto); + } + } + if (callback) { + callback = lodash.createCallback(callback, thisArg, 4); + (isArr ? forEach : forOwn)(object, function(value, index, object) { + return callback(accumulator, value, index, object); + }); + } + return accumulator; + } + + /** + * Creates an array composed of the own enumerable property values of `object`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns an array of property values. + * @example + * + * _.values({ 'one': 1, 'two': 2, 'three': 3 }); + * // => [1, 2, 3] (property order is not guaranteed across environments) + */ + function values(object) { + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + result[index] = object[props[index]]; + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates an array of elements from the specified indexes, or keys, of the + * `collection`. Indexes may be specified as individual arguments or as arrays + * of indexes. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(number|number[]|string|string[])} [index] The indexes of `collection` + * to retrieve, specified as individual indexes or arrays of indexes. + * @returns {Array} Returns a new array of elements corresponding to the + * provided indexes. + * @example + * + * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); + * // => ['a', 'c', 'e'] + * + * _.at(['fred', 'barney', 'pebbles'], 0, 2); + * // => ['fred', 'pebbles'] + */ + function at(collection) { + var args = arguments, + index = -1, + props = baseFlatten(args, true, false, 1), + length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length, + result = Array(length); + + while(++index < length) { + result[index] = collection[props[index]]; + } + return result; + } + + /** + * Checks if a given value is present in a collection using strict equality + * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the + * offset from the end of the collection. + * + * @static + * @memberOf _ + * @alias include + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {*} target The value to check for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {boolean} Returns `true` if the `target` element is found, else `false`. + * @example + * + * _.contains([1, 2, 3], 1); + * // => true + * + * _.contains([1, 2, 3], 1, 2); + * // => false + * + * _.contains({ 'name': 'fred', 'age': 40 }, 'fred'); + * // => true + * + * _.contains('pebbles', 'eb'); + * // => true + */ + function contains(collection, target, fromIndex) { + var index = -1, + indexOf = getIndexOf(), + length = collection ? collection.length : 0, + result = false; + + fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; + if (isArray(collection)) { + result = indexOf(collection, target, fromIndex) > -1; + } else if (typeof length == 'number') { + result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1; + } else { + forOwn(collection, function(value) { + if (++index >= fromIndex) { + return !(result = value === target); + } + }); + } + return result; + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through the callback. The corresponding value + * of each key is the number of times the key was returned by the callback. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); + * // => { '4': 1, '6': 2 } + * + * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); + * // => { '4': 1, '6': 2 } + * + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); + }); + + /** + * Checks if the given callback returns truey value for **all** elements of + * a collection. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias all + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {boolean} Returns `true` if all elements passed the callback check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes']); + * // => false + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.every(characters, 'age'); + * // => true + * + * // using "_.where" callback shorthand + * _.every(characters, { 'age': 36 }); + * // => false + */ + function every(collection, callback, thisArg) { + var result = true; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + if (!(result = !!callback(collection[index], index, collection))) { + break; + } + } + } else { + forOwn(collection, function(value, index, collection) { + return (result = !!callback(value, index, collection)); + }); + } + return result; + } + + /** + * Iterates over elements of a collection, returning an array of all elements + * the callback returns truey for. The callback is bound to `thisArg` and + * invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias select + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of elements that passed the callback check. + * @example + * + * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => [2, 4, 6] + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.filter(characters, 'blocked'); + * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] + * + * // using "_.where" callback shorthand + * _.filter(characters, { 'age': 36 }); + * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] + */ + function filter(collection, callback, thisArg) { + var result = []; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + var value = collection[index]; + if (callback(value, index, collection)) { + result.push(value); + } + } + } else { + forOwn(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result.push(value); + } + }); + } + return result; + } + + /** + * Iterates over elements of a collection, returning the first element that + * the callback returns truey for. The callback is bound to `thisArg` and + * invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias detect, findWhere + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the found element, else `undefined`. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true }, + * { 'name': 'pebbles', 'age': 1, 'blocked': false } + * ]; + * + * _.find(characters, function(chr) { + * return chr.age < 40; + * }); + * // => { 'name': 'barney', 'age': 36, 'blocked': false } + * + * // using "_.where" callback shorthand + * _.find(characters, { 'age': 1 }); + * // => { 'name': 'pebbles', 'age': 1, 'blocked': false } + * + * // using "_.pluck" callback shorthand + * _.find(characters, 'blocked'); + * // => { 'name': 'fred', 'age': 40, 'blocked': true } + */ + function find(collection, callback, thisArg) { + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + var value = collection[index]; + if (callback(value, index, collection)) { + return value; + } + } + } else { + var result; + forOwn(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result = value; + return false; + } + }); + return result; + } + } + + /** + * This method is like `_.find` except that it iterates over elements + * of a `collection` from right to left. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the found element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(num) { + * return num % 2 == 1; + * }); + * // => 3 + */ + function findLast(collection, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + forEachRight(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result = value; + return false; + } + }); + return result; + } + + /** + * Iterates over elements of a collection, executing the callback for each + * element. The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). Callbacks may exit iteration early by + * explicitly returning `false`. + * + * Note: As with other "Collections" methods, objects with a `length` property + * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` + * may be used for object iteration. + * + * @static + * @memberOf _ + * @alias each + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(','); + * // => logs each number and returns '1,2,3' + * + * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); + * // => logs each number and returns the object (property order is not guaranteed across environments) + */ + function forEach(collection, callback, thisArg) { + var index = -1, + length = collection ? collection.length : 0; + + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + if (typeof length == 'number') { + while (++index < length) { + if (callback(collection[index], index, collection) === false) { + break; + } + } + } else { + forOwn(collection, callback); + } + return collection; + } + + /** + * This method is like `_.forEach` except that it iterates over elements + * of a `collection` from right to left. + * + * @static + * @memberOf _ + * @alias eachRight + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(','); + * // => logs each number from right to left and returns '3,2,1' + */ + function forEachRight(collection, callback, thisArg) { + var length = collection ? collection.length : 0; + callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); + if (typeof length == 'number') { + while (length--) { + if (callback(collection[length], length, collection) === false) { + break; + } + } + } else { + var props = keys(collection); + length = props.length; + forOwn(collection, function(value, key, collection) { + key = props ? props[--length] : --length; + return callback(collection[key], key, collection); + }); + } + return collection; + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of a collection through the callback. The corresponding value + * of each key is an array of the elements responsible for generating the key. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false` + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * // using "_.pluck" callback shorthand + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of the collection through the given callback. The corresponding + * value of each key is the last element responsible for generating the key. + * The callback is bound to `thisArg` and invoked with three arguments; + * (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var keys = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.indexBy(keys, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + */ + var indexBy = createAggregator(function(result, value, key) { + result[key] = value; + }); + + /** + * Invokes the method named by `methodName` on each element in the `collection` + * returning an array of the results of each invoked method. Additional arguments + * will be provided to each invoked method. If `methodName` is a function it + * will be invoked for, and `this` bound to, each element in the `collection`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|string} methodName The name of the method to invoke or + * the function invoked per iteration. + * @param {...*} [arg] Arguments to invoke the method with. + * @returns {Array} Returns a new array of the results of each invoked method. + * @example + * + * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invoke([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + function invoke(collection, methodName) { + var args = slice(arguments, 2), + index = -1, + isFunc = typeof methodName == 'function', + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + forEach(collection, function(value) { + result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); + }); + return result; + } + + /** + * Creates an array of values by running each element in the collection + * through the callback. The callback is bound to `thisArg` and invoked with + * three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias collect + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of the results of each `callback` execution. + * @example + * + * _.map([1, 2, 3], function(num) { return num * 3; }); + * // => [3, 6, 9] + * + * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); + * // => [3, 6, 9] (property order is not guaranteed across environments) + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.map(characters, 'name'); + * // => ['barney', 'fred'] + */ + function map(collection, callback, thisArg) { + var index = -1, + length = collection ? collection.length : 0; + + callback = lodash.createCallback(callback, thisArg, 3); + if (typeof length == 'number') { + var result = Array(length); + while (++index < length) { + result[index] = callback(collection[index], index, collection); + } + } else { + result = []; + forOwn(collection, function(value, key, collection) { + result[++index] = callback(value, key, collection); + }); + } + return result; + } + + /** + * Retrieves the maximum value of a collection. If the collection is empty or + * falsey `-Infinity` is returned. If a callback is provided it will be executed + * for each value in the collection to generate the criterion by which the value + * is ranked. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * _.max(characters, function(chr) { return chr.age; }); + * // => { 'name': 'fred', 'age': 40 }; + * + * // using "_.pluck" callback shorthand + * _.max(characters, 'age'); + * // => { 'name': 'fred', 'age': 40 }; + */ + function max(collection, callback, thisArg) { + var computed = -Infinity, + result = computed; + + // allows working with functions like `_.map` without using + // their `index` argument as a callback + if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { + callback = null; + } + if (callback == null && isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + if (value > result) { + result = value; + } + } + } else { + callback = (callback == null && isString(collection)) + ? charAtCallback + : lodash.createCallback(callback, thisArg, 3); + + forEach(collection, function(value, index, collection) { + var current = callback(value, index, collection); + if (current > computed) { + computed = current; + result = value; + } + }); + } + return result; + } + + /** + * Retrieves the minimum value of a collection. If the collection is empty or + * falsey `Infinity` is returned. If a callback is provided it will be executed + * for each value in the collection to generate the criterion by which the value + * is ranked. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * _.min(characters, function(chr) { return chr.age; }); + * // => { 'name': 'barney', 'age': 36 }; + * + * // using "_.pluck" callback shorthand + * _.min(characters, 'age'); + * // => { 'name': 'barney', 'age': 36 }; + */ + function min(collection, callback, thisArg) { + var computed = Infinity, + result = computed; + + // allows working with functions like `_.map` without using + // their `index` argument as a callback + if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { + callback = null; + } + if (callback == null && isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + if (value < result) { + result = value; + } + } + } else { + callback = (callback == null && isString(collection)) + ? charAtCallback + : lodash.createCallback(callback, thisArg, 3); + + forEach(collection, function(value, index, collection) { + var current = callback(value, index, collection); + if (current < computed) { + computed = current; + result = value; + } + }); + } + return result; + } + + /** + * Retrieves the value of a specified property from all elements in the collection. + * + * @static + * @memberOf _ + * @type Function + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {string} property The name of the property to pluck. + * @returns {Array} Returns a new array of property values. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * _.pluck(characters, 'name'); + * // => ['barney', 'fred'] + */ + var pluck = map; + + /** + * Reduces a collection to a value which is the accumulated result of running + * each element in the collection through the callback, where each successive + * callback execution consumes the return value of the previous execution. If + * `accumulator` is not provided the first element of the collection will be + * used as the initial `accumulator` value. The callback is bound to `thisArg` + * and invoked with four arguments; (accumulator, value, index|key, collection). + * + * @static + * @memberOf _ + * @alias foldl, inject + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [accumulator] Initial value of the accumulator. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the accumulated value. + * @example + * + * var sum = _.reduce([1, 2, 3], function(sum, num) { + * return sum + num; + * }); + * // => 6 + * + * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { + * result[key] = num * 3; + * return result; + * }, {}); + * // => { 'a': 3, 'b': 6, 'c': 9 } + */ + function reduce(collection, callback, accumulator, thisArg) { + if (!collection) return accumulator; + var noaccum = arguments.length < 3; + callback = lodash.createCallback(callback, thisArg, 4); + + var index = -1, + length = collection.length; + + if (typeof length == 'number') { + if (noaccum) { + accumulator = collection[++index]; + } + while (++index < length) { + accumulator = callback(accumulator, collection[index], index, collection); + } + } else { + forOwn(collection, function(value, index, collection) { + accumulator = noaccum + ? (noaccum = false, value) + : callback(accumulator, value, index, collection) + }); + } + return accumulator; + } + + /** + * This method is like `_.reduce` except that it iterates over elements + * of a `collection` from right to left. + * + * @static + * @memberOf _ + * @alias foldr + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {*} [accumulator] Initial value of the accumulator. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the accumulated value. + * @example + * + * var list = [[0, 1], [2, 3], [4, 5]]; + * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, callback, accumulator, thisArg) { + var noaccum = arguments.length < 3; + callback = lodash.createCallback(callback, thisArg, 4); + forEachRight(collection, function(value, index, collection) { + accumulator = noaccum + ? (noaccum = false, value) + : callback(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The opposite of `_.filter` this method returns the elements of a + * collection that the callback does **not** return truey for. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of elements that failed the callback check. + * @example + * + * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => [1, 3, 5] + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.reject(characters, 'blocked'); + * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] + * + * // using "_.where" callback shorthand + * _.reject(characters, { 'age': 36 }); + * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] + */ + function reject(collection, callback, thisArg) { + callback = lodash.createCallback(callback, thisArg, 3); + return filter(collection, function(value, index, collection) { + return !callback(value, index, collection); + }); + } + + /** + * Retrieves a random element or `n` random elements from a collection. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to sample. + * @param {number} [n] The number of elements to sample. + * @param- {Object} [guard] Allows working with functions like `_.map` + * without using their `index` arguments as `n`. + * @returns {Array} Returns the random sample(s) of `collection`. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + * + * _.sample([1, 2, 3, 4], 2); + * // => [3, 1] + */ + function sample(collection, n, guard) { + if (collection && typeof collection.length != 'number') { + collection = values(collection); + } + if (n == null || guard) { + return collection ? collection[baseRandom(0, collection.length - 1)] : undefined; + } + var result = shuffle(collection); + result.length = nativeMin(nativeMax(0, n), result.length); + return result; + } + + /** + * Creates an array of shuffled values, using a version of the Fisher-Yates + * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to shuffle. + * @returns {Array} Returns a new shuffled collection. + * @example + * + * _.shuffle([1, 2, 3, 4, 5, 6]); + * // => [4, 1, 6, 3, 5, 2] + */ + function shuffle(collection) { + var index = -1, + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + forEach(collection, function(value) { + var rand = baseRandom(0, ++index); + result[index] = result[rand]; + result[rand] = value; + }); + return result; + } + + /** + * Gets the size of the `collection` by returning `collection.length` for arrays + * and array-like objects or the number of own enumerable properties for objects. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns `collection.length` or number of own enumerable properties. + * @example + * + * _.size([1, 2]); + * // => 2 + * + * _.size({ 'one': 1, 'two': 2, 'three': 3 }); + * // => 3 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + var length = collection ? collection.length : 0; + return typeof length == 'number' ? length : keys(collection).length; + } + + /** + * Checks if the callback returns a truey value for **any** element of a + * collection. The function returns as soon as it finds a passing value and + * does not iterate over the entire collection. The callback is bound to + * `thisArg` and invoked with three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias any + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {boolean} Returns `true` if any element passed the callback check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.some(characters, 'blocked'); + * // => true + * + * // using "_.where" callback shorthand + * _.some(characters, { 'age': 1 }); + * // => false + */ + function some(collection, callback, thisArg) { + var result; + callback = lodash.createCallback(callback, thisArg, 3); + + var index = -1, + length = collection ? collection.length : 0; + + if (typeof length == 'number') { + while (++index < length) { + if ((result = callback(collection[index], index, collection))) { + break; + } + } + } else { + forOwn(collection, function(value, index, collection) { + return !(result = callback(value, index, collection)); + }); + } + return !!result; + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection through the callback. This method + * performs a stable sort, that is, it will preserve the original sort order + * of equal elements. The callback is bound to `thisArg` and invoked with + * three arguments; (value, index|key, collection). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an array of property names is provided for `callback` the collection + * will be sorted by each property value. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of sorted elements. + * @example + * + * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); + * // => [3, 1, 2] + * + * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); + * // => [3, 1, 2] + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 }, + * { 'name': 'barney', 'age': 26 }, + * { 'name': 'fred', 'age': 30 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.map(_.sortBy(characters, 'age'), _.values); + * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]] + * + * // sorting by multiple properties + * _.map(_.sortBy(characters, ['name', 'age']), _.values); + * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] + */ + function sortBy(collection, callback, thisArg) { + var index = -1, + isArr = isArray(callback), + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + if (!isArr) { + callback = lodash.createCallback(callback, thisArg, 3); + } + forEach(collection, function(value, key, collection) { + var object = result[++index] = getObject(); + if (isArr) { + object.criteria = map(callback, function(key) { return value[key]; }); + } else { + (object.criteria = getArray())[0] = callback(value, key, collection); + } + object.index = index; + object.value = value; + }); + + length = result.length; + result.sort(compareAscending); + while (length--) { + var object = result[length]; + result[length] = object.value; + if (!isArr) { + releaseArray(object.criteria); + } + releaseObject(object); + } + return result; + } + + /** + * Converts the `collection` to an array. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|string} collection The collection to convert. + * @returns {Array} Returns the new converted array. + * @example + * + * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); + * // => [2, 3, 4] + */ + function toArray(collection) { + if (collection && typeof collection.length == 'number') { + return slice(collection); + } + return values(collection); + } + + /** + * Performs a deep comparison of each element in a `collection` to the given + * `properties` object, returning an array of all elements that have equivalent + * property values. + * + * @static + * @memberOf _ + * @type Function + * @category Collections + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Object} props The object of property values to filter by. + * @returns {Array} Returns a new array of elements that have the given properties. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }, + * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } + * ]; + * + * _.where(characters, { 'age': 36 }); + * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }] + * + * _.where(characters, { 'pets': ['dino'] }); + * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }] + */ + var where = filter; + + /*--------------------------------------------------------------------------*/ + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are all falsey. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to compact. + * @returns {Array} Returns a new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array ? array.length : 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result.push(value); + } + } + return result; + } + + /** + * Creates an array excluding all values of the provided arrays using strict + * equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to process. + * @param {...Array} [values] The arrays of values to exclude. + * @returns {Array} Returns a new array of filtered values. + * @example + * + * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); + * // => [1, 3, 4] + */ + function difference(array) { + return baseDifference(array, baseFlatten(arguments, true, true, 1)); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element that passes the callback check, instead of the element itself. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': false }, + * { 'name': 'fred', 'age': 40, 'blocked': true }, + * { 'name': 'pebbles', 'age': 1, 'blocked': false } + * ]; + * + * _.findIndex(characters, function(chr) { + * return chr.age < 20; + * }); + * // => 2 + * + * // using "_.where" callback shorthand + * _.findIndex(characters, { 'age': 36 }); + * // => 0 + * + * // using "_.pluck" callback shorthand + * _.findIndex(characters, 'blocked'); + * // => 1 + */ + function findIndex(array, callback, thisArg) { + var index = -1, + length = array ? array.length : 0; + + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length) { + if (callback(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of a `collection` from right to left. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36, 'blocked': true }, + * { 'name': 'fred', 'age': 40, 'blocked': false }, + * { 'name': 'pebbles', 'age': 1, 'blocked': true } + * ]; + * + * _.findLastIndex(characters, function(chr) { + * return chr.age > 30; + * }); + * // => 1 + * + * // using "_.where" callback shorthand + * _.findLastIndex(characters, { 'age': 36 }); + * // => 0 + * + * // using "_.pluck" callback shorthand + * _.findLastIndex(characters, 'blocked'); + * // => 2 + */ + function findLastIndex(array, callback, thisArg) { + var length = array ? array.length : 0; + callback = lodash.createCallback(callback, thisArg, 3); + while (length--) { + if (callback(array[length], length, array)) { + return length; + } + } + return -1; + } + + /** + * Gets the first element or first `n` elements of an array. If a callback + * is provided elements at the beginning of the array are returned as long + * as the callback returns truey. The callback is bound to `thisArg` and + * invoked with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias head, take + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback] The function called + * per element or the number of elements to return. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the first element(s) of `array`. + * @example + * + * _.first([1, 2, 3]); + * // => 1 + * + * _.first([1, 2, 3], 2); + * // => [1, 2] + * + * _.first([1, 2, 3], function(num) { + * return num < 3; + * }); + * // => [1, 2] + * + * var characters = [ + * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.first(characters, 'blocked'); + * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }] + * + * // using "_.where" callback shorthand + * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name'); + * // => ['barney', 'fred'] + */ + function first(array, callback, thisArg) { + var n = 0, + length = array ? array.length : 0; + + if (typeof callback != 'number' && callback != null) { + var index = -1; + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length && callback(array[index], index, array)) { + n++; + } + } else { + n = callback; + if (n == null || thisArg) { + return array ? array[0] : undefined; + } + } + return slice(array, 0, nativeMin(nativeMax(0, n), length)); + } + + /** + * Flattens a nested array (the nesting can be to any depth). If `isShallow` + * is truey, the array will only be flattened a single level. If a callback + * is provided each element of the array is passed through the callback before + * flattening. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to flatten. + * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new flattened array. + * @example + * + * _.flatten([1, [2], [3, [[4]]]]); + * // => [1, 2, 3, 4]; + * + * _.flatten([1, [2], [3, [[4]]]], true); + * // => [1, 2, 3, [[4]]]; + * + * var characters = [ + * { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] }, + * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } + * ]; + * + * // using "_.pluck" callback shorthand + * _.flatten(characters, 'pets'); + * // => ['hoppy', 'baby puss', 'dino'] + */ + function flatten(array, isShallow, callback, thisArg) { + // juggle arguments + if (typeof isShallow != 'boolean' && isShallow != null) { + thisArg = callback; + callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow; + isShallow = false; + } + if (callback != null) { + array = map(array, callback, thisArg); + } + return baseFlatten(array, isShallow); + } + + /** + * Gets the index at which the first occurrence of `value` is found using + * strict equality for comparisons, i.e. `===`. If the array is already sorted + * providing `true` for `fromIndex` will run a faster binary search. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=0] The index to search from or `true` + * to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value or `-1`. + * @example + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2); + * // => 1 + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 4 + * + * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); + * // => 2 + */ + function indexOf(array, value, fromIndex) { + if (typeof fromIndex == 'number') { + var length = array ? array.length : 0; + fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0); + } else if (fromIndex) { + var index = sortedIndex(array, value); + return array[index] === value ? index : -1; + } + return baseIndexOf(array, value, fromIndex); + } + + /** + * Gets all but the last element or last `n` elements of an array. If a + * callback is provided elements at the end of the array are excluded from + * the result as long as the callback returns truey. The callback is bound + * to `thisArg` and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback=1] The function called + * per element or the number of elements to exclude. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + * + * _.initial([1, 2, 3], 2); + * // => [1] + * + * _.initial([1, 2, 3], function(num) { + * return num > 1; + * }); + * // => [1] + * + * var characters = [ + * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.initial(characters, 'blocked'); + * // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }] + * + * // using "_.where" callback shorthand + * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name'); + * // => ['barney', 'fred'] + */ + function initial(array, callback, thisArg) { + var n = 0, + length = array ? array.length : 0; + + if (typeof callback != 'number' && callback != null) { + var index = length; + callback = lodash.createCallback(callback, thisArg, 3); + while (index-- && callback(array[index], index, array)) { + n++; + } + } else { + n = (callback == null || thisArg) ? 1 : callback || n; + } + return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); + } + + /** + * Creates an array of unique values present in all provided arrays using + * strict equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {...Array} [array] The arrays to inspect. + * @returns {Array} Returns an array of shared values. + * @example + * + * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]); + * // => [1, 2] + */ + function intersection() { + var args = [], + argsIndex = -1, + argsLength = arguments.length, + caches = getArray(), + indexOf = getIndexOf(), + trustIndexOf = indexOf === baseIndexOf, + seen = getArray(); + + while (++argsIndex < argsLength) { + var value = arguments[argsIndex]; + if (isArray(value) || isArguments(value)) { + args.push(value); + caches.push(trustIndexOf && value.length >= largeArraySize && + createCache(argsIndex ? args[argsIndex] : seen)); + } + } + var array = args[0], + index = -1, + length = array ? array.length : 0, + result = []; + + outer: + while (++index < length) { + var cache = caches[0]; + value = array[index]; + + if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) { + argsIndex = argsLength; + (cache || seen).push(value); + while (--argsIndex) { + cache = caches[argsIndex]; + if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) { + continue outer; + } + } + result.push(value); + } + } + while (argsLength--) { + cache = caches[argsLength]; + if (cache) { + releaseObject(cache); + } + } + releaseArray(caches); + releaseArray(seen); + return result; + } + + /** + * Gets the last element or last `n` elements of an array. If a callback is + * provided elements at the end of the array are returned as long as the + * callback returns truey. The callback is bound to `thisArg` and invoked + * with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback] The function called + * per element or the number of elements to return. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {*} Returns the last element(s) of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + * + * _.last([1, 2, 3], 2); + * // => [2, 3] + * + * _.last([1, 2, 3], function(num) { + * return num > 1; + * }); + * // => [2, 3] + * + * var characters = [ + * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.pluck(_.last(characters, 'blocked'), 'name'); + * // => ['fred', 'pebbles'] + * + * // using "_.where" callback shorthand + * _.last(characters, { 'employer': 'na' }); + * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] + */ + function last(array, callback, thisArg) { + var n = 0, + length = array ? array.length : 0; + + if (typeof callback != 'number' && callback != null) { + var index = length; + callback = lodash.createCallback(callback, thisArg, 3); + while (index-- && callback(array[index], index, array)) { + n++; + } + } else { + n = callback; + if (n == null || thisArg) { + return array ? array[length - 1] : undefined; + } + } + return slice(array, nativeMax(0, length - n)); + } + + /** + * Gets the index at which the last occurrence of `value` is found using strict + * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used + * as the offset from the end of the collection. + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value or `-1`. + * @example + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); + * // => 4 + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var index = array ? array.length : 0; + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; + } + while (index--) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * Removes all provided values from the given array using strict equality for + * comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to modify. + * @param {...*} [value] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3, 1, 2, 3]; + * _.pull(array, 2, 3); + * console.log(array); + * // => [1, 1] + */ + function pull(array) { + var args = arguments, + argsIndex = 0, + argsLength = args.length, + length = array ? array.length : 0; + + while (++argsIndex < argsLength) { + var index = -1, + value = args[argsIndex]; + while (++index < length) { + if (array[index] === value) { + splice.call(array, index--, 1); + length--; + } + } + } + return array; + } + + /** + * Creates an array of numbers (positive and/or negative) progressing from + * `start` up to but not including `end`. If `start` is less than `stop` a + * zero-length range is created unless a negative `step` is specified. + * + * @static + * @memberOf _ + * @category Arrays + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @param {number} [step=1] The value to increment or decrement by. + * @returns {Array} Returns a new range array. + * @example + * + * _.range(4); + * // => [0, 1, 2, 3] + * + * _.range(1, 5); + * // => [1, 2, 3, 4] + * + * _.range(0, 20, 5); + * // => [0, 5, 10, 15] + * + * _.range(0, -4, -1); + * // => [0, -1, -2, -3] + * + * _.range(1, 4, 0); + * // => [1, 1, 1] + * + * _.range(0); + * // => [] + */ + function range(start, end, step) { + start = +start || 0; + step = typeof step == 'number' ? step : (+step || 1); + + if (end == null) { + end = start; + start = 0; + } + // use `Array(length)` so engines like Chakra and V8 avoid slower modes + // http://youtu.be/XAqIpGU8ZZk#t=17m25s + var index = -1, + length = nativeMax(0, ceil((end - start) / (step || 1))), + result = Array(length); + + while (++index < length) { + result[index] = start; + start += step; + } + return result; + } + + /** + * Removes all elements from an array that the callback returns truey for + * and returns an array of removed elements. The callback is bound to `thisArg` + * and invoked with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to modify. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4, 5, 6]; + * var evens = _.remove(array, function(num) { return num % 2 == 0; }); + * + * console.log(array); + * // => [1, 3, 5] + * + * console.log(evens); + * // => [2, 4, 6] + */ + function remove(array, callback, thisArg) { + var index = -1, + length = array ? array.length : 0, + result = []; + + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length) { + var value = array[index]; + if (callback(value, index, array)) { + result.push(value); + splice.call(array, index--, 1); + length--; + } + } + return result; + } + + /** + * The opposite of `_.initial` this method gets all but the first element or + * first `n` elements of an array. If a callback function is provided elements + * at the beginning of the array are excluded from the result as long as the + * callback returns truey. The callback is bound to `thisArg` and invoked + * with three arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias drop, tail + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|number|string} [callback=1] The function called + * per element or the number of elements to exclude. If a property name or + * object is provided it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a slice of `array`. + * @example + * + * _.rest([1, 2, 3]); + * // => [2, 3] + * + * _.rest([1, 2, 3], 2); + * // => [3] + * + * _.rest([1, 2, 3], function(num) { + * return num < 3; + * }); + * // => [3] + * + * var characters = [ + * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, + * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, + * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.pluck(_.rest(characters, 'blocked'), 'name'); + * // => ['fred', 'pebbles'] + * + * // using "_.where" callback shorthand + * _.rest(characters, { 'employer': 'slate' }); + * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] + */ + function rest(array, callback, thisArg) { + if (typeof callback != 'number' && callback != null) { + var n = 0, + index = -1, + length = array ? array.length : 0; + + callback = lodash.createCallback(callback, thisArg, 3); + while (++index < length && callback(array[index], index, array)) { + n++; + } + } else { + n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); + } + return slice(array, n); + } + + /** + * Uses a binary search to determine the smallest index at which a value + * should be inserted into a given sorted array in order to maintain the sort + * order of the array. If a callback is provided it will be executed for + * `value` and each element of `array` to compute their sort ranking. The + * callback is bound to `thisArg` and invoked with one argument; (value). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([20, 30, 50], 40); + * // => 2 + * + * // using "_.pluck" callback shorthand + * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); + * // => 2 + * + * var dict = { + * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } + * }; + * + * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + * return dict.wordToNumber[word]; + * }); + * // => 2 + * + * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + * return this.wordToNumber[word]; + * }, dict); + * // => 2 + */ + function sortedIndex(array, value, callback, thisArg) { + var low = 0, + high = array ? array.length : low; + + // explicitly reference `identity` for better inlining in Firefox + callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity; + value = callback(value); + + while (low < high) { + var mid = (low + high) >>> 1; + (callback(array[mid]) < value) + ? low = mid + 1 + : high = mid; + } + return low; + } + + /** + * Creates an array of unique values, in order, of the provided arrays using + * strict equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {...Array} [array] The arrays to inspect. + * @returns {Array} Returns an array of combined values. + * @example + * + * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]); + * // => [1, 2, 3, 5, 4] + */ + function union() { + return baseUniq(baseFlatten(arguments, true, true)); + } + + /** + * Creates a duplicate-value-free version of an array using strict equality + * for comparisons, i.e. `===`. If the array is sorted, providing + * `true` for `isSorted` will use a faster algorithm. If a callback is provided + * each element of `array` is passed through the callback before uniqueness + * is computed. The callback is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is provided for `callback` the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is provided for `callback` the created "_.where" style callback + * will return `true` for elements that have the properties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias unique + * @category Arrays + * @param {Array} array The array to process. + * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. + * @param {Function|Object|string} [callback=identity] The function called + * per iteration. If a property name or object is provided it will be used + * to create a "_.pluck" or "_.where" style callback, respectively. + * @param {*} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a duplicate-value-free array. + * @example + * + * _.uniq([1, 2, 1, 3, 1]); + * // => [1, 2, 3] + * + * _.uniq([1, 1, 2, 2, 3], true); + * // => [1, 2, 3] + * + * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); }); + * // => ['A', 'b', 'C'] + * + * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); + * // => [1, 2.5, 3] + * + * // using "_.pluck" callback shorthand + * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniq(array, isSorted, callback, thisArg) { + // juggle arguments + if (typeof isSorted != 'boolean' && isSorted != null) { + thisArg = callback; + callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted; + isSorted = false; + } + if (callback != null) { + callback = lodash.createCallback(callback, thisArg, 3); + } + return baseUniq(array, isSorted, callback); + } + + /** + * Creates an array excluding all provided values using strict equality for + * comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to filter. + * @param {...*} [value] The values to exclude. + * @returns {Array} Returns a new array of filtered values. + * @example + * + * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); + * // => [2, 3, 4] + */ + function without(array) { + return baseDifference(array, slice(arguments, 1)); + } + + /** + * Creates an array that is the symmetric difference of the provided arrays. + * See http://en.wikipedia.org/wiki/Symmetric_difference. + * + * @static + * @memberOf _ + * @category Arrays + * @param {...Array} [array] The arrays to inspect. + * @returns {Array} Returns an array of values. + * @example + * + * _.xor([1, 2, 3], [5, 2, 1, 4]); + * // => [3, 5, 4] + * + * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]); + * // => [1, 4, 5] + */ + function xor() { + var index = -1, + length = arguments.length; + + while (++index < length) { + var array = arguments[index]; + if (isArray(array) || isArguments(array)) { + var result = result + ? baseUniq(baseDifference(result, array).concat(baseDifference(array, result))) + : array; + } + } + return result || []; + } + + /** + * Creates an array of grouped elements, the first of which contains the first + * elements of the given arrays, the second of which contains the second + * elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @alias unzip + * @category Arrays + * @param {...Array} [array] Arrays to process. + * @returns {Array} Returns a new array of grouped elements. + * @example + * + * _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + */ + function zip() { + var array = arguments.length > 1 ? arguments : arguments[0], + index = -1, + length = array ? max(pluck(array, 'length')) : 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = pluck(array, index); + } + return result; + } + + /** + * Creates an object composed from arrays of `keys` and `values`. Provide + * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]` + * or two arrays, one of `keys` and one of corresponding `values`. + * + * @static + * @memberOf _ + * @alias object + * @category Arrays + * @param {Array} keys The array of keys. + * @param {Array} [values=[]] The array of values. + * @returns {Object} Returns an object composed of the given keys and + * corresponding values. + * @example + * + * _.zipObject(['fred', 'barney'], [30, 40]); + * // => { 'fred': 30, 'barney': 40 } + */ + function zipObject(keys, values) { + var index = -1, + length = keys ? keys.length : 0, + result = {}; + + if (!values && length && !isArray(keys[0])) { + values = []; + } + while (++index < length) { + var key = keys[index]; + if (values) { + result[key] = values[index]; + } else if (key) { + result[key[0]] = key[1]; + } + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a function that executes `func`, with the `this` binding and + * arguments of the created function, only after being called `n` times. + * + * @static + * @memberOf _ + * @category Functions + * @param {number} n The number of times the function must be called before + * `func` is executed. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('Done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => logs 'Done saving!', after all saves have completed + */ + function after(n, func) { + if (!isFunction(func)) { + throw new TypeError; + } + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that, when called, invokes `func` with the `this` + * binding of `thisArg` and prepends any additional `bind` arguments to those + * provided to the bound function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to bind. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var func = function(greeting) { + * return greeting + ' ' + this.name; + * }; + * + * func = _.bind(func, { 'name': 'fred' }, 'hi'); + * func(); + * // => 'hi fred' + */ + function bind(func, thisArg) { + return arguments.length > 2 + ? createWrapper(func, 17, slice(arguments, 2), null, thisArg) + : createWrapper(func, 1, null, null, thisArg); + } + + /** + * Binds methods of an object to the object itself, overwriting the existing + * method. Method names may be specified as individual arguments or as arrays + * of method names. If no method names are provided all the function properties + * of `object` will be bound. + * + * @static + * @memberOf _ + * @category Functions + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...string} [methodName] The object method names to + * bind, specified as individual method names or arrays of method names. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'onClick': function() { console.log('clicked ' + this.label); } + * }; + * + * _.bindAll(view); + * jQuery('#docs').on('click', view.onClick); + * // => logs 'clicked docs', when the button is clicked + */ + function bindAll(object) { + var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object), + index = -1, + length = funcs.length; + + while (++index < length) { + var key = funcs[index]; + object[key] = createWrapper(object[key], 1, null, null, object); + } + return object; + } + + /** + * Creates a function that, when called, invokes the method at `object[key]` + * and prepends any additional `bindKey` arguments to those provided to the bound + * function. This method differs from `_.bind` by allowing bound functions to + * reference methods that will be redefined or don't yet exist. + * See http://michaux.ca/articles/lazy-function-definition-pattern. + * + * @static + * @memberOf _ + * @category Functions + * @param {Object} object The object the method belongs to. + * @param {string} key The key of the method. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'name': 'fred', + * 'greet': function(greeting) { + * return greeting + ' ' + this.name; + * } + * }; + * + * var func = _.bindKey(object, 'greet', 'hi'); + * func(); + * // => 'hi fred' + * + * object.greet = function(greeting) { + * return greeting + 'ya ' + this.name + '!'; + * }; + * + * func(); + * // => 'hiya fred!' + */ + function bindKey(object, key) { + return arguments.length > 2 + ? createWrapper(key, 19, slice(arguments, 2), null, object) + : createWrapper(key, 3, null, null, object); + } + + /** + * Creates a function that is the composition of the provided functions, + * where each function consumes the return value of the function that follows. + * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. + * Each function is executed with the `this` binding of the composed function. + * + * @static + * @memberOf _ + * @category Functions + * @param {...Function} [func] Functions to compose. + * @returns {Function} Returns the new composed function. + * @example + * + * var realNameMap = { + * 'pebbles': 'penelope' + * }; + * + * var format = function(name) { + * name = realNameMap[name.toLowerCase()] || name; + * return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); + * }; + * + * var greet = function(formatted) { + * return 'Hiya ' + formatted + '!'; + * }; + * + * var welcome = _.compose(greet, format); + * welcome('pebbles'); + * // => 'Hiya Penelope!' + */ + function compose() { + var funcs = arguments, + length = funcs.length; + + while (length--) { + if (!isFunction(funcs[length])) { + throw new TypeError; + } + } + return function() { + var args = arguments, + length = funcs.length; + + while (length--) { + args = [funcs[length].apply(this, args)]; + } + return args[0]; + }; + } + + /** + * Creates a function which accepts one or more arguments of `func` that when + * invoked either executes `func` returning its result, if all `func` arguments + * have been provided, or returns a function that accepts one or more of the + * remaining `func` arguments, and so on. The arity of `func` can be specified + * if `func.length` is not sufficient. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @returns {Function} Returns the new curried function. + * @example + * + * var curried = _.curry(function(a, b, c) { + * console.log(a + b + c); + * }); + * + * curried(1)(2)(3); + * // => 6 + * + * curried(1, 2)(3); + * // => 6 + * + * curried(1, 2, 3); + * // => 6 + */ + function curry(func, arity) { + arity = typeof arity == 'number' ? arity : (+arity || func.length); + return createWrapper(func, 4, null, null, null, arity); + } + + /** + * Creates a function that will delay the execution of `func` until after + * `wait` milliseconds have elapsed since the last time it was invoked. + * Provide an options object to indicate that `func` should be invoked on + * the leading and/or trailing edge of the `wait` timeout. Subsequent calls + * to the debounced function will return the result of the last `func` call. + * + * Note: If `leading` and `trailing` options are `true` `func` will be called + * on the trailing edge of the timeout only if the the debounced function is + * invoked more than once during the `wait` timeout. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to debounce. + * @param {number} wait The number of milliseconds to delay. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout. + * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called. + * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // avoid costly calculations while the window size is in flux + * var lazyLayout = _.debounce(calculateLayout, 150); + * jQuery(window).on('resize', lazyLayout); + * + * // execute `sendMail` when the click event is fired, debouncing subsequent calls + * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * }); + * + * // ensure `batchLog` is executed once after 1 second of debounced calls + * var source = new EventSource('/stream'); + * source.addEventListener('message', _.debounce(batchLog, 250, { + * 'maxWait': 1000 + * }, false); + */ + function debounce(func, wait, options) { + var args, + maxTimeoutId, + result, + stamp, + thisArg, + timeoutId, + trailingCall, + lastCalled = 0, + maxWait = false, + trailing = true; + + if (!isFunction(func)) { + throw new TypeError; + } + wait = nativeMax(0, wait) || 0; + if (options === true) { + var leading = true; + trailing = false; + } else if (isObject(options)) { + leading = options.leading; + maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0); + trailing = 'trailing' in options ? options.trailing : trailing; + } + var delayed = function() { + var remaining = wait - (now() - stamp); + if (remaining <= 0) { + if (maxTimeoutId) { + clearTimeout(maxTimeoutId); + } + var isCalled = trailingCall; + maxTimeoutId = timeoutId = trailingCall = undefined; + if (isCalled) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + } else { + timeoutId = setTimeout(delayed, remaining); + } + }; + + var maxDelayed = function() { + if (timeoutId) { + clearTimeout(timeoutId); + } + maxTimeoutId = timeoutId = trailingCall = undefined; + if (trailing || (maxWait !== wait)) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + } + }; + + return function() { + args = arguments; + stamp = now(); + thisArg = this; + trailingCall = trailing && (timeoutId || !leading); + + if (maxWait === false) { + var leadingCall = leading && !timeoutId; + } else { + if (!maxTimeoutId && !leading) { + lastCalled = stamp; + } + var remaining = maxWait - (stamp - lastCalled), + isCalled = remaining <= 0; + + if (isCalled) { + if (maxTimeoutId) { + maxTimeoutId = clearTimeout(maxTimeoutId); + } + lastCalled = stamp; + result = func.apply(thisArg, args); + } + else if (!maxTimeoutId) { + maxTimeoutId = setTimeout(maxDelayed, remaining); + } + } + if (isCalled && timeoutId) { + timeoutId = clearTimeout(timeoutId); + } + else if (!timeoutId && wait !== maxWait) { + timeoutId = setTimeout(delayed, wait); + } + if (leadingCall) { + isCalled = true; + result = func.apply(thisArg, args); + } + if (isCalled && !timeoutId && !maxTimeoutId) { + args = thisArg = null; + } + return result; + }; + } + + /** + * Defers executing the `func` function until the current call stack has cleared. + * Additional arguments will be provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to defer. + * @param {...*} [arg] Arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { console.log(text); }, 'deferred'); + * // logs 'deferred' after one or more milliseconds + */ + function defer(func) { + if (!isFunction(func)) { + throw new TypeError; + } + var args = slice(arguments, 1); + return setTimeout(function() { func.apply(undefined, args); }, 1); + } + + /** + * Executes the `func` function after `wait` milliseconds. Additional arguments + * will be provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay execution. + * @param {...*} [arg] Arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { console.log(text); }, 1000, 'later'); + * // => logs 'later' after one second + */ + function delay(func, wait) { + if (!isFunction(func)) { + throw new TypeError; + } + var args = slice(arguments, 2); + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided it will be used to determine the cache key for storing the result + * based on the arguments provided to the memoized function. By default, the + * first argument provided to the memoized function is used as the cache key. + * The `func` is executed with the `this` binding of the memoized function. + * The result cache is exposed as the `cache` property on the memoized function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] A function used to resolve the cache key. + * @returns {Function} Returns the new memoizing function. + * @example + * + * var fibonacci = _.memoize(function(n) { + * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); + * }); + * + * fibonacci(9) + * // => 34 + * + * var data = { + * 'fred': { 'name': 'fred', 'age': 40 }, + * 'pebbles': { 'name': 'pebbles', 'age': 1 } + * }; + * + * // modifying the result cache + * var get = _.memoize(function(name) { return data[name]; }, _.identity); + * get('pebbles'); + * // => { 'name': 'pebbles', 'age': 1 } + * + * get.cache.pebbles.name = 'penelope'; + * get('pebbles'); + * // => { 'name': 'penelope', 'age': 1 } + */ + function memoize(func, resolver) { + if (!isFunction(func)) { + throw new TypeError; + } + var memoized = function() { + var cache = memoized.cache, + key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0]; + + return hasOwnProperty.call(cache, key) + ? cache[key] + : (cache[key] = func.apply(this, arguments)); + } + memoized.cache = {}; + return memoized; + } + + /** + * Creates a function that is restricted to execute `func` once. Repeat calls to + * the function will return the value of the first call. The `func` is executed + * with the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // `initialize` executes `createApplication` once + */ + function once(func) { + var ran, + result; + + if (!isFunction(func)) { + throw new TypeError; + } + return function() { + if (ran) { + return result; + } + ran = true; + result = func.apply(this, arguments); + + // clear the `func` variable so the function may be garbage collected + func = null; + return result; + }; + } + + /** + * Creates a function that, when called, invokes `func` with any additional + * `partial` arguments prepended to those provided to the new function. This + * method is similar to `_.bind` except it does **not** alter the `this` binding. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { return greeting + ' ' + name; }; + * var hi = _.partial(greet, 'hi'); + * hi('fred'); + * // => 'hi fred' + */ + function partial(func) { + return createWrapper(func, 16, slice(arguments, 1)); + } + + /** + * This method is like `_.partial` except that `partial` arguments are + * appended to those provided to the new function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [arg] Arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var defaultsDeep = _.partialRight(_.merge, _.defaults); + * + * var options = { + * 'variable': 'data', + * 'imports': { 'jq': $ } + * }; + * + * defaultsDeep(options, _.templateSettings); + * + * options.variable + * // => 'data' + * + * options.imports + * // => { '_': _, 'jq': $ } + */ + function partialRight(func) { + return createWrapper(func, 32, null, slice(arguments, 1)); + } + + /** + * Creates a function that, when executed, will only call the `func` function + * at most once per every `wait` milliseconds. Provide an options object to + * indicate that `func` should be invoked on the leading and/or trailing edge + * of the `wait` timeout. Subsequent calls to the throttled function will + * return the result of the last `func` call. + * + * Note: If `leading` and `trailing` options are `true` `func` will be called + * on the trailing edge of the timeout only if the the throttled function is + * invoked more than once during the `wait` timeout. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to throttle. + * @param {number} wait The number of milliseconds to throttle executions to. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // avoid excessively updating the position while scrolling + * var throttled = _.throttle(updatePosition, 100); + * jQuery(window).on('scroll', throttled); + * + * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes + * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { + * 'trailing': false + * })); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (!isFunction(func)) { + throw new TypeError; + } + if (options === false) { + leading = false; + } else if (isObject(options)) { + leading = 'leading' in options ? options.leading : leading; + trailing = 'trailing' in options ? options.trailing : trailing; + } + debounceOptions.leading = leading; + debounceOptions.maxWait = wait; + debounceOptions.trailing = trailing; + + return debounce(func, wait, debounceOptions); + } + + /** + * Creates a function that provides `value` to the wrapper function as its + * first argument. Additional arguments provided to the function are appended + * to those provided to the wrapper function. The wrapper is executed with + * the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {*} value The value to wrap. + * @param {Function} wrapper The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('Fred, Wilma, & Pebbles'); + * // => '

Fred, Wilma, & Pebbles

' + */ + function wrap(value, wrapper) { + return createWrapper(wrapper, 16, [value]); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new function. + * @example + * + * var object = { 'name': 'fred' }; + * var getter = _.constant(object); + * getter() === object; + * // => true + */ + function constant(value) { + return function() { + return value; + }; + } + + /** + * Produces a callback bound to an optional `thisArg`. If `func` is a property + * name the created callback will return the property value for a given element. + * If `func` is an object the created callback will return `true` for elements + * that contain the equivalent object properties, otherwise it will return `false`. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} [func=identity] The value to convert to a callback. + * @param {*} [thisArg] The `this` binding of the created callback. + * @param {number} [argCount] The number of arguments the callback accepts. + * @returns {Function} Returns a callback function. + * @example + * + * var characters = [ + * { 'name': 'barney', 'age': 36 }, + * { 'name': 'fred', 'age': 40 } + * ]; + * + * // wrap to create custom callback shorthands + * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) { + * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback); + * return !match ? func(callback, thisArg) : function(object) { + * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; + * }; + * }); + * + * _.filter(characters, 'age__gt38'); + * // => [{ 'name': 'fred', 'age': 40 }] + */ + function createCallback(func, thisArg, argCount) { + var type = typeof func; + if (func == null || type == 'function') { + return baseCreateCallback(func, thisArg, argCount); + } + // handle "_.pluck" style callback shorthands + if (type != 'object') { + return property(func); + } + var props = keys(func), + key = props[0], + a = func[key]; + + // handle "_.where" style callback shorthands + if (props.length == 1 && a === a && !isObject(a)) { + // fast path the common case of providing an object with a single + // property containing a primitive value + return function(object) { + var b = object[key]; + return a === b && (a !== 0 || (1 / a == 1 / b)); + }; + } + return function(object) { + var length = props.length, + result = false; + + while (length--) { + if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) { + break; + } + } + return result; + }; + } + + /** + * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their + * corresponding HTML entities. + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} string The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('Fred, Wilma, & Pebbles'); + * // => 'Fred, Wilma, & Pebbles' + */ + function escape(string) { + return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar); + } + + /** + * This method returns the first argument provided to it. + * + * @static + * @memberOf _ + * @category Utilities + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'name': 'fred' }; + * _.identity(object) === object; + * // => true + */ + function identity(value) { + return value; + } + + /** + * Adds function properties of a source object to the destination object. + * If `object` is a function methods will be added to its prototype as well. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Function|Object} [object=lodash] object The destination object. + * @param {Object} source The object of functions to add. + * @param {Object} [options] The options object. + * @param {boolean} [options.chain=true] Specify whether the functions added are chainable. + * @example + * + * function capitalize(string) { + * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); + * } + * + * _.mixin({ 'capitalize': capitalize }); + * _.capitalize('fred'); + * // => 'Fred' + * + * _('fred').capitalize().value(); + * // => 'Fred' + * + * _.mixin({ 'capitalize': capitalize }, { 'chain': false }); + * _('fred').capitalize(); + * // => 'Fred' + */ + function mixin(object, source, options) { + var chain = true, + methodNames = source && functions(source); + + if (!source || (!options && !methodNames.length)) { + if (options == null) { + options = source; + } + ctor = lodashWrapper; + source = object; + object = lodash; + methodNames = functions(source); + } + if (options === false) { + chain = false; + } else if (isObject(options) && 'chain' in options) { + chain = options.chain; + } + var ctor = object, + isFunc = isFunction(ctor); + + forEach(methodNames, function(methodName) { + var func = object[methodName] = source[methodName]; + if (isFunc) { + ctor.prototype[methodName] = function() { + var chainAll = this.__chain__, + value = this.__wrapped__, + args = [value]; + + push.apply(args, arguments); + var result = func.apply(object, args); + if (chain || chainAll) { + if (value === result && isObject(result)) { + return this; + } + result = new ctor(result); + result.__chain__ = chainAll; + } + return result; + }; + } + }); + } + + /** + * Reverts the '_' variable to its previous value and returns a reference to + * the `lodash` function. + * + * @static + * @memberOf _ + * @category Utilities + * @returns {Function} Returns the `lodash` function. + * @example + * + * var lodash = _.noConflict(); + */ + function noConflict() { + context._ = oldDash; + return this; + } + + /** + * A no-operation function. + * + * @static + * @memberOf _ + * @category Utilities + * @example + * + * var object = { 'name': 'fred' }; + * _.noop(object) === undefined; + * // => true + */ + function noop() { + // no operation performed + } + + /** + * Gets the number of milliseconds that have elapsed since the Unix epoch + * (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @category Utilities + * @example + * + * var stamp = _.now(); + * _.defer(function() { console.log(_.now() - stamp); }); + * // => logs the number of milliseconds it took for the deferred function to be called + */ + var now = isNative(now = Date.now) && now || function() { + return new Date().getTime(); + }; + + /** + * Converts the given value into an integer of the specified radix. + * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the + * `value` is a hexadecimal, in which case a `radix` of `16` is used. + * + * Note: This method avoids differences in native ES3 and ES5 `parseInt` + * implementations. See http://es5.github.io/#E. + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} value The value to parse. + * @param {number} [radix] The radix used to interpret the value to parse. + * @returns {number} Returns the new integer value. + * @example + * + * _.parseInt('08'); + * // => 8 + */ + var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) { + // Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt` + return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0); + }; + + /** + * Creates a "_.pluck" style function, which returns the `key` value of a + * given object. + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} key The name of the property to retrieve. + * @returns {Function} Returns the new function. + * @example + * + * var characters = [ + * { 'name': 'fred', 'age': 40 }, + * { 'name': 'barney', 'age': 36 } + * ]; + * + * var getName = _.property('name'); + * + * _.map(characters, getName); + * // => ['barney', 'fred'] + * + * _.sortBy(characters, getName); + * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] + */ + function property(key) { + return function(object) { + return object[key]; + }; + } + + /** + * Produces a random number between `min` and `max` (inclusive). If only one + * argument is provided a number between `0` and the given number will be + * returned. If `floating` is truey or either `min` or `max` are floats a + * floating-point number will be returned instead of an integer. + * + * @static + * @memberOf _ + * @category Utilities + * @param {number} [min=0] The minimum possible value. + * @param {number} [max=1] The maximum possible value. + * @param {boolean} [floating=false] Specify returning a floating-point number. + * @returns {number} Returns a random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(min, max, floating) { + var noMin = min == null, + noMax = max == null; + + if (floating == null) { + if (typeof min == 'boolean' && noMax) { + floating = min; + min = 1; + } + else if (!noMax && typeof max == 'boolean') { + floating = max; + noMax = true; + } + } + if (noMin && noMax) { + max = 1; + } + min = +min || 0; + if (noMax) { + max = min; + min = 0; + } else { + max = +max || 0; + } + if (floating || min % 1 || max % 1) { + var rand = nativeRandom(); + return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max); + } + return baseRandom(min, max); + } + + /** + * Resolves the value of property `key` on `object`. If `key` is a function + * it will be invoked with the `this` binding of `object` and its result returned, + * else the property value is returned. If `object` is falsey then `undefined` + * is returned. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Object} object The object to inspect. + * @param {string} key The name of the property to resolve. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { + * 'cheese': 'crumpets', + * 'stuff': function() { + * return 'nonsense'; + * } + * }; + * + * _.result(object, 'cheese'); + * // => 'crumpets' + * + * _.result(object, 'stuff'); + * // => 'nonsense' + */ + function result(object, key) { + if (object) { + var value = object[key]; + return isFunction(value) ? object[key]() : value; + } + } + + /** + * A micro-templating method that handles arbitrary delimiters, preserves + * whitespace, and correctly escapes quotes within interpolated code. + * + * Note: In the development build, `_.template` utilizes sourceURLs for easier + * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl + * + * For more information on precompiling templates see: + * http://lodash.com/custom-builds + * + * For more information on Chrome extension sandboxes see: + * http://developer.chrome.com/stable/extensions/sandboxingEval.html + * + * @static + * @memberOf _ + * @category Utilities + * @param {string} text The template text. + * @param {Object} data The data object used to populate the text. + * @param {Object} [options] The options object. + * @param {RegExp} [options.escape] The "escape" delimiter. + * @param {RegExp} [options.evaluate] The "evaluate" delimiter. + * @param {Object} [options.imports] An object to import into the template as local variables. + * @param {RegExp} [options.interpolate] The "interpolate" delimiter. + * @param {string} [sourceURL] The sourceURL of the template's compiled source. + * @param {string} [variable] The data object variable name. + * @returns {Function|string} Returns a compiled function when no `data` object + * is given, else it returns the interpolated text. + * @example + * + * // using the "interpolate" delimiter to create a compiled template + * var compiled = _.template('hello <%= name %>'); + * compiled({ 'name': 'fred' }); + * // => 'hello fred' + * + * // using the "escape" delimiter to escape HTML in data property values + * _.template('<%- value %>', { 'value': ' + + + + + + + + +
+ + +
+ + +
+ + diff --git a/public_html/twine/test2.html b/public_html/twine/test2.html new file mode 100644 index 0000000..76c780c --- /dev/null +++ b/public_html/twine/test2.html @@ -0,0 +1,3065 @@ + + + + + +Sugarcane + + + + + + + + + + + +
+ + +
+ + +
+ + diff --git a/public_html/twine/twineTest.html b/public_html/twine/twineTest.html new file mode 100644 index 0000000..ca2d73e --- /dev/null +++ b/public_html/twine/twineTest.html @@ -0,0 +1,3065 @@ + + + + + +Sugarcane + + + + + + + + + + + +
+ + +
+ + +
+ + diff --git a/ttitt/krowbar.twee b/ttitt/krowbar.twee new file mode 100644 index 0000000..5cf67da --- /dev/null +++ b/ttitt/krowbar.twee @@ -0,0 +1,43 @@ +:: krowbar-start [start inv] +<> +<>Welcome to the adventure!<> +There is a sealed door on the wall. +<>You see a McGuffin
<>\ +<>You see a few coins on the floor
<>\ +<>\ +<><><>\ +<>[[Go through door|Room2]]<> +[[PlayerProfile]] +[[Return to Hub|Start]] + +:: Get McGuffin +You pick up the McGuffin. +<> +[[Return|previous()]] + +:: Get Coins +You find <<$items['gold'] += random(2,5)>> coins +[[Return|previous()]] + +:: Use McGuffin on door +You use the McGuffin on the door. +The McGuffin crumbles and the door opens. +<> +[[Return|previous()]] + +:: Room2 [inv] +This is room2. There is a cake on the ground. +The door ahead is blocked. +<> +<>[[Break through the door|Room3]] +<>You are not strong enough to break this door.<> + +::Eat cake +You feel incredibly stronger! +Strength increased to <<$stats['strength'] += 3>> +[[Return|previous()]] + +:: Room3 [inv] +Seriously, nothing here. +Return to [[the start|Start]] + diff --git a/ttitt/macros.twee b/ttitt/macros.twee new file mode 100644 index 0000000..001529e --- /dev/null +++ b/ttitt/macros.twee @@ -0,0 +1,168 @@ +:: Inventory +
+Inventory: +<> + +:: ShowInventory [script] +try { + version.extensions['Inventory'] = { + major:0, minor:1, revision:0 + }; + macros['Inventory'] = + { + handler: function(place, macroName, params, parser) + { + var msg = ""; + var items = state.history[0].variables.items; + if (items == undefined) { + new Wikifier(place, "nothing"); + return; + } + for(var name in items) { + if(!isNaN(parseFloat(items[name])) && isFinite(items[name])) { + msg += name + "(" + items[name] + "), "; + } + else if(items[name] != false) { + msg += name + ", "; + } + }; + new Wikifier(place, msg.slice(0,-2)); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"Inventory Setup Error: " + e.message); +} + +:: PlayerStats +
+Player Stats: +<> + +:: ShowPlayerStats [script] +try { + version.extensions['PlayerStats'] = { + major:0, minor:1, revision:0 + }; + macros['PlayerStats'] = + { + handler: function(place, macroName, params, parser) + { + var msg = ""; + var stats = state.history[0].variables.stats; + if (stats == undefined) { + new Wikifier(place, "no stats"); + return; + } + for(var stat in stats) { + if(stat.slice(-4) == "_max") { + continue; + } + msg += stat + ": " + stats[stat]; + if(stats[stat+"_max"] != undefined) { + msg += " / " + stats[stat+"_max"]; + } + msg += "
"; + } + new Wikifier(place, msg); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"PlayerStats Setup Error: " + e.message); +} + +:: PlayerSkills +
+Player Skills: +<> + +:: ShowPlayerSkills [script] +try { + version.extensions['PlayerSkills'] = { + major:0, minor:1, revision:0 + }; + macros['PlayerSkills'] = + { + handler: function(place, macroName, params, parser) + { + var msg = ""; + var stats = state.history[0].variables.skills; + if (stats == undefined) { + new Wikifier(place, "no skills"); + return; + } + for(var stat in stats) { + msg += stat + ": " + stats[stat]+"
"; + } + new Wikifier(place, msg); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"PlayerSkills Setup Error: " + e.message); +} + +:: PlayerProfile +[[Return|previous()]] +-~-~-~-~-~- +<> +<> +<> + +:: postrender [script] +postrender.tagInventory = function(place) { + var inv = tale.get("Inventory"); + if (inv.id !== undefined && ~this.tags.indexOf("inv")) { + new Wikifier(place, inv.processText()); + }; + var stats = tale.get("PlayerStats"); + if(stats.id !== undefined && ~this.tags.indexOf("stats")) { + new Wikifier(place, stats.processText()); + }; + var skills = tale.get("PlayerSkills"); + if(skills.id !== undefined && ~this.tags.indexOf("skills")) { + new Wikifier(place, skills.processText()); + }; +} + +:: core-init +<> +<> +<> +<> +<> +<> +<> +<> +<> +<> +<> +<> +<> +<> + +:: GetInit [script] +try { + version.extensions['GetInit'] = { + major:0, minor:1, revision:0 + }; + macros['Init'] = + { + handler: function(place, macroName, params, parser) + { + var msg = "<><>"; + for(var p in tale.passages) { + /%if(~tale.passages[p].tags.indexOf("init")) {%/ + if(p.slice(-5) == "-init") { + msg += "<>"; + } + } + msg += "<><>"; + new Wikifier(place, msg); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"GetInit Setup Error: " + e.message); +} diff --git a/twine/global.twee b/twine/global.twee new file mode 100644 index 0000000..0dcdeb2 --- /dev/null +++ b/twine/global.twee @@ -0,0 +1,185 @@ +:: Start +[[Start Adventure|krowbar-start]] +Visited <> times. +<> +<> +<> +<> +<> +<> +<> +<> +<> +<> +<> +<> + +:: krowbar-start [start inv] +<>Welcome to the adventure!<> +There is a door on the wall. +<>You see a McGuffin<> +<>You see a few coins on the floor<> +<>\ +<><><>\ +<>[[Go through door|Room2]]<> +[[PlayerProfile]] +<> + +:: Get McGuffin +You pick up the McGuffin. +<> +[[Return|previous()]] + +:: Get Coins +You pick up the coins. +<> +[[Return|previous()]] + +:: Use McGuffin on door +You use the McGuffin on the door. +The McGuffin crumbles and the door opens. +<> +[[Return|previous()]] + +:: Room2 [inv] +This is room2. There is a cake on the ground. +The door ahead is blocked. +<> +<>[[Break through the door|Room3]] +<>You are not strong enough to break this door.<> + +::Eat cake +You feel incredibly stronger! +Strength increased to <<$stats['strength'] += 3>> +[[Return|previous()]] + +:: Room3 [inv] +Seriously, nothing here. + +:: Inventory +
+Inventory: +<> + +:: ShowInventory [script] +try { + version.extensions['Inventory'] = { + major:0, minor:1, revision:0 + }; + macros['Inventory'] = + { + handler: function(place, macroName, params, parser) + { + var msg = ""; + var items = state.history[0].variables.items; + if (items == undefined) { + new Wikifier(place, "nothing"); + return; + } + for(var name in items) { + if(!isNaN(parseFloat(items[name])) && isFinite(items[name])) { + msg += name + "(" + items[name] + "), "; + } + else if(items[name] != false) { + msg += name + ", "; + } + }; + new Wikifier(place, msg.slice(0,-2)); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"Inventory Setup Error: " + e.message); +} + +:: PlayerStats +
+Player Stats: +<> + +:: ShowPlayerStats [script] +try { + version.extensions['PlayerStats'] = { + major:0, minor:1, revision:0 + }; + macros['PlayerStats'] = + { + handler: function(place, macroName, params, parser) + { + var msg = ""; + var stats = state.history[0].variables.stats; + if (stats == undefined) { + new Wikifier(place, "no stats"); + return; + } + for(var stat in stats) { + if(stat.slice(-4) == "_max") { + continue; + } + msg += stat + ": " + stats[stat]; + if(stats[stat+"_max"] != undefined) { + msg += " / " + stats[stat+"_max"]; + } + msg += "
"; + } + new Wikifier(place, msg); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"PlayerStats Setup Error: " + e.message); +} + +:: PlayerSkills +
+Player Skills: +<> + +:: ShowPlayerSkills [script] +try { + version.extensions['PlayerSkills'] = { + major:0, minor:1, revision:0 + }; + macros['PlayerSkills'] = + { + handler: function(place, macroName, params, parser) + { + var msg = ""; + var stats = state.history[0].variables.skills; + if (stats == undefined) { + new Wikifier(place, "no skills"); + return; + } + for(var stat in stats) { + msg += stat + ": " + stats[stat]+"
"; + } + new Wikifier(place, msg); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"PlayerSkills Setup Error: " + e.message); +} + +:: PlayerProfile +[[Return|previous()]] +-~-~-~-~-~- +<> +<> +<> + +:: postrender [script] +postrender.tagInventory = function(place) { + var inv = tale.get("Inventory"); + if (inv.id !== undefined && ~this.tags.indexOf("inv")) { + new Wikifier(place, inv.processText()); + }; + var stats = tale.get("PlayerStats"); + if(stats.id !== undefined && ~this.tags.indexOf("stats")) { + new Wikifier(place, stats.processText()); + }; + var skills = tale.get("PlayerSkills"); + if(skills.id !== undefined && ~this.tags.indexOf("skills")) { + new Wikifier(place, skills.processText()); + }; +} diff --git a/twine/global.twee.bak b/twine/global.twee.bak new file mode 100644 index 0000000..a592093 --- /dev/null +++ b/twine/global.twee.bak @@ -0,0 +1,174 @@ +:: Start +[[Start Adventure|krowbar-start]] +<> +<> +<> +<> +<> +<> +<> +<> +<> +<> +<> + +:: krowbar-start [start inv stats skills] +<>Welcome to the adventure!<> +There is a door on the wall. +<>You see a McGuffin<> +<>You see a few coins on the floor<> +<>\ +<><><>\ +<>[[Go through door|Room2]]<> +[[PlayerProfile]] + +:: Get McGuffin +You pick up the McGuffin. +<> +[[Return|previous()]] + +:: Get Coins +You pick up the coins. +<> +[[Return|previous()]] + +:: Use McGuffin on door +You use the McGuffin on the door. +The McGuffin crumbles and the door opens. +<> +[[Return|previous()]] + +:: Room2 [inv] +This is room2. There is nothing here. +[[Go to room3|Room3]] + +:: Room3 [inv] +Seriously, nothing here. + +:: Inventory +
+Inventory: +<> + +:: ShowInventory [script] +try { + version.extensions['Inventory'] = { + major:0, minor:1, revision:0 + }; + macros['Inventory'] = + { + handler: function(place, macroName, params, parser) + { + var msg = ""; + var items = state.history[0].variables.items; + if (items == undefined) { + new Wikifier(place, "nothing"); + return; + } + for(var name in items) { + if(!isNaN(parseFloat(items[name])) && isFinite(items[name])) { + msg += name + "(" + items[name] + "), "; + } + else if(items[name] != false) { + msg += name + ", "; + } + }; + new Wikifier(place, msg.slice(0,-2)); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"Inventory Setup Error: " + e.message); +} + +:: PlayerStats +
+Player Stats: +<> + +:: ShowPlayerStats [script] +try { + version.extensions['PlayerStats'] = { + major:0, minor:1, revision:0 + }; + macros['PlayerStats'] = + { + handler: function(place, macroName, params, parser) + { + var msg = ""; + var stats = state.history[0].variables.stats; + if (stats == undefined) { + new Wikifier(place, "no stats"); + return; + } + for(var stat in stats) { + if(stat.slice(-4) == "_max") { + continue; + } + msg += stat + ": " + stats[stat]; + if(stats[stat+"_max"] != undefined) { + msg += " / " + stats[stat+"_max"]; + } + msg += "
"; + } + new Wikifier(place, msg); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"PlayerStats Setup Error: " + e.message); +} + +:: PlayerSkills +
+Player Skills: +<> + +:: ShowPlayerSkills [script] +try { + version.extensions['PlayerSkills'] = { + major:0, minor:1, revision:0 + }; + macros['PlayerSkills'] = + { + handler: function(place, macroName, params, parser) + { + var msg = ""; + var stats = state.history[0].variables.skills; + if (stats == undefined) { + new Wikifier(place, "no skills"); + return; + } + for(var stat in stats) { + msg += stat + ": " + stats[stat]+"
"; + } + new Wikifier(place, msg); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"PlayerSkills Setup Error: " + e.message); +} + +:: PlayerProfile +[[Return|previous()]] +-~-~-~-~-~- +<> +<> +<> + +:: postrender [script] +postrender.tagInventory = function(place) { + var inv = tale.get("Inventory"); + if (inv.id !== undefined && ~this.tags.indexOf("inv")) { + new Wikifier(place, inv.processText()); + }; + var stats = tale.get("PlayerStats"); + if(stats.id !== undefined && ~this.tags.indexOf("stats")) { + new Wikifier(place, stats.processText()); + }; + var skills = tale.get("PlayerSkills"); + if(skills.id !== undefined && ~this.tags.indexOf("skills")) { + new Wikifier(place, skills.processText()); + }; +} diff --git a/twine/krowbar.twee b/twine/krowbar.twee new file mode 100644 index 0000000..da1bb5d --- /dev/null +++ b/twine/krowbar.twee @@ -0,0 +1,194 @@ +:: Start +[[krowbar-start]] + +:: Set Globals [script] +try { + macros['SetGlobals'] = + { + handler: function(place, macroName, params, parser) + { + }, + + var gVars = state.history[0].variables; + gVars.items = {}; + gVars.items['gold'] = 0; + gVars.events = {}; + gVars.stats = {}; + gVars.stats['health'] = 10; + gVars.stats['health_max'] = 10; + gVars.stats['strength'] = 1; + gVars.skills = {}; + gVars.skills['adventuring'] = 2; +} catch(e) { + console.log("Error during Globals setup: " + e.message); +} + +:: krowbar-start [start inv] +<>Welcome to the adventure!<> +There is a door on the wall. +<>You see a McGuffin<> +<>You see a few coins on the floor<> +<>\ +<><><>\ +<>[[Go through door|Room2]]<> +[[PlayerProfile]] + +:: Get McGuffin +You pick up the McGuffin. +<> +[[Return|previous()]] + +:: Get Coins +You pick up the coins. +<> +[[Return|previous()]] + +:: Use McGuffin on door +You use the McGuffin on the door. +The McGuffin crumbles and the door opens. +<> +[[Return|previous()]] + +:: Room2 [inv] +This is room2. There is a cake on the ground. +The door ahead is blocked. +<> +<>[[Break through the door|Room3]] +<>You are not strong enough to break this door.<> + +::Eat cake +You feel incredibly stronger! +Strength increased to <<$stats['strength'] += 3>> +[[Return|previous()]] + +:: Room3 [inv] +Seriously, nothing here. +Return to [[the start|Start]] + +:: Inventory +
+Inventory: +<> + +:: ShowInventory [script] +try { + version.extensions['Inventory'] = { + major:0, minor:1, revision:0 + }; + macros['Inventory'] = + { + handler: function(place, macroName, params, parser) + { + var msg = ""; + var items = state.history[0].variables.items; + if (items == undefined) { + new Wikifier(place, "nothing"); + return; + } + for(var name in items) { + if(!isNaN(parseFloat(items[name])) && isFinite(items[name])) { + msg += name + "(" + items[name] + "), "; + } + else if(items[name] != false) { + msg += name + ", "; + } + }; + new Wikifier(place, msg.slice(0,-2)); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"Inventory Setup Error: " + e.message); +} + +:: PlayerStats +
+Player Stats: +<> + +:: ShowPlayerStats [script] +try { + version.extensions['PlayerStats'] = { + major:0, minor:1, revision:0 + }; + macros['PlayerStats'] = + { + handler: function(place, macroName, params, parser) + { + var msg = ""; + var stats = state.history[0].variables.stats; + if (stats == undefined) { + new Wikifier(place, "no stats"); + return; + } + for(var stat in stats) { + if(stat.slice(-4) == "_max") { + continue; + } + msg += stat + ": " + stats[stat]; + if(stats[stat+"_max"] != undefined) { + msg += " / " + stats[stat+"_max"]; + } + msg += "
"; + } + new Wikifier(place, msg); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"PlayerStats Setup Error: " + e.message); +} + +:: PlayerSkills +
+Player Skills: +<> + +:: ShowPlayerSkills [script] +try { + version.extensions['PlayerSkills'] = { + major:0, minor:1, revision:0 + }; + macros['PlayerSkills'] = + { + handler: function(place, macroName, params, parser) + { + var msg = ""; + var stats = state.history[0].variables.skills; + if (stats == undefined) { + new Wikifier(place, "no skills"); + return; + } + for(var stat in stats) { + msg += stat + ": " + stats[stat]+"
"; + } + new Wikifier(place, msg); + }, + init: function() { }, + }; +} catch(e) { + throwError(place,"PlayerSkills Setup Error: " + e.message); +} + +:: PlayerProfile +[[Return|previous()]] +-~-~-~-~-~- +<> +<> +<> + +:: postrender [script] +postrender.tagInventory = function(place) { + var inv = tale.get("Inventory"); + if (inv.id !== undefined && ~this.tags.indexOf("inv")) { + new Wikifier(place, inv.processText()); + }; + var stats = tale.get("PlayerStats"); + if(stats.id !== undefined && ~this.tags.indexOf("stats")) { + new Wikifier(place, stats.processText()); + }; + var skills = tale.get("PlayerSkills"); + if(skills.id !== undefined && ~this.tags.indexOf("skills")) { + new Wikifier(place, skills.processText()); + }; +} diff --git a/twine/test_visited.twee b/twine/test_visited.twee new file mode 100644 index 0000000..cd744ae --- /dev/null +++ b/twine/test_visited.twee @@ -0,0 +1,45 @@ +:: Start +<> + +:: krowbar-start [start] +<> +<> + +Here is the start page. +There is a door on the wall. +<> +<> +<> +<> +<> +[[Go through door|Room2]] +<> +<> + +:: item_mcguffin +<> +You see a McGuffin. +<> +<> + +:: Get McGuffin +You pick up the McGuffin. +[[Return|previous()]] + +:: Use McGuffin on door +You use the McGuffin on the door. +The McGuffin crumbles and the door opens. +<> +[[Return|Start]] +[[Go through door|Room2]] + +:: Room2 +This is room2. There is nothing here. +[[Go back to the start|Start]] + +:: Inventory +Inventory: +<> +<> +<> +<> diff --git a/twine/twineGuidelines.txt b/twine/twineGuidelines.txt new file mode 100644 index 0000000..e6762ed --- /dev/null +++ b/twine/twineGuidelines.txt @@ -0,0 +1,36 @@ +Here are some of my thoughts on our Twine story guidelines + +## The Player ## +* Should have global objects for $items, $events, $stats, and $skills that any + story could modify + +## Player Inventory ## +* Global inventory items should be of the form +* Per-story inventory items should be of the form +* To pick up an item, use the <> +* To check if a player has already retrieved an item, either check the +* $items['NAME'] value or check "visited("Get NAME")" +* An item can be added to the global items hash with the following + $items['NAME'] = VALUE +* A unique item, like "gearbox" or "sword", will have VALUE of true +* When a unique items is used up or destroyed, set its value to false +* Generic items that the player can have many of, like "gold" or "smallKey", + will have a numerical value + +## Player Stats and Skills ## +* Are persistant between stories +* Are stored as + $stat.{name} = {value} + $skill.{name} = {value} + +## The Hub ## +* Should heal the player +* Should be able to tell the player their stats/skills + +## Rules for all stories ## +* All stories should have a path that leads back to the hub +* Stories can NOT kill the player +** Alternately, we could allow player death to 'port them to the Hub +* Stories should not cause the player to lose or use up global objects +** An exception to this could be gold or money +* Should not decrease a stat or skill